Migrate runs all pending migrations
(ctx context.Context)
| 118 | |
| 119 | // Migrate runs all pending migrations |
| 120 | func (m *Migrator) Migrate(ctx context.Context) error { |
| 121 | // Ensure the migrations table exists |
| 122 | if err := m.ensureMigrationsTable(ctx); err != nil { |
| 123 | return fmt.Errorf("failed to create migrations table: %w", err) |
| 124 | } |
| 125 | |
| 126 | // Get applied migrations |
| 127 | applied, err := m.getAppliedMigrations(ctx) |
| 128 | if err != nil { |
| 129 | return fmt.Errorf("failed to get applied migrations: %w", err) |
| 130 | } |
| 131 | |
| 132 | // Load all migration files |
| 133 | migrations, err := m.loadMigrations() |
| 134 | if err != nil { |
| 135 | return fmt.Errorf("failed to load migrations: %w", err) |
| 136 | } |
| 137 | |
| 138 | // Find pending migrations |
| 139 | var pending []Migration |
| 140 | for _, migration := range migrations { |
| 141 | if !applied[migration.Version] { |
| 142 | pending = append(pending, migration) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | if len(pending) == 0 { |
| 147 | log.Println("No pending migrations") |
| 148 | return nil |
| 149 | } |
| 150 | |
| 151 | log.Printf("Applying %d pending migrations", len(pending)) |
| 152 | |
| 153 | // Apply each pending migration in a transaction |
| 154 | for _, migration := range pending { |
| 155 | if err := m.applyMigration(ctx, migration); err != nil { |
| 156 | return fmt.Errorf("failed to apply migration %d (%s): %w", migration.Version, migration.Name, err) |
| 157 | } |
| 158 | log.Printf("Applied migration %d: %s", migration.Version, migration.Name) |
| 159 | } |
| 160 | |
| 161 | log.Println("All migrations applied successfully") |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | // applyMigration applies a single migration in a transaction |
| 166 | func (m *Migrator) applyMigration(ctx context.Context, migration Migration) error { |
no test coverage detected