Ошибка получения: невозможно получить блокировку при попытке выполнить миграцию с помощью golang-migrate в базу данных postgres - PullRequest
0 голосов
/ 02 апреля 2019

Я пытаюсь перейти с помощью golang на базу данных postgres, используя библиотеку "github.com/golang-migrate/migrate/v4"

Я получил ошибку, подобную приведенному ниже.

base_test.go:79: Migrating postgres://db:db@localhost:65432/testdb?sslmode=disable from file:///Users/clouds/CitraOffice/cdl/oa/judel/migrations/test
base_test.go:88: can't acquire lock

здесь подготовлена ​​функция b для миграции, эта функцияя вызвал тест для переноса теста:

func PrepareDB() {
    if dbConnPool != nil {
        return
    }
    log.SetFlags(log.Lshortfile)

    configFile := os.Getenv("CONFIG_FILE")
    if configFile == "" {
        configFile = "./configs/config.json"
    }
    viper.SetConfigFile(configFile)
    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }

    conf := viper.Sub("dev")
    port := uint16(conf.GetInt("dbPort"))
    host := conf.GetString("dbHost")
    user := conf.GetString("dbUser")
    pass := conf.GetString("dbPass")
    dbName = conf.GetString("dbName")
    redisHost := conf.GetString("redisHost")
    redisPort := conf.GetString("redisPort")

    hostOvr := os.Getenv("_DBHOST")
    if hostOvr != "" {
        host = hostOvr
    }

    portOvr := os.Getenv("_DBPORT")
    if portOvr != "" {
        portX, err := strconv.Atoi(portOvr)
        if err != nil {
            log.Fatal(err)
        }
        port = uint16(portX)
    }

    migrationPath := "file://" + os.Getenv("MIGRATION_PATH")
    if migrationPath == "file://" {
        log.Println("MIGRATION_PATH environment is not set, using default value")
        cwd, _ := filepath.Abs(filepath.Dir(os.Args[0]))
        migrationPath = "file://" + cwd + "/migrations/test"
    }

    url := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", user, pass, host, port, dbName)
    log.Println(fmt.Sprintf("Migrating %s from %s", url, migrationPath))
    m, err := migrate.New(
        migrationPath,
        url)
    if err != nil {
        log.Fatal(err)
    }
    err = m.Drop()
    if err != nil && err.Error() != "no change" {
        log.Fatal(err)
    }
    err = m.Up()
    if err != nil && err.Error() != "no change" {
        log.Fatal(err)
    }

    pgxConf := &pgx.ConnConfig{
        Port:     port,
        Host:     host,
        User:     user,
        Password: pass,
        Database: dbName,
    }
    pgxPoolConf := pgx.ConnPoolConfig{
        ConnConfig:     *pgxConf,
        MaxConnections: 5,
    }
    dbConnPool, err = pgx.NewConnPool(pgxPoolConf)
    if err != nil {
        panic(err)
    }
}

и вот моя схема базы данных, я создаю ее из postgres cli, затем экспортирую ее с помощью pg_dump для повторной попытки миграции в базу данных:

--
-- PostgreSQL database dump
--

-- Dumped from database version 11.2
-- Dumped by pg_dump version 11.2

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: pgcrypto; Type: EXTENSION; Schema: -; Owner: 
--

CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;


--
-- Name: EXTENSION pgcrypto; Type: COMMENT; Schema: -; Owner: 
--

COMMENT ON EXTENSION pgcrypto IS 'cryptographic functions';


SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: variant; Type: TABLE; Schema: public; Owner: clouds
--

CREATE TABLE public.variant (
    id integer NOT NULL,
    project_id character varying(255) NOT NULL,
    variant_name character varying(255) NOT NULL,
    variant_release_version character varying(255) NOT NULL,
    repo_url character varying(255) NOT NULL,
    state character varying(255) NOT NULL,
    created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP
);


ALTER TABLE public.variant OWNER TO clouds;

--
-- Name: variant_id_seq; Type: SEQUENCE; Schema: public; Owner: clouds
--

CREATE SEQUENCE public.variant_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER TABLE public.variant_id_seq OWNER TO clouds;

--
-- Name: variant_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: clouds
--

ALTER SEQUENCE public.variant_id_seq OWNED BY public.variant.id;


--
-- Name: variant id; Type: DEFAULT; Schema: public; Owner: clouds
--

ALTER TABLE ONLY public.variant ALTER COLUMN id SET DEFAULT nextval('public.variant_id_seq'::regclass);


--
-- Data for Name: variant; Type: TABLE DATA; Schema: public; Owner: clouds
--

COPY public.variant (id, project_id, variant_name, variant_release_version, repo_url, state, created_at) FROM stdin;
1   123 auth    stagging    https://repo.dev.citra.digital  test    2019-04-02 17:46:30.886344
2   345 release release https://repo.dev.citra.digital  test    2019-04-02 17:47:03.258495
\.


--
-- Name: variant_id_seq; Type: SEQUENCE SET; Schema: public; Owner: clouds
--

SELECT pg_catalog.setval('public.variant_id_seq', 2, true);


--
-- Name: variant variant_pkey; Type: CONSTRAINT; Schema: public; Owner: clouds
--

ALTER TABLE ONLY public.variant
    ADD CONSTRAINT variant_pkey PRIMARY KEY (id);


--
-- PostgreSQL database dump complete
--

...