// применяет SQL из бинарника ровно один раз на файл. package migrate import ( "context" "fmt" "io/fs" "sort" "strings" "github.com/jackc/pgx/v5/pgxpool" "messenger/migrations" ) // Создаёт schema_migrations и выполняет ещё не записанные файлы. // Повторный запуск не исполняет уже применённый SQL и не дублирует строки. func Apply(ctx context.Context, pool *pgxpool.Pool) error { _, err := pool.Exec(ctx, ` CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() )`) if err != nil { return fmt.Errorf("schema_migrations: %w", err) } entries, err := fs.ReadDir(migrations.FS, ".") if err != nil { return err } names := make([]string, 0, len(entries)) for _, entry := range entries { if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { continue } names = append(names, entry.Name()) } sort.Strings(names) for _, name := range names { var applied bool if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&applied); err != nil { return err } if applied { continue } body, err := fs.ReadFile(migrations.FS, name) if err != nil { return err } tx, err := pool.Begin(ctx) if err != nil { return err } if _, err := tx.Exec(ctx, string(body)); err != nil { _ = tx.Rollback(ctx) return fmt.Errorf("%s: %w", name, err) } if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil { _ = tx.Rollback(ctx) return err } if err := tx.Commit(ctx); err != nil { return err } } return nil }