migrator

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 21 Imported by: 1

README

migrator

Package migrator handles loading authorization schemas into PostgreSQL.

This package provides the primary API for applying OpenFGA schemas to your database, generating specialized SQL functions for permission checking. Migrations are idempotent and safe to run on every application startup.

Package Responsibilities

  • Parse and validate OpenFGA schemas
  • Generate specialized SQL functions per relation
  • Apply migrations atomically within transactions
  • Track migration history for skip-if-unchanged optimization
  • Clean up orphaned functions when schema changes

Public API

High-Level Functions
// Migrate parses schema file and applies to database in one operation.
// Recommended for most applications.
func Migrate(ctx context.Context, db Execer, schemaPath string) error

// MigrateFromString parses schema content and applies to database.
// Useful for embedded schemas or testing.
func MigrateFromString(ctx context.Context, db Execer, content string) error

// MigrateWithOptions provides control over dry-run and skip behavior.
func MigrateWithOptions(ctx context.Context, db Execer, schemaPath string, opts MigrateOptions) (skipped bool, err error)

// PlanWithOptions predicts what MigrateWithOptions would do with opts,
// unforced, without changing the database.
func PlanWithOptions(ctx context.Context, db Execer, schemaPath string, opts MigrateOptions) (*MigrationPlan, error)
Migrator Type
// NewMigrator creates a new schema migrator.
func NewMigrator(db Execer, schemaPath string) *Migrator

// MigrateWithTypes performs migration using pre-parsed type definitions.
// It records no migration, so it generates under the recorded exposure and
// returns *UnrecordedExposureChangeError when SetExposure asks for another.
func (m *Migrator) MigrateWithTypes(ctx context.Context, types []TypeDefinition) error

// MigrateWithTypesAndOptions performs migration with full options control.
// It records the migration when opts.SchemaContent holds the schema text;
// without it, it records nothing and refuses an exposure change like
// MigrateWithTypes.
func (m *Migrator) MigrateWithTypesAndOptions(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) error

// Plan predicts what MigrateWithTypesAndOptions would do with opts, unforced.
// It reads the database and takes no lock; Force and DryRun are ignored.
func (m *Migrator) Plan(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) (*MigrationPlan, error)

// GetStatus returns the current migration status.
func (m *Migrator) GetStatus(ctx context.Context) (*Status, error)

// GetLastMigration returns the most recent migration record.
func (m *Migrator) GetLastMigration(ctx context.Context) (*MigrationRecord, error)

// HasSchema returns true if the schema file exists.
func (m *Migrator) HasSchema() bool
Types
// MigrateOptions controls migration behavior.
type MigrateOptions struct {
    DryRun             io.Writer // Output SQL without applying; nil = apply normally
    Force              bool      // Re-run even if unchanged; also drops orphans with CASCADE and overrides the downgrade guard
    Version            string    // Melange version for traceability
    DatabaseSchema     string    // PostgreSQL schema for melange objects
    IfDeployedChecksum *string   // Compare-and-swap: abort with *DeployedModelChangedError unless this checksum is deployed
    Exposure           *Exposure // SQL API to generate; nil keeps the recorded one (the default when none), a pointer to the zero value restores the default
}

// Status represents the current migration state.
type Status struct {
    SchemaExists bool // Schema file exists on disk
    TuplesExists bool // melange_tuples view exists in database
}

// MigrationRecord represents a row in melange_migrations table.
type MigrationRecord struct {
    MelangeVersion string
    SchemaChecksum string
    CodegenVersion string
    FunctionNames  []string
    Exposure       Exposure // normalized exposure the functions were generated with
}

// MigrationPlan is what an unforced migration would do (Plan).
type MigrationPlan struct {
    Action   PlanAction         // PlanApply, PlanRecordOnly, PlanSkip or PlanRefusedAhead
    Record   *MigrationRecord   // last migration; nil when none is recorded
    Exposure Exposure           // the exposure the migration generates with
    Orphans  []OrphanedFunction // what an applying (or forced) run drops, with dependents
}

PlanRecordOnly means the generated SQL is the SQL the last migration recorded: the migration records the new state and applies nothing, so a function dropped or edited by hand stays that way. PlanSkip does nothing at all. Both are fixed by Force: true, which also drops Orphans with CASCADE, dependents included. PlanRefusedAhead means a newer melange migrated the database and migrate returns *DatabaseAheadError.

Usage Examples

import "github.com/pthm/melange/pkg/migrator"

