|
| 1 | +package migrator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + pgx "github.com/jackc/pgx/v5" |
| 9 | + pgconn "github.com/jackc/pgx/v5/pgconn" |
| 10 | +) |
| 11 | + |
| 12 | +// PgxIface is interface for database connection or transaction |
| 13 | +type PgxIface interface { |
| 14 | + Begin(ctx context.Context) (pgx.Tx, error) |
| 15 | + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) |
| 16 | + QueryRow(context.Context, string, ...interface{}) pgx.Row |
| 17 | + Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) |
| 18 | + Ping(ctx context.Context) error |
| 19 | +} |
| 20 | + |
| 21 | +const defaultTableName = "migrations" |
| 22 | + |
| 23 | +// Migrator is the migrator implementation |
| 24 | +type Migrator struct { |
| 25 | + TableName string |
| 26 | + migrations []interface{} |
| 27 | + onNotice func(string) |
| 28 | +} |
| 29 | + |
| 30 | +// Option sets options such migrations or table name. |
| 31 | +type Option func(*Migrator) |
| 32 | + |
| 33 | +// TableName creates an option to allow overriding the default table name |
| 34 | +func TableName(tableName string) Option { |
| 35 | + return func(m *Migrator) { |
| 36 | + m.TableName = tableName |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// SetNotice overrides the default standard output function |
| 41 | +func SetNotice(noticeFunc func(string)) Option { |
| 42 | + return func(m *Migrator) { |
| 43 | + m.onNotice = noticeFunc |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +// Migrations creates an option with provided migrations |
| 48 | +func Migrations(migrations ...interface{}) Option { |
| 49 | + return func(m *Migrator) { |
| 50 | + m.migrations = migrations |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// New creates a new migrator instance |
| 55 | +func New(opts ...Option) (*Migrator, error) { |
| 56 | + m := &Migrator{ |
| 57 | + TableName: defaultTableName, |
| 58 | + onNotice: func(msg string) { |
| 59 | + fmt.Println(msg) |
| 60 | + }, |
| 61 | + } |
| 62 | + for _, opt := range opts { |
| 63 | + opt(m) |
| 64 | + } |
| 65 | + |
| 66 | + if len(m.migrations) == 0 { |
| 67 | + return nil, errors.New("Migrations must be provided") |
| 68 | + } |
| 69 | + |
| 70 | + for _, m := range m.migrations { |
| 71 | + switch m.(type) { |
| 72 | + case *Migration: |
| 73 | + case *MigrationNoTx: |
| 74 | + default: |
| 75 | + return nil, errors.New("Invalid migration type") |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + return m, nil |
| 80 | +} |
| 81 | + |
| 82 | +// Migrate applies all available migrations |
| 83 | +func (m *Migrator) Migrate(ctx context.Context, db PgxIface) error { |
| 84 | + // create migrations table if doesn't exist |
| 85 | + _, err := db.Exec(ctx, fmt.Sprintf(` |
| 86 | + CREATE TABLE IF NOT EXISTS %s ( |
| 87 | + id INT8 NOT NULL, |
| 88 | + version TEXT NOT NULL, |
| 89 | + PRIMARY KEY (id) |
| 90 | + ); |
| 91 | + `, m.TableName)) |
| 92 | + if err != nil { |
| 93 | + return err |
| 94 | + } |
| 95 | + |
| 96 | + pm, count, err := m.Pending(ctx, db) |
| 97 | + if err != nil { |
| 98 | + return err |
| 99 | + } |
| 100 | + |
| 101 | + // plan migrations |
| 102 | + for idx, migration := range pm { |
| 103 | + insertVersion := fmt.Sprintf("INSERT INTO %s (id, version) VALUES (%d, '%s')", m.TableName, idx+count, migration.(fmt.Stringer).String()) |
| 104 | + switch mm := migration.(type) { |
| 105 | + case *Migration: |
| 106 | + if err := migrate(ctx, db, insertVersion, mm, m.onNotice); err != nil { |
| 107 | + return fmt.Errorf("Error while running migrations: %w", err) |
| 108 | + } |
| 109 | + case *MigrationNoTx: |
| 110 | + if err := migrateNoTx(ctx, db, insertVersion, mm, m.onNotice); err != nil { |
| 111 | + return fmt.Errorf("Error while running migrations: %w", err) |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + return nil |
| 117 | +} |
| 118 | + |
| 119 | +// Pending returns all pending (not yet applied) migrations and count of migration applied |
| 120 | +func (m *Migrator) Pending(ctx context.Context, db PgxIface) ([]interface{}, int, error) { |
| 121 | + count, err := countApplied(ctx, db, m.TableName) |
| 122 | + if err != nil { |
| 123 | + return nil, 0, err |
| 124 | + } |
| 125 | + if count > len(m.migrations) { |
| 126 | + count = len(m.migrations) |
| 127 | + } |
| 128 | + return m.migrations[count:len(m.migrations)], count, nil |
| 129 | +} |
| 130 | + |
| 131 | +// NeedUpgrade returns True if database need to be updated with migrations |
| 132 | +func (m *Migrator) NeedUpgrade(ctx context.Context, db PgxIface) (bool, error) { |
| 133 | + exists, err := tableExists(ctx, db, m.TableName) |
| 134 | + if !exists { |
| 135 | + return true, err |
| 136 | + } |
| 137 | + mm, _, err := m.Pending(ctx, db) |
| 138 | + return len(mm) > 0, err |
| 139 | +} |
| 140 | + |
| 141 | +func countApplied(ctx context.Context, db PgxIface, tableName string) (int, error) { |
| 142 | + // count applied migrations |
| 143 | + var count int |
| 144 | + err := db.QueryRow(ctx, fmt.Sprintf("SELECT count(*) FROM %s", tableName)).Scan(&count) |
| 145 | + if err != nil { |
| 146 | + return 0, err |
| 147 | + } |
| 148 | + return count, nil |
| 149 | +} |
| 150 | + |
| 151 | +func tableExists(ctx context.Context, db PgxIface, tableName string) (bool, error) { |
| 152 | + var exists bool |
| 153 | + err := db.QueryRow(ctx, "SELECT to_regclass($1) IS NOT NULL", tableName).Scan(&exists) |
| 154 | + if err != nil { |
| 155 | + return false, err |
| 156 | + } |
| 157 | + return exists, nil |
| 158 | +} |
| 159 | + |
| 160 | +// Migration represents a single migration |
| 161 | +type Migration struct { |
| 162 | + Name string |
| 163 | + Func func(context.Context, pgx.Tx) error |
| 164 | +} |
| 165 | + |
| 166 | +// String returns a string representation of the migration |
| 167 | +func (m *Migration) String() string { |
| 168 | + return m.Name |
| 169 | +} |
| 170 | + |
| 171 | +// MigrationNoTx represents a single not transactional migration |
| 172 | +type MigrationNoTx struct { |
| 173 | + Name string |
| 174 | + Func func(context.Context, PgxIface) error |
| 175 | +} |
| 176 | + |
| 177 | +func (m *MigrationNoTx) String() string { |
| 178 | + return m.Name |
| 179 | +} |
| 180 | + |
| 181 | +func migrate(ctx context.Context, db PgxIface, insertVersion string, migration *Migration, notice func(string)) error { |
| 182 | + tx, err := db.Begin(ctx) |
| 183 | + if err != nil { |
| 184 | + return err |
| 185 | + } |
| 186 | + defer func() { |
| 187 | + if err != nil { |
| 188 | + if errRb := tx.Rollback(ctx); errRb != nil { |
| 189 | + err = fmt.Errorf("Error rolling back: %s\n%s", errRb, err) |
| 190 | + } |
| 191 | + return |
| 192 | + } |
| 193 | + err = tx.Commit(ctx) |
| 194 | + }() |
| 195 | + notice(fmt.Sprintf("Applying migration named '%s'...", migration.Name)) |
| 196 | + if err = migration.Func(ctx, tx); err != nil { |
| 197 | + return fmt.Errorf("Error executing golang migration: %w", err) |
| 198 | + } |
| 199 | + if _, err = tx.Exec(ctx, insertVersion); err != nil { |
| 200 | + return fmt.Errorf("Error updating migration versions: %w", err) |
| 201 | + } |
| 202 | + notice(fmt.Sprintf("Applied migration named '%s'", migration.Name)) |
| 203 | + |
| 204 | + return err |
| 205 | +} |
| 206 | + |
| 207 | +func migrateNoTx(ctx context.Context, db PgxIface, insertVersion string, migration *MigrationNoTx, notice func(string)) error { |
| 208 | + notice(fmt.Sprintf("Applying no tx migration named '%s'...", migration.Name)) |
| 209 | + if err := migration.Func(ctx, db); err != nil { |
| 210 | + return fmt.Errorf("Error executing golang migration: %w", err) |
| 211 | + } |
| 212 | + if _, err := db.Exec(ctx, insertVersion); err != nil { |
| 213 | + return fmt.Errorf("Error updating migration versions: %w", err) |
| 214 | + } |
| 215 | + notice(fmt.Sprintf("Applied no tx migration named '%s'...", migration.Name)) |
| 216 | + |
| 217 | + return nil |
| 218 | +} |
0 commit comments