101 lines
2.0 KiB
Go
101 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
|
|
"forge.cadoles.com/Cadoles/daddy/internal/database"
|
|
"forge.cadoles.com/Cadoles/daddy/internal/migration"
|
|
"github.com/jackc/pgx/v4"
|
|
"github.com/pkg/errors"
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
"gitlab.com/wpetit/goweb/service"
|
|
)
|
|
|
|
const (
|
|
migrateUp = "up"
|
|
migrateLatest = "latest"
|
|
migrateDown = "down"
|
|
)
|
|
|
|
func applyMigration(ctx context.Context, ctn *service.Container) error {
|
|
migr, err := migration.From(ctn)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Register available migrations
|
|
migr.Register(
|
|
m000initialSchema(),
|
|
)
|
|
|
|
currentVersion, err := migr.CurrentVersion(ctx)
|
|
if err != nil {
|
|
return errors.Wrap(err, "could not retrieve current data schema version")
|
|
}
|
|
|
|
switch migrate {
|
|
case migrateUp:
|
|
if err := migr.Up(ctx); err != nil {
|
|
return errors.Wrap(err, "could not apply up migration")
|
|
}
|
|
|
|
case migrateLatest:
|
|
latestVersion, err := migr.LatestVersion()
|
|
if err != nil {
|
|
return errors.Wrap(err, "could not retrieve latest data schema version")
|
|
}
|
|
|
|
logger.Info(
|
|
ctx,
|
|
"migrating data schema to latest version",
|
|
logger.F("currentVersion", currentVersion),
|
|
logger.F("latestVersion", latestVersion),
|
|
)
|
|
|
|
// Execute migration to latest available version
|
|
if err := migr.Latest(ctx); err != nil {
|
|
return errors.Wrap(err, "could not migrate to latest data schema")
|
|
}
|
|
|
|
case migrateDown:
|
|
if err := migr.Down(ctx); err != nil {
|
|
return errors.Wrap(err, "could not apply down migration")
|
|
}
|
|
|
|
default:
|
|
return errors.Errorf("unknown migration command: '%s'", migrate)
|
|
}
|
|
|
|
logger.Info(
|
|
ctx,
|
|
"migration completed",
|
|
)
|
|
|
|
return nil
|
|
}
|
|
|
|
func m000initialSchema() migration.Migration {
|
|
return database.NewMigration(
|
|
"00_initial_schema",
|
|
func(ctx context.Context, tx pgx.Tx) error {
|
|
_, err := tx.Exec(ctx, `
|
|
CREATE TABLE users (
|
|
id SERIAL PRIMARY KEY,
|
|
name TEXT,
|
|
email TEXT NOT NULL,
|
|
CONSTRAINT unique_email unique(email)
|
|
);
|
|
`)
|
|
|
|
return err
|
|
},
|
|
func(ctx context.Context, tx pgx.Tx) error {
|
|
_, err := tx.Exec(ctx, `
|
|
DROP TABLE users;
|
|
`)
|
|
|
|
return err
|
|
},
|
|
)
|
|
}
|