// Run on application startup. Concurrent replicas are serialized by an
// advisory lock, so every replica can migrate.
func main() {
    db, _ := sql.Open("postgres", connString)

    err := migrator.Migrate(ctx, db, "schemas/schema.fga")
    var ahead *migrator.DatabaseAheadError
    switch {
    case errors.As(err, &ahead):
        // A replica running a newer melange already upgraded the database
        // (e.g. mid rolling deploy). Its functions keep the same SQL API.
        log.Printf("Skipping migration: %v", err)
    case err != nil:
        log.Fatalf("Migration failed: %v", err)
    }

    // Application ready...
}
Embedded Schema
import (
    _ "embed"
    "github.com/pthm/melange/pkg/migrator"
)

//go:embed schema.fga
var embeddedSchema string

func main() {
    db, _ := sql.Open("postgres", connString)

    if err := migrator.MigrateFromString(ctx, db, embeddedSchema); err != nil {
        log.Fatalf("Migration failed: %v", err)
    }
}
Dry-Run (Preview SQL)
var buf bytes.Buffer

_, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{
    DryRun: &buf,
})
if err != nil {
    log.Fatal(err)
}

// Write SQL to file for review
os.WriteFile("migrations/001_authz.sql", buf.Bytes(), 0644)
Force Re-Migration
// Useful after manual schema corruption or template changes
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{
    Force: true,
})
if err != nil {
    log.Fatal(err)
}
// skipped is always false when Force=true
Predict a Migration
// Readiness check: the last migration recorded exactly what this schema,
// exposure and codegen version generate. Plan reads the migration record,
// not the installed functions, so PlanSkip does not detect a function
// dropped or edited by hand; `melange doctor` and `melange functions` check
// those.
plan, err := migrator.PlanWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{})
if err != nil {
    log.Fatal(err)
}
if plan.Action != migrator.PlanSkip {
    log.Printf("migration pending: %s", plan.Action)
}
Check Migration Status
m := migrator.NewMigrator(db, "schemas/schema.fga")

status, err := m.GetStatus(ctx)
if err != nil {
    log.Fatal(err)
}

if !status.SchemaExists {
    log.Println("No schema file found")
}

if !status.TuplesExists {
    log.Println("melange_tuples view needs to be created")
}
With Pre-Parsed Types
import (
    "github.com/pthm/melange/pkg/parser"
    "github.com/pthm/melange/pkg/migrator"
)

// Parse once, migrate multiple databases
types, err := parser.ParseSchema("schemas/schema.fga")
if err != nil {
    log.Fatal(err)
}

for _, db := range databases {
    m := migrator.NewMigrator(db, "schemas/schema.fga")
    if err := m.MigrateWithTypes(ctx, types); err != nil {
        log.Printf("Migration failed for %s: %v", db, err)
    }
}

MigrateWithTypes records no migration, so it cannot change the SQL API exposure: it generates under the recorded one (the default when none is recorded), and an exposure set with SetExposure must be that same one. To change it, record the migration by passing the schema text:

m := migrator.NewMigrator(db, "")
err := m.MigrateWithTypesAndOptions(ctx, types, migrator.InternalMigrateOptions{
    SchemaContent: schemaContent,
    SchemaFormat:  migrator.FormatSingle,
    Exposure:      &exposure,
})
var unrecorded *migrator.UnrecordedExposureChangeError
if errors.As(err, &unrecorded) {
    // Only a migration without SchemaContent returns this; nothing was applied.
    log.Printf("exposure %v needs a recorded migration", unrecorded.Requested)
}

Migration Workflow

When you run migration, the following steps occur:

  1. Parse - Read and parse the OpenFGA schema
  2. Validate - Check for cycles and invalid references
  3. Compute - Generate transitive closure for role hierarchies
  4. Analyze - Classify relations and determine SQL patterns
  5. Generate - Create specialized SQL functions per relation
  6. Apply - Execute SQL atomically in a transaction
  7. Cleanup - Drop functions a previous migration installed that this one no longer generates. When other database objects (for example a view or RLS policy) depend on one, an unforced migration fails with *DependentObjectsError before applying anything; Force: true drops them with CASCADE, dependents included
  8. Track - Record the migration (schema, codegen version, function checksums and SQL API exposure) in melange_migrations

Skip-If-Unchanged Optimization

Migrations are skipped when all of these match the last migration:

  • Schema content hash
  • Codegen version
  • SQL API exposure

When one differs, the SQL is generated and compared with the function checksums the last migration recorded; identical SQL is recorded without being applied. Neither phase looks at the installed functions, so one dropped or edited by hand is restored only by Force: true. This avoids redundant function regeneration on every restart. Plan predicts the outcome without migrating.

