Documentation
¶
Overview ¶
Package gormmigrator implements the migration.Migrator interface using GORM as the database driver. It maintains a `schema_migrations` table to track which migration versions have been applied.
Each migration is executed within a transaction. If the migration SQL fails, the transaction is rolled back and the version is not recorded.
Quick start ¶
import (
"embed"
"context"
gormmigrator "github.com/LingByte/ling-base/common/migration/gormmigrator"
"github.com/LingByte/ling-base/common/migration"
"gorm.io/gorm"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
func runMigrations(db *gorm.DB) error {
src := migration.NewEmbedSource(migrationFS, "migrations")
m := gormmigrator.New(db, src)
return m.Up(context.Background())
}
Schema migrations table ¶
The migrator creates a `schema_migrations` table:
CREATE TABLE schema_migrations (
version BIGINT PRIMARY KEY,
description VARCHAR(255),
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Transaction safety ¶
Each migration runs inside a database transaction. If the SQL fails, the transaction is rolled back. Note that some SQL statements (like DDL on MySQL) may implicitly commit and cannot be rolled back — this is a database limitation, not a migrator limitation.
Index ¶
- type Migrator
- func (m *Migrator) Close() error
- func (m *Migrator) Down(ctx context.Context) error
- func (m *Migrator) DownTo(ctx context.Context, targetVersion uint64) error
- func (m *Migrator) RunMigrations(ctx context.Context) error
- func (m *Migrator) Status(ctx context.Context) ([]migration.MigrationStatus, error)
- func (m *Migrator) Steps(ctx context.Context, n int) error
- func (m *Migrator) Up(ctx context.Context) error
- func (m *Migrator) UpTo(ctx context.Context, targetVersion uint64) error
- func (m *Migrator) Version(ctx context.Context) (uint64, bool, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator implements migration.Migrator using GORM.
func New ¶
New creates a new GORM-based migrator. The schema_migrations table is created automatically if it doesn't exist.
func (*Migrator) DownTo ¶
DownTo rolls back migrations down to (but not including) the given version. If version is 0, all migrations are rolled back.
func (*Migrator) RunMigrations ¶
RunMigrations applies all pending migrations. This implements the bootstrap.MigrationRunner interface, allowing the migrator to be used with bootstrap.WithMigration().