Documentation
¶
Overview ¶
Package migrator applies compiled OpenFGA schemas to a PostgreSQL database, installing the generated PL/pgSQL functions and tracking applied migrations.
Index ¶
- Constants
- Variables
- func CodegenVersion() string
- func CodegenVersionAhead(deployed string) bool
- func ComputeFunctionChecksums(namedFunctions []NamedFunction) map[string]string
- func ComputeSchemaChecksum(content string) string
- func DeployedTypes(rec *MigrationRecord) ([]schema.TypeDefinition, error)
- func Migrate(ctx context.Context, db Execer, schemaPath string) error
- func MigrateFromString(ctx context.Context, db Execer, content string) error
- func MigrateWithOptions(ctx context.Context, db Execer, schemaPath string, opts MigrateOptions) (skipped bool, err error)
- func SameCodegenVersion(a, b string) bool
- func SameExposure(a, b Exposure) bool
- type DatabaseAheadError
- type DependentObjectsError
- type DeployedModel
- type DeployedModelChangedError
- type Execer
- type Exposure
- type FunctionDependent
- type GeneratedSQL
- type InternalMigrateOptions
- type ListGeneratedSQL
- type MigrateOptions
- type MigrationPlan
- type MigrationRecord
- type Migrator
- func (m *Migrator) ApplyDDL(ctx context.Context) error
- func (m *Migrator) DatabaseSchema() string
- func (m *Migrator) GetDeployedModel(ctx context.Context) (*DeployedModel, error)
- func (m *Migrator) GetLastMigration(ctx context.Context) (*MigrationRecord, error)
- func (m *Migrator) GetMigrationHistory(ctx context.Context, limit int) ([]MigrationRecord, error)
- func (m *Migrator) GetStatus(ctx context.Context) (*Status, error)
- func (m *Migrator) HasSchema() bool
- func (m *Migrator) MigrateWithTypes(ctx context.Context, types []TypeDefinition) error
- func (m *Migrator) MigrateWithTypesAndOptions(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) error
- func (m *Migrator) Plan(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) (*MigrationPlan, error)
- func (m *Migrator) SchemaPath() string
- func (m *Migrator) SetDatabaseSchema(databaseSchema string)
- func (m *Migrator) SetExposure(exposure *Exposure)
- type NamedFunction
- type OrphanedFunction
- type PlanAction
- type Status
- type TypeDefinition
- type UnrecordedExposureChangeError
Constants ¶
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.
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 ¶
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
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 ¶
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 ¶
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:
- Reads the schema file at schemaPath
- Parses OpenFGA DSL using the official parser
- Validates schema (cycle detection, referential integrity)
- Generates specialized check_permission and list_accessible functions
- 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 ¶
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
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
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
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:
- Creates/replaces check_permission and list_accessible_* functions
- 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 ¶
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 ¶
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
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
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 ¶
GetStatus returns the current migration status. Useful for health checks or migration diagnostics.
func (*Migrator) HasSchema ¶
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:
- Validates the schema (checks for cycles)
- Computes derived data (closure)
- Analyzes relations and generates specialized SQL functions
- 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
func (m *Migrator) Plan(ctx context.Context, types []TypeDefinition, opts InternalMigrateOptions) (*MigrationPlan, error)
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 ¶
SchemaPath returns the path to the schema file.
func (*Migrator) SetDatabaseSchema ¶ added in v0.8.0
SetDatabaseSchema sets the PostgreSQL schema for melange objects.
func (*Migrator) SetExposure ¶ added in v0.11.0
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
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
func (e *UnrecordedExposureChangeError) Error() string