Transaction Support

When the Execer can begin a transaction (*sql.DB, *sql.Conn), migrations are applied atomically in the migrator's own transaction:

// All-or-nothing: either all functions are created or none
err := migrator.Migrate(ctx, db, "schema.fga")

With a *sql.Tx, functions are applied on the caller's transaction, which the caller commits or rolls back.

Error Handling

err := migrator.Migrate(ctx, db, "schema.fga")
if err != nil {
    // Check specific error types
    if schema.IsCyclicSchemaErr(err) {
        log.Fatal("Schema has cyclic relations")
    }
    if errors.Is(err, melange.ErrInvalidSchema) {
        log.Fatal("Schema syntax error")
    }
    log.Fatalf("Migration failed: %v", err)
}

Database Requirements

The migrator requires:

  1. PostgreSQL - Generates PL/pgSQL functions
  2. Schema permissions - Ability to CREATE/REPLACE FUNCTION
  3. melange_tuples view - User-defined view over domain tables (checked by GetStatus)

Dependency Information

This package imports:

  • github.com/lib/pq - PostgreSQL driver for array handling
  • github.com/pthm/melange/pkg/parser - Schema parsing
  • github.com/pthm/melange/pkg/schema - Schema types
  • github.com/pthm/melange/internal/sqlgen - SQL generation

Execer Interface

The migrator accepts any type implementing Execer:

type Execer interface {
    ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
    QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
    QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Compatible types: *sql.DB, *sql.Tx, *sql.Conn

Documentation

Overview

Package migrator applies compiled OpenFGA schemas to a PostgreSQL database, installing the generated PL/pgSQL functions and tracking applied migrations.

Index

Constants

View Source
const (
	FormatSingle  = "single"  // a single .fga file
	FormatModular = "modular" // an fga.mod manifest
)

Schema format values recorded in melange_migrations.schema_format and surfaced on DeployedModel.Format.

View Source
const GeneratedFunctionFilter = `p.proname ~ '^(check|list|expand|explain|accessible|accessiblesk)_'`

GeneratedFunctionFilter matches pg_proc rows (aliased p) named like a per-relation function melange generates: check_, list_, expand_, explain_, accessible_ or accessiblesk_. Migrate's orphan cleanup and doctor's orphan report share it so a new family can't be missed by one of them.

Variables

View Source
var (
	DetectCycles           = schema.DetectCycles
	ComputeRelationClosure = schema.ComputeRelationClosure
	AnalyzeRelations       = sqlgen.AnalyzeRelations
	ComputeCanGenerate     = sqlgen.ComputeCanGenerate

	GenerateSQL          = sqlgen.GenerateSQL
	GenerateListSQL      = sqlgen.GenerateListSQL
	CollectFunctionNames = sqlgen.CollectFunctionNames
)

Function aliases from schema and sqlgen packages.

Functions

func CodegenVersion

func CodegenVersion() string

CodegenVersion returns the melange version used to identify which codegen produced the SQL. Combined with function checksums, this allows skip detection and change tracking across migrations.

func CodegenVersionAhead added in v0.11.0

func CodegenVersionAhead(deployed string) bool

CodegenVersionAhead reports whether deployed is a newer codegen version than this melange's, so migrate refuses to replace its functions unless forced (DatabaseAheadError). Versions that cannot be ordered are not ahead.

func ComputeFunctionChecksums added in v0.7.4

func ComputeFunctionChecksums(namedFunctions []NamedFunction) map[string]string

ComputeFunctionChecksums computes SHA256 hashes for each named function's SQL body. The returned map is stored in the migration record and used by `generate migration --db` to determine which functions have changed and need to be included in the migration.

func ComputeSchemaChecksum

func ComputeSchemaChecksum(content string) string

ComputeSchemaChecksum returns a SHA256 hash of the schema content. Used to detect schema changes for skip-if-unchanged optimization.

func DeployedTypes added in v0.11.0

func DeployedTypes(rec *MigrationRecord) ([]schema.TypeDefinition, error)

DeployedTypes returns the parsed model a migration record stores, preferring model_json and falling back to parsing the recorded DSL when the JSON is absent, empty or unreadable, the same order doctor uses, so every tool agrees on what a database has deployed.

It returns nil types and a nil error for a record written before model storage (no DSL recorded), which callers report as "not recorded".

func Migrate

func Migrate(ctx context.Context, db Execer, schemaPath string) error

Migrate parses an OpenFGA schema file and applies it to the database in one operation. This is the recommended high-level API for most applications.

The function is idempotent - safe to call on every application startup. It validates the schema, generates specialized SQL functions per relation, and applies everything atomically within a transaction (when db supports BeginTx).

Migration workflow:

  1. Reads the schema file at schemaPath
  2. Parses OpenFGA DSL using the official parser
  3. Validates schema (cycle detection, referential integrity)
  4. Generates specialized check_permission and list_accessible functions
  5. Applies generated SQL atomically via transaction

The SQL API exposure recorded by the last migration is kept (the default when none is recorded), so a database migrated by `melange migrate` with a restricted exposure stays restricted. Use MigrateWithOptions to change it.

Example usage on application startup:

if err := migrator.Migrate(ctx, db, "schemas/schema.fga"); err != nil {
    log.Fatalf("migration failed: %v", err)
}

For embedded schemas (no file I/O), use MigrateFromString. For fine-grained control (dry-run, skip optimization), use MigrateWithOptions. For programmatic use with pre-parsed types, use Migrator directly:

types, _ := parser.ParseSchema("schemas/schema.fga")
m := migrator.NewMigrator(db, "schemas/schema.fga")
err := m.MigrateWithTypes(ctx, types)

func MigrateFromString

func MigrateFromString(ctx context.Context, db Execer, content string) error

MigrateFromString parses schema content and applies it to the database. Useful for testing or when schema is embedded in the application binary.

This allows bundling the authorization schema with the application rather than reading from disk, which simplifies deployment and versioning.

Example:

//go:embed schema.fga
var embeddedSchema string

err := migrator.MigrateFromString(ctx, db, embeddedSchema)

The migration is idempotent and transactional (when using *sql.DB). Like Migrate, it keeps the recorded SQL API exposure.

func MigrateWithOptions

func MigrateWithOptions(ctx context.Context, db Execer, schemaPath string, opts MigrateOptions) (skipped bool, err error)

MigrateWithOptions performs migration with control over dry-run and skip behavior. Use this when you need to preview migrations, force re-application, or detect skips.

Skip detection has two phases. Phase 1 compares the schema content hash, melange version and exposure against the last migration; if all match, the migration is skipped entirely (skipped=true). Phase 2 generates SQL and compares function checksums; if the output is identical to what's already applied, the functions are not re-applied (only the migration record is updated). This avoids redundant function regeneration even across melange version upgrades when the generated SQL hasn't changed.

Returns (skipped, error):

  • skipped=true if migration was skipped due to unchanged schema (only when Force=false and DryRun=nil)
  • error is non-nil if migration failed (parse error, validation error, DB error)

Example: Generate migration script without applying

var buf bytes.Buffer
_, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{
    DryRun: &buf,
})
os.WriteFile("migrations/001_authz.sql", buf.Bytes(), 0644)

