80181855bc
PLATFORM_ARCHITECTURE.md §5c schema, end-to-end:
enums: tenant_status (demo/trial/active/frozen/archived),
tenant_kind (customer/demo), idp_kind (oidc/saml),
tenant_project_status (active/archived)
tables: tenants id/slug/name/status/kind/plan/erp_id/
stripe_id/trial_ends_at/contract_dates/
sales_owner
tenant_projects sub-tenancy (GCP-Project style); opt-in via
product manifest.supports_projects=true
tenant_products tenant ↔ product matrix + JSONB config
tenant_idp_config enterprise SSO (OIDC/SAML metadata + verified)
api_keys argon2 hash + prefix + scopes + revoked_at;
single source of truth across all products
audit_log Retraced-compatible: actor/action/target/
product/metadata; indexed for cross-product
filtering (PRODUCT_INTEGRATION_SPEC.md §8.4)
triggers: updated_at auto-bump on every mutable table.
fks: ON DELETE CASCADE for owned rows; SET NULL for audit_log so
forensic history outlives the tenant delete.
cmd/migrate (new binary):
golang-migrate as a library with the migrations embedded via
migrations/embed.go → embed.FS. Sub-commands: up / down / version /
force. Ships as a self-contained binary; in prod it's the Orca init
container per IMPLEMENTATION_PLAN.md §1.7.
Dockerfile builds both binaries; the migrate one is invoked separately
as the init step.
Tests (require Docker; gated by -short):
TestMigrate_upDownRoundTrip schema → 6 tables + 4 enums; down→empty;
up-after-down succeeds (round-trip clean)
TestSeed_canInsertAndQuery insert across every table; FK cascade
works; audit_log SET-NULL keeps the row
TestSlugConstraint tenant.slug regex rejects too-short /
leading dash / trailing dash / uppercase /
underscore
Makefile:
make migrate-up / down / down-all / version / create NAME=...
make test-short → skip integration when Docker isn't around
make build-migrate → just the migrator binary
The handler-layer in-memory store is unchanged; M4.2 swaps it for the
pgx-backed implementation against this schema.
Refs: M4.1
138 lines
3.5 KiB
Go
138 lines
3.5 KiB
Go
// migrate — standalone CLI that applies tenant-registry's SQL migrations.
|
|
//
|
|
// Usage:
|
|
// migrate up apply all pending migrations
|
|
// migrate down roll back the most recent migration
|
|
// migrate down --all roll back every migration (DESTRUCTIVE)
|
|
// migrate version print the current schema version
|
|
// migrate force <version> mark a specific version applied (recovery)
|
|
//
|
|
// Reads DATABASE_URL from the environment. Migrations are embedded so this
|
|
// binary is self-contained — ship it as an Orca init container in prod.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
|
|
"github.com/golang-migrate/migrate/v4"
|
|
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
|
|
|
"gitea.meghsakha.com/platform/tenant-registry/migrations"
|
|
)
|
|
|
|
func main() {
|
|
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
|
slog.SetDefault(logger)
|
|
|
|
allDown := flag.Bool("all", false, "with 'down', roll back every migration")
|
|
flag.Usage = func() {
|
|
fmt.Fprintf(os.Stderr, "usage: %s <up|down|version|force <n>>\n", os.Args[0])
|
|
flag.PrintDefaults()
|
|
}
|
|
flag.Parse()
|
|
|
|
args := flag.Args()
|
|
if len(args) < 1 {
|
|
flag.Usage()
|
|
os.Exit(2)
|
|
}
|
|
|
|
dbURL := os.Getenv("DATABASE_URL")
|
|
if dbURL == "" {
|
|
slog.Error("DATABASE_URL not set")
|
|
os.Exit(1)
|
|
}
|
|
|
|
if err := run(context.Background(), args, dbURL, *allDown); err != nil {
|
|
slog.Error("migrate failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(ctx context.Context, args []string, dbURL string, allDown bool) error {
|
|
src, err := iofs.New(migrations.FS, ".")
|
|
if err != nil {
|
|
return fmt.Errorf("load embedded migrations: %w", err)
|
|
}
|
|
|
|
m, err := migrate.NewWithSourceInstance("iofs", src, dbURL)
|
|
if err != nil {
|
|
return fmt.Errorf("open migrate: %w", err)
|
|
}
|
|
defer func() {
|
|
if srcErr, dbErr := m.Close(); srcErr != nil || dbErr != nil {
|
|
slog.Warn("close error", "src_err", srcErr, "db_err", dbErr)
|
|
}
|
|
}()
|
|
|
|
cmd := args[0]
|
|
switch cmd {
|
|
case "up":
|
|
err = m.Up()
|
|
if errors.Is(err, migrate.ErrNoChange) {
|
|
slog.Info("no pending migrations")
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("up: %w", err)
|
|
}
|
|
v, dirty, _ := m.Version()
|
|
slog.Info("migrate up complete", "version", v, "dirty", dirty)
|
|
return nil
|
|
|
|
case "down":
|
|
if allDown {
|
|
if err := m.Down(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
|
return fmt.Errorf("down all: %w", err)
|
|
}
|
|
slog.Info("migrate down --all complete (schema empty)")
|
|
return nil
|
|
}
|
|
if err := m.Steps(-1); err != nil {
|
|
if errors.Is(err, migrate.ErrNoChange) {
|
|
slog.Info("no migrations to roll back")
|
|
return nil
|
|
}
|
|
return fmt.Errorf("down 1: %w", err)
|
|
}
|
|
v, dirty, _ := m.Version()
|
|
slog.Info("migrate down 1 complete", "version", v, "dirty", dirty)
|
|
return nil
|
|
|
|
case "version":
|
|
v, dirty, err := m.Version()
|
|
if errors.Is(err, migrate.ErrNilVersion) {
|
|
slog.Info("no migrations applied")
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("version: %w", err)
|
|
}
|
|
slog.Info("schema version", "version", v, "dirty", dirty)
|
|
return nil
|
|
|
|
case "force":
|
|
if len(args) != 2 {
|
|
return errors.New("usage: migrate force <version>")
|
|
}
|
|
var n int
|
|
if _, err := fmt.Sscanf(args[1], "%d", &n); err != nil {
|
|
return fmt.Errorf("invalid version %q", args[1])
|
|
}
|
|
if err := m.Force(n); err != nil {
|
|
return fmt.Errorf("force: %w", err)
|
|
}
|
|
slog.Info("forced version", "version", n)
|
|
return nil
|
|
|
|
default:
|
|
return fmt.Errorf("unknown command %q", cmd)
|
|
}
|
|
}
|