mirror of https://github.com/status-im/migrate.git
postgres: Make `ensureVersionTable` atomic
Fixes https://github.com/golang-migrate/migrate/issues/55
This commit is contained in:
parent
ce7a2234ee
commit
519dae2639
|
@ -332,20 +332,19 @@ func (p *Postgres) Drop() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Postgres) ensureVersionTable() error {
|
func (p *Postgres) ensureVersionTable() (err error) {
|
||||||
// check if migration table exists
|
if err = p.Lock(); err != nil {
|
||||||
var count int
|
return err
|
||||||
query := `SELECT COUNT(1) FROM information_schema.tables WHERE table_name = $1 AND table_schema = (SELECT current_schema()) LIMIT 1`
|
|
||||||
if err := p.conn.QueryRowContext(context.Background(), query, p.config.MigrationsTable).Scan(&count); err != nil {
|
|
||||||
return &database.Error{OrigErr: err, Query: []byte(query)}
|
|
||||||
}
|
|
||||||
if count == 1 {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// if not, create the empty migration table
|
defer func() {
|
||||||
query = `CREATE TABLE "` + p.config.MigrationsTable + `" (version bigint not null primary key, dirty boolean not null)`
|
if e := p.Unlock(); err == nil {
|
||||||
if _, err := p.conn.ExecContext(context.Background(), query); err != nil {
|
err = e
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
query := `CREATE TABLE IF NOT EXISTS "` + p.config.MigrationsTable + `" (version bigint not null primary key, dirty boolean not null)`
|
||||||
|
if _, err = p.conn.ExecContext(context.Background(), query); err != nil {
|
||||||
return &database.Error{OrigErr: err, Query: []byte(query)}
|
return &database.Error{OrigErr: err, Query: []byte(query)}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
Loading…
Reference in New Issue