Example: Force re-migration (e.g., after manual schema corruption)

skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{
    Force: true,
})

func SameCodegenVersion added in v0.10.3

func SameCodegenVersion(a, b string) bool

SameCodegenVersion reports whether a and b name the same codegen version, ignoring the "v" prefix that only some build paths stamp.

func SameExposure added in v0.11.0

func SameExposure(a, b Exposure) bool

SameExposure reports whether a and b select the same SQL API, that is, whether they normalize to the same exposure.

Types

type DatabaseAheadError added in v0.10.1

type DatabaseAheadError struct {
	Deployed string // codegen version that generated the deployed functions
	Current  string // this melange's codegen version
}

DatabaseAheadError is returned by migrate when the database's functions were generated by a newer melange than this one. Applying would replace them with older generated SQL, undoing codegen fixes, and during a rolling deploy old and new replicas would overwrite each other on every restart. Nothing is applied. Callers that run migrate on startup can treat it as "another replica already upgraded the database" (errors.As) and continue: the newer functions keep the same SQL API. MigrateOptions.Force overrides the guard.

func (*DatabaseAheadError) Error added in v0.10.1

func (e *DatabaseAheadError) Error() string

type DependentObjectsError added in v0.11.0

type DependentObjectsError struct {
	Dependents []FunctionDependent
	Err        error
	// contains filtered or unexported fields
}

DependentObjectsError is returned by migrate when functions the new SQL no longer generates (orphans) have dependents. Dropping them with CASCADE would silently drop the dependents too; losing an RLS policy widens access. MigrateOptions.Force drops them.

