package database import ( "context" _ "embed" "github.com/jackc/pgx/v5/pgxpool" ) //go:embed 001_identity.sql var identityMigration string //go:embed 002_contacts.sql var contactsMigration string func Migrate(ctx context.Context, pool *pgxpool.Pool) error { tx, err := pool.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(749109272)"); err != nil { return err } if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil { return err } for index, migration := range []string{identityMigration, contactsMigration} { version := index + 1 var applied bool if err = tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version=$1)", version).Scan(&applied); err != nil { return err } if applied { continue } if _, err = tx.Exec(ctx, migration); err != nil { return err } if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations VALUES ($1)", version); err != nil { return err } } return tx.Commit(ctx) }