Files
archie/internal/platform/pg/pg.go
T

89 lines
2.7 KiB
Go

// Package pg opens Archie's Postgres connections and applies its one ordered
// migration series.
package pg
import (
"context"
"embed"
"fmt"
"io/fs"
"log/slog"
"github.com/jackc/pgx/v5"
// Registers the "pgx" database/sql driver that sqlx and goose use.
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/jmoiron/sqlx"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
)
//go:embed migrations
var migrationFiles embed.FS
// Open connects with the runtime URL and checks the connection.
func Open(ctx context.Context, url string) (*sqlx.DB, error) {
db, err := sqlx.Open("pgx", url)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("reach database: %w", err)
}
return db, nil
}
// Migrate applies every pending migration as the owner, under a session
// advisory lock, so two instances starting together never race, then grants
// the runtime role DML on each module schema. A failed migration returns an
// error and the boot stops.
func Migrate(ctx context.Context, log *slog.Logger, ownerURL, runtimeURL string, schemas []string) error {
db, err := Open(ctx, ownerURL)
if err != nil {
return fmt.Errorf("owner connection: %w", err)
}
defer func() { _ = db.Close() }()
files, err := fs.Sub(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("migration files: %w", err)
}
locker, err := lock.NewPostgresSessionLocker()
if err != nil {
return fmt.Errorf("migration lock: %w", err)
}
provider, err := goose.NewProvider(goose.DialectPostgres, db.DB, files, goose.WithSessionLocker(locker))
if err != nil {
return fmt.Errorf("migration provider: %w", err)
}
results, err := provider.Up(ctx)
if err != nil {
return fmt.Errorf("apply migrations: %w", err)
}
for _, r := range results {
log.InfoContext(ctx, "migration applied", "migration", r.Source.Version, "file", r.Source.Path, "took", r.Duration)
}
return grantRuntime(ctx, db, runtimeURL, schemas)
}
// grantRuntime gives the runtime role USAGE and DML on each schema, never DDL.
func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error {
cfg, err := pgx.ParseConfig(runtimeURL)
if err != nil {
return fmt.Errorf("parse runtime URL: %w", err)
}
role := pgx.Identifier{cfg.User}.Sanitize()
for _, schema := range schemas {
name := pgx.Identifier{schema}.Sanitize()
for _, stmt := range []string{
"GRANT USAGE ON SCHEMA " + name + " TO " + role,
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role,
} {
if _, err := db.ExecContext(ctx, stmt); err != nil {
return fmt.Errorf("grant runtime role on %s: %w", schema, err)
}
}
}
return nil
}