Migrate checks for dependents before applying anything. A dependent created by another session after that check makes the drop itself fail, since an unforced drop does not CASCADE; Err then holds the database's refusal (SQLSTATE 2BP01) and the migration is not recorded. In the migrator's own transaction everything is rolled back; on a caller's Execer without one, the new functions stay applied and the orphans stay installed.

func (*DependentObjectsError) Error added in v0.11.0

func (e *DependentObjectsError) Error() string

func (*DependentObjectsError) Unwrap added in v0.11.0

func (e *DependentObjectsError) Unwrap() error

type DeployedModel added in v0.9.3

type DeployedModel struct {
	DSL            string                  // OpenFGA DSL that produced the deployment
	Format         string                  // "single" or "modular"
	Types          []schema.TypeDefinition // parsed model (see DeployedTypes)
	SchemaChecksum string
	MelangeVersion string
	CodegenVersion string // codegen version that generated the installed functions
	MigratedAt     time.Time
	Exposure       Exposure // normalized SQL API exposure; zero is the default
}

DeployedModel is the authorization model recorded by the most recent migration — the source for `melange schema pull`, drift detection, and diffs.

type DeployedModelChangedError added in v0.9.3

type DeployedModelChangedError struct {
	Expected string // checksum the caller expected to be deployed
	Actual   string // checksum actually deployed ("" when no migration is recorded)
}

DeployedModelChangedError is returned by migrate when --if-deployed-checksum does not match the currently-deployed schema checksum: the database drifted from the expected state, so nothing was applied.

func (*DeployedModelChangedError) Error added in v0.9.3

func (e *DeployedModelChangedError) Error() string

type Execer

type Execer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Execer is the minimal interface needed for schema migration operations. Implemented by *sql.DB, *sql.Tx, and *sql.Conn.

type Exposure added in v0.11.0

type Exposure = sqlgen.Exposure

Exposure re-exports sqlgen.Exposure: the SQL API a migration generates. The zero value is the default (every relation, every function family).

type FunctionDependent added in v0.11.0

type FunctionDependent struct {
	Function string // the generated function
	Object   string // the dependent, as pg_describe_object names it (e.g. "view doc_access")
}

FunctionDependent is a database object that depends on a generated function, as recorded in pg_depend: a view or materialized view, an RLS policy, a rule, or a function with a SQL-standard (BEGIN ATOMIC) body.

type GeneratedSQL

type GeneratedSQL = sqlgen.GeneratedSQL

GeneratedSQL re-exports sqlgen.GeneratedSQL.

type InternalMigrateOptions

type InternalMigrateOptions struct {
	DryRun io.Writer
	Force  bool

	// Version is the melange CLI/library version (e.g., "v0.4.3").
	// Recorded in melange_migrations for traceability.
	Version string

	// SchemaContent is the raw schema text used for checksum calculation to detect schema changes.
	// If empty, no migration is recorded: skip-if-unchanged optimization is
	// disabled, and an Exposure other than the recorded one is refused (see
	// UnrecordedExposureChangeError) unless DryRun is set.
	SchemaContent string

	// SchemaFormat records how the schema was authored: "single" for a .fga
	// file or "modular" for an fga.mod manifest. Stored alongside the DSL so
	// `melange schema pull` can annotate its output.
	SchemaFormat string

	// IfDeployedChecksum is the compare-and-swap precondition; see MigrateOptions.
	IfDeployedChecksum *string

	// Exposure selects the generated SQL API; see MigrateOptions. Nil falls
	// back to the Migrator's exposure (SetExposure), then to the recorded one.
	// Changing it needs a recorded migration: without SchemaContent or
	// DryRun, a different exposure returns *UnrecordedExposureChangeError.
	Exposure *Exposure
}

InternalMigrateOptions extends MigrateOptions with internal fields.

type ListGeneratedSQL

type ListGeneratedSQL = sqlgen.ListGeneratedSQL

ListGeneratedSQL re-exports sqlgen.ListGeneratedSQL.

type MigrateOptions

type MigrateOptions struct {
	// DryRun outputs SQL to the provided writer without applying changes to the database.
	// If nil, migration proceeds normally. Use for previewing migrations or generating migration scripts.
	DryRun io.Writer

	// Force re-runs migration even if schema/codegen unchanged. Use when manually fixing corrupted state or testing.
	// It also overrides the downgrade guard (see DatabaseAheadError), so an older
	// melange can deliberately replace functions generated by a newer one, and
	// the dependent-object refusal (see DependentObjectsError): orphaned
	// functions are dropped with CASCADE, together with any views, policies,
	// rules or functions that depend on them.
	Force bool

	// Version is the melange CLI/library version (e.g., "v0.4.3").
	// Recorded in melange_migrations for traceability.
	Version string

	// DatabaseSchema is the Postgres schema where the objects will be created.
	DatabaseSchema string

	// IfDeployedChecksum, when non-nil, makes migration a compare-and-swap: it
	// proceeds only if the currently-deployed schema checksum equals the pointed-to
	// value, otherwise it aborts with *DeployedModelChangedError without applying
	// anything. An empty string matches a database with no migration recorded. It
	// is enforced in dry-run too, so a drift-gated preview aborts rather than
	// printing SQL against a drifted database.
	//
	// The checksum is verified up front and again inside the apply transaction,
	// which holds the migration lock, so a migration committed while this one
	// waited aborts it.
	IfDeployedChecksum *string

	// Exposure selects the generated SQL API (see [Exposure]). Nil keeps the
	// exposure the database was last migrated with (the default when none is
	// recorded), so an application that migrates on startup does not undo an
	// exposure set by `melange migrate`. A non-nil value replaces it; pass a
	// pointer to the zero value to restore the default.
	Exposure *Exposure
}

MigrateOptions controls migration behavior (public API).

type MigrationPlan added in v0.11.0

type MigrationPlan struct {
	Action PlanAction

	// Record is the last migration, nil when none is recorded.
	Record *MigrationRecord

	// Exposure is the exposure the migration generates with: the requested
	// one, else the recorded one, else the default. Unset for
	// PlanRefusedAhead.
	Exposure Exposure

	// Orphans are what an applying migration drops: installed functions that
	// any migration recorded and this one does not generate. Filled for every
	// action but PlanRefusedAhead, since a forced migration applies, and drops
	// them, whatever the action.
	Orphans []OrphanedFunction
}

MigrationPlan predicts an unforced migration; see Migrator.Plan.

func PlanWithOptions added in v0.11.0

func PlanWithOptions(ctx context.Context, db Execer, schemaPath string, opts MigrateOptions) (*MigrationPlan, error)

PlanWithOptions predicts what MigrateWithOptions would do with opts unforced, without changing the database; see Migrator.Plan. It reads and parses the schema file the same way. opts.Force and opts.DryRun are ignored, and opts.IfDeployedChecksum is not evaluated.

Example: a readiness check that waits for the database to be migrated

plan, err := migrator.PlanWithOptions(ctx, db, "schemas/schema.fga", migrator.MigrateOptions{})
ready := err == nil && plan.Action == migrator.PlanSkip

type MigrationRecord

type MigrationRecord struct {
	// ID and MigratedAt identify the row and when it was written. Populated by
	// reads (getLastMigration); ignored on writes (the DB assigns them).
	ID         int
	MigratedAt time.Time

	MelangeVersion string
	SchemaChecksum string
	CodegenVersion string
	FunctionNames  []string
	// FunctionChecksums maps function_name → SHA256(sql_body) for each function
	// installed by this migration. Populated only when the database schema includes
	// the function_checksums column (added in v0.7.3). Nil on records written by
	// older versions; callers should treat nil as "no checksum data available" and
	// fall back to full-mode generation.
	FunctionChecksums map[string]string

	// SchemaDSL, SchemaFormat, and ModelJSON make the database self-describing.
	// They are populated only when the corresponding columns exist and were
	// written by a version that records the model. On older records SchemaDSL is
	// "" (treat as "no model recorded") and ModelJSON is nil.
	SchemaDSL    string
	SchemaFormat string
	ModelJSON    []byte

	// Exposure is the normalized exposure the functions were generated with.
	// Records written before the exposure column existed read as the default,
	// which is what those migrations generated.
	Exposure Exposure
}

MigrationRecord represents a row in the melange_migrations table.

type Migrator

type Migrator struct {
	// contains filtered or unexported fields
}

Migrator handles loading authorization schemas into PostgreSQL. The migrator is idempotent - safe to run on every application startup.

The migration process:

  1. Creates/replaces check_permission and list_accessible_* functions
  2. Loads generated SQL entrypoints into the database

Usage

Use the convenience functions in pkg/migrator for most use cases:

import "github.com/pthm/melange/pkg/migrator"
err := migrator.Migrate(ctx, db, "schemas/schema.fga")

For embedded schemas (no file I/O):

err := migrator.MigrateFromString(ctx, db, schemaContent)

Use the Migrator directly when you have pre-parsed TypeDefinitions or need fine-grained control (DDL-only, status checks, etc.):

types, _ := parser.ParseSchema("schemas/schema.fga")
m := migrator.NewMigrator(db, "schemas/schema.fga")
err := m.MigrateWithTypes(ctx, types)

MigrateWithTypes records no migration, so it cannot change the SQL API exposure (see UnrecordedExposureChangeError). To record one from parsed types, pass the schema text as well:

err := m.MigrateWithTypesAndOptions(ctx, types, migrator.InternalMigrateOptions{
	SchemaContent: schemaContent,
	SchemaFormat:  migrator.FormatSingle,
	Exposure:      &exposure,
})

func NewMigrator

func NewMigrator(db Execer, schemaPath string) *Migrator

NewMigrator creates a new schema migrator. The schemaPath should point to an OpenFGA DSL schema file (e.g., "schemas/schema.fga"). The Execer is typically *sql.DB but can be *sql.Tx for testing.

func (*Migrator) ApplyDDL

func (m *Migrator) ApplyDDL(ctx context.Context) error

ApplyDDL applies any base schema required by Melange. With fully generated SQL entrypoints, no base DDL is required.

func (*Migrator) DatabaseSchema added in v0.8.0

func (m *Migrator) DatabaseSchema() string

DatabaseSchema returns the database schema.

func (*Migrator) GetDeployedModel added in v0.9.3

func (m *Migrator) GetDeployedModel(ctx context.Context) (*DeployedModel, error)

GetDeployedModel returns the model recorded by the most recent migration, or nil if none has been recorded — either because the database has never been migrated or because it was migrated before model storage existed (SchemaDSL empty). Callers surface a "re-run migrate to record the model" hint for nil. Types comes from DeployedTypes, so a record with only the DSL has them too; it is nil when neither the JSON nor the DSL yields a model, which leaves the DSL available (schema pull) without failing.

func (*Migrator) GetLastMigration

func (m *Migrator) GetLastMigration(ctx context.Context) (*MigrationRecord, error)

GetLastMigration returns the most recent migration record, or nil if none exists. It queries against the migrator's own database connection, making it suitable for external callers such as the generate migration command.

Internal migration code uses the private getLastMigration with an explicit Execer to participate in an in-progress transaction.

func (*Migrator) GetMigrationHistory added in v0.9.3

func (m *Migrator) GetMigrationHistory(ctx context.Context, limit int) ([]MigrationRecord, error)

GetMigrationHistory returns up to limit migration records, most recent first. It reads a lightweight subset (no DSL or model JSON) suitable for an audit listing, and tolerates databases migrated by older versions that lack the melange_version, schema_format or exposure columns. Returns nil when no migrations table exists.

func (*Migrator) GetStatus

func (m *Migrator) GetStatus(ctx context.Context) (*Status, error)

GetStatus returns the current migration status. Useful for health checks or migration diagnostics.

func (*Migrator) HasSchema

func (m *Migrator) HasSchema() bool

HasSchema returns true if the schema file exists. Use this to conditionally run migration or skip if not configured.

func (*Migrator) MigrateWithTypes

func (m *Migrator) MigrateWithTypes(ctx context.Context, types []TypeDefinition) error

MigrateWithTypes performs database migration using pre-parsed type definitions.

The method:

  1. Validates the schema (checks for cycles)
  2. Computes derived data (closure)
  3. Analyzes relations and generates specialized SQL functions
  4. Applies everything atomically in a transaction: - Generated specialized functions and dispatcher

This is idempotent - safe to run multiple times with the same types.

It records no migration and drops no functions: without the schema text there is no checksum to record (use MigrateWithTypesAndOptions with SchemaContent for that). It generates under the recorded exposure, or the default when none is recorded. An exposure set with SetExposure must be that same exposure, otherwise it returns *UnrecordedExposureChangeError and applies nothing.

Uses a transaction if the db supports it (*sql.DB). This ensures the schema is updated atomically or not at all.

func (*Migrator) MigrateWithTypesAndOptions

func (m *Migrator) MigrateWithTypesAndOptions(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) error

MigrateWithTypesAndOptions performs database migration with options. This is the full-featured migration method that supports dry-run, two-phase skip detection, and orphan cleanup.

Skip detection has two phases:

  • Phase 1: If the schema checksum, melange version and exposure all match the last migration, skip entirely without generating SQL.
  • Phase 2: If phase 1 didn't skip (schema, version or exposure changed), generate the SQL and compare function checksums against the last migration. If every function is identical and no orphans exist, skip applying and only record the new migration state.

Orphaned functions (installed by the previous migration, no longer generated) are dropped. When user objects depend on one (see FunctionDependent), migration fails with *DependentObjectsError and applies nothing, unless opts.Force is set, which drops them with CASCADE.

Without opts.SchemaContent there is no checksum to record: it applies on every run, drops the orphans of the latest existing record, records nothing, and refuses an exposure change with *UnrecordedExposureChangeError. Pass the schema text (for an embedded schema, with SchemaFormat FormatSingle) to record the migration.

See MigrateWithTypes for basic usage without options.

func (*Migrator) Plan added in v0.11.0

Plan predicts what MigrateWithTypesAndOptions would do with opts unforced, without changing the database or taking the migration lock: the action, and the orphans an applying (or forced) run drops, with their dependents. opts.Force and opts.DryRun are ignored, and opts.IfDeployedChecksum is not evaluated. It returns the error the migration would fail with before applying anything (a cycle, an invalid exposure, or *UnrecordedExposureChangeError without opts.SchemaContent), except that a database a newer melange migrated is PlanRefusedAhead.

A migration that commits between Plan and the run can change the outcome. A readiness check can wait for PlanSkip: the database then has exactly what this schema, exposure and codegen version generate, as recorded.

func (*Migrator) SchemaPath

func (m *Migrator) SchemaPath() string

SchemaPath returns the path to the schema file.

func (*Migrator) SetDatabaseSchema added in v0.8.0

func (m *Migrator) SetDatabaseSchema(databaseSchema string)

SetDatabaseSchema sets the PostgreSQL schema for melange objects.

func (*Migrator) SetExposure added in v0.11.0

func (m *Migrator) SetExposure(exposure *Exposure)

SetExposure sets the exposure MigrateWithTypesAndOptions uses when its options carry none, and the one MigrateWithTypes generates with. Nil, the initial value, keeps the exposure recorded by the last migration. It takes effect on calls that record a migration; a call that records nothing (MigrateWithTypes, or MigrateWithTypesAndOptions without SchemaContent or DryRun) may only restate the current exposure, and returns *UnrecordedExposureChangeError for any other.

type NamedFunction added in v0.7.4

type NamedFunction = sqlgen.NamedFunction

NamedFunction pairs a function name with its generated SQL body.

type OrphanedFunction added in v0.11.0

type OrphanedFunction struct {
	Name       string
	Dependents []string
}

OrphanedFunction is an installed function an applying migration drops, with the objects that depend on it (as FunctionDependent.Object names them). An unforced migration refuses to drop one with dependents (*DependentObjectsError); a forced one drops them with CASCADE.

type PlanAction added in v0.11.0

type PlanAction string

PlanAction is what an unforced migration would do; see Migrator.Plan.

const (
	// PlanApply applies every generated function, drops the orphans and
	// records the migration (when it has the schema text to record).
	PlanApply PlanAction = "apply"
	// PlanRecordOnly records the migration and applies nothing: the
	// generated SQL is the SQL the last migration recorded (phase 2).
	PlanRecordOnly PlanAction = "record_only"
	// PlanSkip does nothing: the schema, codegen version and exposure match
	// the last migration (phase 1), or the generated SQL and the record both
	// do (phase 2).
	PlanSkip PlanAction = "skip"
	// PlanRefusedAhead applies nothing and returns *DatabaseAheadError: a
	// newer melange migrated the database.
	PlanRefusedAhead PlanAction = "refused_ahead"
)

type Status

type Status struct {
	// SchemaExists indicates if the schema.fga file exists on disk.
	SchemaExists bool

	// TuplesExists indicates if the melange_tuples relation exists (view, table, or materialized view).
	// This must be created by the user to map their domain tables.
	TuplesExists bool
}

Status represents the current migration state. Use GetStatus to check if the authorization system is properly configured.

type TypeDefinition

type TypeDefinition = schema.TypeDefinition

TypeDefinition re-exports schema.TypeDefinition for callers of this package.

type UnrecordedExposureChangeError added in v0.11.0

type UnrecordedExposureChangeError struct {
	Requested Exposure // the requested exposure, normalized
	Recorded  Exposure // the recorded exposure, normalized; the default when HasRecord is false
	HasRecord bool     // whether a migration is recorded
}

UnrecordedExposureChangeError is returned by a migration that records no migration (MigrateWithTypes, or MigrateWithTypesAndOptions without SchemaContent or DryRun) when asked for an exposure other than the one the database is known to have: the latest record's, or the default when none is recorded. Such a migration can neither drop the functions the previous exposure generated nor record the new one, so nothing is applied.

func (*UnrecordedExposureChangeError) Error added in v0.11.0

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL