CLI Reference
The Melange CLI provides commands for validating schemas, generating client code, and applying migrations to your database. Built on Cobra/Viper, it supports configuration files, environment variables, and command-line flags with consistent precedence.
Installation
go install github.com/pthm/melange@latestGlobal Flags
These flags are available on all commands:
| Flag | Description |
|---|---|
--config | Path to config file (default: auto-discover melange.yaml). See Configuration. |
--env | Select a named environment profile. See Configuration → Environments. |
-v, --verbose | Increase verbosity (can be repeated: -vv, -vvv) |
-q, --quiet | Suppress non-error output |
--no-update-check | Disable automatic update checking |
Any command that connects to a database accepts --env <name> to target one of
the environment profiles defined in your
config (e.g. melange status --env production). An explicit --db still wins
over the environment’s connection.
Update Notifications
By default, Melange automatically checks for new versions in the background and displays a notification if an update is available. The check is:
- Non-blocking: Runs in a background goroutine with a 5-second timeout
- Cached: Results are cached for 24 hours in
melange/update-check.jsonunder the user cache directory (~/.cacheon Linux,~/Library/Cacheson macOS,%LocalAppData%on Windows) - Fast: Uses a 1-second wait time for displaying results
- Respectful: Automatically disabled in CI environments (when
CIenv var is set)
Example notification:
$ melange migrate
Applying authz infrastructure...
Authz schema applied successfully.
* A new version of melange is available: v1.2.3 (current: v1.2.0)
brew upgrade pthm/tap/melangeThe second line is the upgrade command for how melange was installed: brew upgrade pthm/tap/melange for Homebrew, scoop update melange for Scoop, go install github.com/pthm/melange@latest for a binary in $GOBIN or $GOPATH/bin, and otherwise a link to Updating.
To disable update checks:
melange --no-update-check migrateTo clear the cache:
rm -rf ~/.cache/melange/update-check.json # Linux; adjust for your OSThe XDG_CACHE_HOME environment variable, if set, overrides the cache directory on every OS.
Command Groups
Commands are organized into logical groups:
Schema Commands: validate, migrate, status, schema pull, diff, history, doctor, functions, explain, expand, studio
Client Commands: generate client, generate migration
Utility Commands: init, init agent, config show, env list, version, license
Schema Commands
validate
Check a schema without database access: syntax, references to undefined types and relations, unsupported features (conditions), and relation cycles. These are the same checks migrate and generate run before compiling.
melange validate --schema schemas/schema.fgaOutput:
Schema is valid. Found 3 types:
- user (0 relations)
- organization (3 relations)
- repository (5 relations)An invalid schema exits with code 3 and names each problem:
Error: parsing schema: melange: invalid schema: undefined references: document#viewer references "editr", which is not a relation on "document"With --format json, the result is printed to stdout for both outcomes, and an invalid schema still exits non-zero:
{
"valid": false,
"schema": "melange/schema.fga",
"error": "parsing schema: melange: invalid schema: undefined references: ..."
}A valid result lists each type with its relation names under types.
Flags:
| Flag | Default | Description |
|---|---|---|
--schema | schemas/schema.fga | Path to schema.fga or fga.mod file |
--format | text | Output format: text or json |
The schema path can also be set via configuration file or environment variable. See Configuration.
migrate
Apply the schema to your PostgreSQL database.
melange migrate \
--db postgres://localhost/mydb \
--schema schemas/schema.fgaFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--schema | schemas/schema.fga | Path to schema.fga file |
--dry-run | false | Output SQL to stdout without applying changes |
--force | false | Re-apply even if unchanged, and drop removed functions with CASCADE, together with their dependents (see below) |
--if-deployed-checksum | (unset) | Apply only if the deployed schema checksum matches (see below) |
--include-relation | (config sql.relations.include) | Expose only relations matching this pattern; repeatable, replaces the config list |
--exclude-relation | (config sql.relations.exclude) | Do not expose relations matching this pattern; repeatable, replaces the config list |
--no-list-objects | false | Turn off the list_objects family (sets sql.functions.list_objects to false) |
--no-list-subjects | false | Turn off the list_subjects family (sets sql.functions.list_subjects to false) |
--no-accessible | false | Turn off the accessible family (sets sql.functions.accessible to false) |
--no-parent-key | false | Turn off the parent_key family (sets sql.functions.parent_key to false) |
--no-expand | false | Turn off the expand family (sets sql.functions.expand to false) |
--no-explain | false | Turn off the explain family (sets sql.functions.explain to false) |
This command:
- Checks if the schema or the SQL API exposure has changed since the last migration
- Installs generated SQL functions (
check_permission,list_accessible_objects, etc.) - Cleans up orphaned functions from removed relations or a narrower exposure
- Records the migration in
melange_migrationstable — including the schema DSL, parsed model and exposure, so the database is self-describing. This is whatmelange statusandmelange schema pullread back.
SQL API exposure flags:
The exposure flags override the sql: section
of the configuration for this run: a list flag replaces its key (repeat it for
several patterns, or separate them with commas) and a --no-<family> flag sets
that family to false (--no-expand=false turns a family the config disables
back on). Precedence is flag, then MELANGE_SQL_* variable, then config file,
then default.
A family that is off makes its public function raise M2003 for every
relation the model defines. melange explain, melange expand and studio
still work with explain or expand off: they create those functions in
pg_temp for each call (on demand).
Turning off
list_objects or accessible alone removes no per-relation functions, since
list_objects, accessible and parent_key read each other; see
Exposure for what is installed.
migrate always applies the exposure it resolves to. Without an sql:
section and without flags that is the default exposure, so a database
restricted earlier is widened back. Flags are not remembered: the next
migrate without them applies the config again. Keep a lasting restriction in
melange.yaml. A pattern that matches no relation of the schema prints a
warning.
melange generate client follows the sql: section, never these flags. When
generate.client.runtime is configured and the flags make the exposure differ
from the section, migrate warns that the generated client may name functions
or relations this migration does not install. It still migrates; check the
client afterwards with melange generate client --check --db.
# Expose only the can_* relations, without the expand and explain functions
# (melange explain and expand then compile them on demand)
melange migrate --include-relation 'can_*' --no-expand --no-explainSkip-if-unchanged behavior:
Melange tracks schema changes using a SHA256 checksum. If you run migrate and the schema hasn’t changed since the last migration, it will be skipped automatically:
Schema unchanged, migration skipped.
Use --force to re-apply.The codegen version is part of this check, so a plain migrate re-applies
after a Melange upgrade that changes the generated SQL; no --force is needed.
Use --force only when the functions in the database were changed or dropped
outside Melange. It also drops functions the new SQL no longer generates with
CASCADE, together with any views or policies that call them, instead of
refusing (see Dependent objects and --force below).
A change to the exposure alone is not skipped: it re-applies even when the schema checksum is unchanged.
Drift-safe apply (--if-deployed-checksum):
--if-deployed-checksum turns migrate into a compare-and-swap: it applies only if
the database is currently at the schema checksum you pass, otherwise it aborts
having changed nothing and exits non-zero. This closes the window where someone
else migrates the database between the time you plan a change and the time your
deploy applies — which last-writer-wins would silently clobber.
The intended CI pattern reads the current checksum from status, then gates the
apply on it:
CURRENT=$(melange status --env production --format json | jq -r .deployed.schema_checksum)
# review / plan the change …
melange migrate --env production --if-deployed-checksum "$CURRENT"On a mismatch:
Error: migration aborted: deployed model changed: expected checksum abc… but database has def…; nothing was appliedAn empty value (--if-deployed-checksum "") matches a database with no migration
recorded (a fresh database). The guard compares only the schema checksum: an
exposure the database was migrated with that differs from the local one does
not abort it. The guard is enforced in --dry-run too, so a
drift-gated preview aborts rather than printing SQL against a drifted database.
Concurrent migrations and downgrades:
Migrations against the same database schema are serialized with a
transaction-scoped advisory lock, so replicas that all run migrate on startup
are safe: the first applies, and the rest see its record under the lock and
skip.
migrate also refuses to replace functions generated by a newer melange. During
a rolling deploy, a replica still on the old version would otherwise overwrite
the upgraded functions on every restart, undoing codegen fixes:
Error: migration refused: database functions were generated by melange 0.11.0, newer than this melange (0.10.0); nothing was applied (upgrade melange, or force the migration to downgrade deliberately)The refusal exits with code 5. The newer functions keep the same SQL API, so an old replica can keep serving; a startup script can treat code 5 as success:
melange migrate || [ $? -eq 5 ]Pass --force to downgrade deliberately. Versions that cannot be ordered are
never refused: development builds (dev) and local git describe builds such
as v0.10.0-3-gabc1234.
Dry-run mode:
Preview the migration SQL without applying it:
melange migrate --db postgres://localhost/mydb --dry-runThis outputs the complete SQL that would be executed, including:
- DDL for the migrations tracking table
- All generated check functions
- All generated list functions
- Dispatcher functions
- Drops of orphaned functions
- The migration record insert
Unless --force is given, the script starts with a guard block that fails
when an orphaned function has dependents at the time the script runs, and
drops orphans without CASCADE. The script has no BEGIN/COMMIT of its
own, so apply it in one transaction that stops at the first error:
psql -v ON_ERROR_STOP=1 --single-transaction -f migration.sqlDry-run output goes to stdout, so you can redirect it:
melange migrate --db postgres://localhost/mydb --dry-run > migration.sqlOrphan cleanup:
When you remove a relation from your schema, or narrow the exposure, Melange automatically drops the orphaned SQL functions during migration. For example, if you remove the editor relation from document, the next migration will drop check_document_editor, list_document_editor_obj, etc.
Dependent objects and --force:
A view, materialized view, row-level security policy, rule or BEGIN ATOMIC
function that calls an orphaned function blocks its drop. migrate checks for
such dependents before applying anything and refuses, listing them:
Error: migration refused (rerun with --force to drop the dependents): migration would drop functions that other database objects depend on; nothing was applied (remove or change the dependents, or force the migration to drop them with CASCADE):
policy docs_read on table docs depends on accessible_document_viewerChange or remove the dependents, then migrate again. --force (or
migrate.force: true) overrides the refusal and drops the orphans with
CASCADE, which drops the dependents too. Dropping an RLS policy widens access
to its table, so review the list before forcing. See
Dependent objects.
melange_tuples warning:
After migration, if the melange_tuples view doesn’t exist, you’ll see a warning:
WARNING: melange_tuples view/table does not exist.
Permission checks will fail until you create it.See Tuples View for setup instructions.
status
Show whether the schema file and melange_tuples view are present, what model
the database has deployed, and whether the local schema file is in sync with it.
melange status \
--db postgres://localhost/mydb \
--schema schemas/schema.fgaFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--schema | schemas/schema.fga | Path to schema.fga file |
--format | text | Output format: text or json |
status also takes the SQL API exposure flags (--include-relation,
--exclude-relation, --no-<family>), which override the sql: section of the
configuration for the comparison below.
Output:
Schema file: present
Tuples view: present
Deployed: checksum d0c1746f7e26… · melange v0.9.0 · 2026-07-01T20:46:10Z
Sync: in sync — local schema matches deployedWhen the local schema has drifted, the change summary follows the Sync line:
Schema file: present
Tuples view: present
Deployed: checksum d0c1746f7e26… · melange v0.9.0 · 2026-07-01T20:46:10Z
Sync: drift — local schema differs from deployed (`melange diff` to see changes, `melange migrate` to apply)
1 breaking, 2 additive
+ type audit_log added
+ relation document.can_export added
- relation document.legacy_viewer removedAt most five changes are listed; run melange diff for the full list. The
summary is omitted when the deployed model was never recorded, when either side
fails to parse (a Note: explains why), or when the two models are semantically
equivalent — reformatting or a comment edit moves the checksum without changing
behavior, and that is reported as drift with no changes to show.
The Deployed line reports the model recorded by the most recent migration (checksum, melange version, and time). The Sync state compares the local schema file’s checksum against the deployed one:
| Sync state | Meaning |
|---|---|
in_sync | The local schema matches what’s deployed |
drift | The local schema differs — run melange migrate to apply |
exposure_drift | The schema matches, but the local SQL API exposure differs from the recorded one; melange migrate would re-apply |
database_ahead | Drift where the deployed model is in no recent commit of your schema file |
unknown | No local schema file to compare against |
not_recorded | The database has no migration record |
database_ahead is the warning case: the deployed model is not the local file
and is not any version of it in your schema’s git history, so someone migrated
that database from a different checkout — applying your local schema would
overwrite their model rather than move the database forward. Check with
melange schema pull before migrating, and use
melange migrate --if-deployed-checksum to make the apply conditional.
The probe is advisory and errs toward plain drift. It follows the schema across
renames and reads each revision as a checkout would (so end-of-line conversion
doesn’t cause spurious mismatches), and it stays silent whenever it cannot search
every version:
- outside a git repository, or without git installed
- in a shallow (
--depth) or partial clone — CI checkouts are shallow by default, so this is the common case in automation - when the schema is uncommitted or has local modifications: migrating from a dirty working tree is routine, so the deployed model may be a version git never saw
- for modular (
fga.mod) schemas, whose checksum covers the manifest plus every module - for a schema with more than 50 commits of history, past which the search is no longer exhaustive
- when the two models are semantically equivalent — a checksum that moved on formatting or comments alone is drift, never an allegation
Treat it as a prompt to look, not a verdict: it reports what git could see, and git cannot see every place a model may have come from.
The local exposure is the one melange migrate would apply: the sql: section
of the configuration with any exposure flags given to status. Without either
it is the default exposure, so a database restricted with flags only reports
exposure_drift. When the recorded exposure is not the default, text output
shows it on an Exposure: line and JSON output as deployed.exposure.
Databases migrated before model storage existed (or by MigrateWithTypes) have no recorded model
DSL; status notes this and melange schema pull cannot recover them. Reading the
migration record is non-fatal — if it fails, status still reports schema/tuples
presence and adds a Note: line.
JSON output (--format json) emits the machine-readable report, including a
notes array for any non-fatal warnings:
{
"schema_file": "present",
"tuples_view": "present",
"sync": "in_sync",
"deployed": {
"melange_version": "v0.9.0",
"migrated_at": "2026-07-01T20:46:10Z",
"schema_checksum": "d0c1746f7e26ea40027a24b1c0e0c5f34e279e7c27f6fa17e4611ce2f1ec0962",
"schema_format": "single",
"model_recorded": true
}
}When the sync state is drift or database_ahead and both models are
available, a drift object
carries the same detail as the text output — the counts plus every change, not
just the first five. Changes are sorted by type, then relation, so the order is
stable across runs:
{
"sync": "drift",
"deployed": { "schema_checksum": "d0c1746f7e26…", "model_recorded": true },
"drift": {
"additive": 2,
"breaking": 1,
"changes": [
{ "class": "additive", "type": "audit_log", "summary": "type audit_log added" },
{ "class": "additive", "type": "document", "relation": "can_export", "summary": "relation document.can_export added" },
{ "class": "breaking", "type": "document", "relation": "legacy_viewer", "summary": "relation document.legacy_viewer removed" }
]
}
}schema pull
Reconstruct the OpenFGA schema recorded by the most recent migration. Use it to recover a schema whose source file was lost, or to see exactly what model a database is running.
# Print the deployed schema
melange schema pull --db postgres://localhost/mydb
# Recover it to a file, targeting a named environment
melange schema pull --env production -o recovered.fgaFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
-o, --output | (stdout) | Write to this file instead of stdout |
--no-header | false | Omit the provenance header comment |
Output:
# Pulled from a melange-migrated database by `melange schema pull`
# Deployed: 2026-07-01T20:46:10Z by melange v0.9.0
# Schema checksum: d0c1746f7e26ea40027a24b1c0e0c5f34e279e7c27f6fa17e4611ce2f1ec0962
model
schema 1.1
type user
...The provenance header is written as # comments (valid DSL), so the output still
parses; the database URL is never included. Pass --no-header for the bare
schema, which for a single-file schema is byte-identical to what you migrated.
fga.mod) schema is emitted as the stored manifest + module
bundle for reference/recovery. That combined form does not re-parse as a
single .fga, and splitting it back into module files is not supported.Requires a database migrated by a version that records the model. Older databases did not record the model; pull reports whether the database was never migrated or was migrated before model storage existed.
diff
Show what changed between a deployed (or previous) model and your local schema, with each change classified additive (safe — widens access or adds structure) or breaking (narrows access or removes structure).
# What would migrating apply to production?
melange diff --env production
# Compare against the schema on main, or a previous file
melange diff --git-ref main
melange diff --previous-schema old.fgaFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | Database to compare against (the default source) |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--schema | schemas/schema.fga | Local .fga — the new side of the diff |
--git-ref | (unset) | Compare against your schema at a git commit/branch/tag |
--previous-schema | (unset) | Compare against a previous .fga file (modular not supported) |
--format | tree | Output format: tree (default) or json |
--exit-code | false | Exit 1 if any change is breaking (CI gate) |
The comparison source is the deployed model by default (--db/--env, or the
configured database); --git-ref and --previous-schema select a file/git
source instead and are mutually exclusive with a database source.
Output:
Comparing deployed → melange/schema.fga
additive type audit_log added
BREAKING relation document.legacy removed
additive document.viewer grants [org]
1 breaking, 2 additiveClassification reflects melange’s compiled model and is deliberately conservative:
it accounts for implied-by closure, intersection subsumption, and exclusion
polarity, and it never under-reports a breaking change — so --exit-code is safe
as a CI gate. --format=json emits the structured SchemaDiff for tooling.
history
List recent entries from the melange_migrations table — when each migration
ran, the melange version, the schema checksum, and how many functions it
installed. An audit trail of how a database’s model has evolved.
melange history --db postgres://localhost/mydbFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--format | text | Output format: text (default) or json |
--limit | 20 | Maximum number of entries to show |
Output:
Migration history (most recent first):
2026-07-02T20:46:10Z · melange v0.9.1 · checksum 550b0008a779… · single · 23 functions
2026-07-01T18:12:03Z · melange v0.9.0 · checksum 0ba53b1429e9… · single · 17 functionsdoctor
Run comprehensive health checks on your authorization infrastructure.
melange doctor \
--db postgres://localhost/mydb \
--schema schemas/schema.fgaFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--schema | schemas/schema.fga | Path to schema.fga file |
--verbose | false | Show detailed output with additional context |
--skip-performance | false | Skip performance checks (view analysis) |
--skip-client | false | Skip the Generated Client checks |
--strict-client | false | Fail, rather than warn, when the generated client names something the database does not answer for |
--format | text | Output format: text or json |
doctor also takes the SQL API exposure flags (--include-relation,
--exclude-relation, --no-<family>), which override the sql: section of the
configuration for the exposure checks. They do not reach the Generated Client
checks, which read melange.yaml only.
With --format json, the report is a list of checks (each with category, name, status of pass, warn, or fail, message, and optional details and fix) plus passed, warnings, and errors counts. The command exits non-zero when any check fails.
Output:
melange doctor - Health Check
Schema File
✓ Schema file exists at schemas/schema.fga
✓ Schema is valid (3 types, 8 relations)
✓ No cyclic dependencies detected
Migration State
✓ melange_migrations table exists
✓ Schema migrated (24 functions tracked)
✓ Schema is in sync with database
Generated Functions
✓ All dispatcher functions present
✓ All 24 expected functions present
Tuples Source
✓ melange_tuples exists (view)
✓ All required columns present
Data Health
✓ melange_tuples contains 1523 tuples
✓ All sampled tuples reference valid types and relations
Performance
✓ View definition parsed (3 branches)
✓ View uses UNION ALL (no unnecessary deduplication)
✓ Source tables: users, organizations, repositories
✓ All ::text cast columns have expression indexes
Summary: 15 passed, 0 warnings, 0 errorsThe doctor command performs the following checks:
Schema File:
- Verifies the schema file exists
- Parses the schema and checks for undefined types and relations
- Detects cyclic dependencies in implied-by relationships
Migration State:
- Checks if the
melange_migrationstracking table exists - Verifies a migration has been applied
- Compares schema checksum to detect if schema has changed since last migration
- Checks if codegen version has changed (indicating Melange was updated)
- Compares the local SQL API exposure (the
sql:section and exposure flags) with the one the database was migrated with, and warns when they differ (exposure_sync)
Generated Functions:
- Verifies all dispatcher functions exist (
check_permission,list_accessible_objects, etc.) - Compares expected functions from schema against actual functions in database. The expected set follows the exposure the database was migrated with, so a restricted database reports no missing functions
- Identifies orphan functions: installed functions the last migration recorded that the schema no longer generates. A function only named like a generated one (your own
explain_invoice) is not an orphan, since no migration recorded it. Without a migration record nothing is an orphan, sincemelange migratedrops only recorded functions - Warns about exposure patterns that match no relation in the schema (
exposure_patterns), usually a typo or a renamed relation
Generated Client (when generate.client.runtime is configured):
The same check as melange generate client --check --db, from generate.client.* and the sql: section of melange.yaml (or their MELANGE_* variables) alone. A client generated with relation flags can only be compared with what the configuration generates, so keep the selection in generate.client.relations.
client_file: the files undergenerate.client.outputagainst a fresh generation. Skipped when the directory does not exist (a production image without sources;--verbosesays so). A difference is a warning; a file that cannot be read, or a configuration that does not generate, is a failureclient_functions: every accessible function name the client uses against the functions installed by the last migrationclient_relations: every relation the client has a constant for against the relations the database exposes
A client name the database does not answer for is a warning by default, since the working tree may be ahead of the database: run doctor after migrate. --strict-client or doctor.strict_client: true makes it a failure. The details list the first 10 findings, and the fix hint follows what a plain migrate would do, as below. --skip-client or doctor.skip_client: true skips the category.
Tuples Source:
- Verifies
melange_tuplesview/table exists - Checks required columns:
object_type,object_id,relation,subject_type,subject_id - Warns if using a materialized view (requires manual refresh)
Data Health:
- Reports tuple count
- Validates that tuples reference valid types and relations defined in the schema
Performance (view-based melange_tuples only):
Performance checks run automatically when melange_tuples is a view (not a table or materialized view). They can be disabled with --skip-performance.
- Parses the view definition via
pg_get_viewdef()and reports the number of UNION branches and source tables - Detects bare
UNION(warns to useUNION ALLinstead, sinceUNIONadds deduplication overhead) - Checks for missing expression indexes on columns cast with
::textin the view definition. Missing indexes cause sequential scans on the source tables:- Warning if the source table has fewer than 10,000 rows (recommended for future scaling)
- Failure if the source table has 10,000+ rows (critical at current scale)
- Provides exact
CREATE INDEXstatements as fix hints - A
varcharortextcolumn needs no expression index: casting it totextis a relabel, so an ordinary index on the column serves the lookup.char(n),uuidand numeric columns need the::textexpression index.
- Checks each single-table branch for a composite index covering object lookups: the columns behind
object_id, thenrelation(when it comes from a column), thensubject_id. Without one, a check on a membership-style table reads every row for the object. Branches whose object or subject column is unique, that join tables, or whose ids are computed are skipped. Warns with the exactCREATE INDEXfor the source table. - Checks each branch whose subject id is a column, joined branches included, for an index leading with that column (its
::textexpression when the cast converts the value). List functions look tuples up by a set of subject ids, and without the index each row of the branch is compared with the whole set. Severity follows the table’s size, as for expression indexes. A cast column with no index at all is reported once, by the expression index check.
Expand Fan-Out Advisory:
Runs whenever melange_tuples exists (both view and table backends). Flags relations whose Expand response can grow large depending on tuple counts:
- Wildcard grants (
[user:*]): every Expand response surfaces the wildcard entry (user:*). Downstream consumers that enumerate the wildcard client-side hit unbounded fan-out. - Recursive TTU (
viewer from parenton a self-referential type):ExpandRecursivewalks the parent pointer chain, so a deep hierarchy multiplies round-trip cost.
The advisory is StatusPass, a hint rather than a diagnosed problem. It suggests capping each leaf per call with WithExpandMaxLeaf, --max-leaf or expand_permission’s p_max_leaf. See Expanding Permissions.
Verbose mode:
Use --verbose to see additional details for each check:
melange doctor --db postgres://localhost/mydb --verboseThis shows:
- Exact file paths and checksums
- Lists of missing or orphan functions
- Specific unknown types or relations found in data
Common issues and fixes:
| Issue | Fix |
|---|---|
| Schema file not found | Create schemas/schema.fga |
| Schema is invalid | Run melange validate for the specific errors |
| Schema out of sync | Run melange migrate |
| Exposure out of sync | Run melange migrate, or change the sql: section back |
| Pattern matches nothing | Fix the pattern in the sql: section |
| Missing functions | Run melange migrate, or --force when the fix hint says so |
| Generated client differs | Run melange generate client; keep the relation selection in melange.yaml |
| Client names what the database lacks | Run melange migrate with melange.yaml’s sql: section, or regenerate the client |
| Orphan functions | Run melange migrate (cleanup is automatic); change their dependents first if any |
| melange_tuples missing | Create a view over your domain tables |
| Missing columns | Update melange_tuples to include all required columns |
| Unknown types in tuples | Update tuples view or schema to match |
| UNION instead of UNION ALL | Replace UNION with UNION ALL in view definition |
| Missing expression index | Run the CREATE INDEX command shown in the fix hint |
Fix hints:
A fix hint that suggests melange migrate says what an unforced melange migrate of the local schema and exposure would do:
- When it would apply, the hint is a plain
melange migrate. If that migrate would drop removed functions that other objects depend on, which it refuses to do, the hint names the dependents to change or drop first. This covers functions a narrowed exposure stops installing, which the orphan check does not list. - When it would skip (schema, exposure and codegen version unchanged) or only record (the generated SQL is the SQL the last migration recorded), it cannot restore functions dropped or edited by hand, or a stored model that cannot be decoded. The hint is
melange migrate --force, with the reason. It says how many removed functions--forcedrops withCASCADEand names their dependents. - When a newer melange migrated the database, this melange’s migrate refuses to downgrade it, so the hint names that version. It never suggests
--forcewith this melange, which would override the refusal. A stored model that cannot be decoded is rewritten by re-running migrate with the newer melange, so that hint may suggest--forcewith the newer version. - Orphans that views, policies or functions depend on are listed with their dependents:
melange migraterefuses to drop them, so change or drop the dependents first, or--forcedrops them withCASCADE.
These checks compare the database with the local schema file. melange functions --db and studio’s SQL API page compare it with the deployed model and the exposure the last migration recorded, so while a migration is pending doctor reports what migrate would add and functions reports what the deployed model is missing.
functions
List the SQL functions melange generates for each relation: whether the exposure exposes the relation or it is internal (modelling only), and every function a migration installs for it under its exact name. Names longer than PostgreSQL’s 63 bytes are truncated with a hash, so this is where to look them up rather than building them by hand.
# The SQL API of the local schema and the sql: section of melange.yaml
melange functions
# What the database has installed, compared with its deployed model
melange functions --db postgres://localhost/mydb
# One relation: signatures, example calls, dependencies, and why a family is missing
melange functions show document#viewerSource. As for diff, an explicit database (--db, --env or
MELANGE_ENV) means database mode; otherwise the command reads files only:
- Database mode reads the model and exposure the last migration recorded
(as
schema pulland studio do) and checks each expected function inpg_procof--db-schema: installed, missing, installed with other arguments (signature_differs), or with another body. A body is compared with the one this melange generates for the deployed model; it isbody_changedwhen the migration recorded the same one (someone edited it in the database) andcodegen_differswhen this melange generates another (the nextmigratereplaces it). Other functions of the same name are stale overloads. Installed functions the last migration recorded that the model no longer generates are orphans; functions only named like generated ones (check_invoice) are listed as unmanaged and never counted as drift. When the functions were generated by another melange version, a note above the list says so. When that version is newer than this melange, itsmigraterefuses to replace or drop anything, so the orphans andcodegen_differsbodies are the newer melange’s: use that version. A database whose last migration recorded no model is compared with--schema(orschemain the config) under the recorded exposure; one with no migration record at all, such as a database built frommelange generate migrationfiles, under the localsql:section, which those files were generated with. - File mode reads the schema file and the
sql:section of the configuration, with the exposure flags on top, asmigratewould apply them. Statuses arenot_checked.
functions only reads. The exposure flags are refused in database mode,
which reports the recorded exposure.
Flags:
| Flag | Default | Description |
|---|---|---|
--db | PostgreSQL connection string: database mode | |
--db-schema | (config, else public) | PostgreSQL schema the functions are in; qualifies the example calls |
--schema | (config) | Schema file (file mode, or a database that records no model) |
--format | text | text or json |
--type | Only this type’s relations (repeatable; list only) | |
--kind | Only functions of this kind (repeatable; list only): check, check_nw, list_objects, list_subjects, accessible, parent_key, expand, explain, dispatcher | |
--exposed / --internal | Only exposed, or only internal, relations (list only) | |
--include-relation, --exclude-relation, --no-<family> | Exposure flags, file mode only |
List output groups by type, then relation, with each function’s name,
kind, whether applications call it (public: the dispatchers, the
accessible functions of exposed relations and their parent-key forms) or a
dispatcher routes to it (internal), and its status. Notes (codegen
version skew, a missing record) follow the header, above the list.
Dispatchers follow the relations, then orphans, unmanaged functions and name
collisions:
Source: database schema app (deployed model)
Exposure: {"relations":{"include":["can_*"]},"functions":{}}
Functions: 251 for 45 relations (23 exposed), dispatchers included
Status: all 251 installed
pull_request
can_read_security_advisories_and_vulnerability_reports exposed
check_pull_req_can_read_security_advisories_and_vulner_d0edb52c check internal installed (truncated)
list_pull_req_can_read_security_advisories_and_vul_d0edb52c_obj list_objects internal installed (truncated)
list_pull_req_can_read_security_advisories_and_vul_d0edb52c_sub list_subjects internal installed (truncated)
accessible_pull_re_can_read_security_advisories_and_vu_d0edb52c accessible public installed (truncated)
accessible_pull_r_can_read_security_advisories_and_vul_e8c3d69b parent_key public installed (truncated)
expand_pull_req_can_read_security_advisories_and_vulne_d0edb52c expand internal installed (truncated)
explain_pull_req_can_read_security_advisories_and_vuln_d0edb52c explain internal installed (truncated)
...show <type#relation> adds, for each function, its signature and
language, an example call that runs as written (argument order differs by
kind: check, explain, list objects and accessible take the subject first;
list subjects and expand take the object; an accessible function is inlined
into the calling query, so its note says the schema holding
melange_tuples must be on the search_path), how an application uses the
result, and the installed functions its body may call, from the model
analysis. A parent-key function returns ids of the parent type, so its usage
filters on the link column. type.relation also works. Families that are not
installed say why: the relation is not exposed, the family is off (explain and
expand are then compiled on demand by the CLI and studio), the relation’s
rewrite is not eligible for explain or expand, or it has no access path (no
function is generated, and the dispatchers deny it, or raise M2003 when
the exposure leaves it out). Not exposed wins over a
family that is off when no exposed relation resolves through the relation,
since turning the family on, or compiling on demand, installs nothing for it:
accessible_pull_r_can_read_security_advisories_and_vul_e8c3d69b
kind: parent_key, public · installed
name: truncated to 63 bytes with a hash of the type and relation; copy it from here or the generated client
signature: accessible_pull_r_can_read_security_advisories_and_vul_e8c3d69b(p_subject_type text, p_subject_id text) RETURNS TABLE(object_id text) · LANGUAGE plpgsql
link: repo → repository (reads can_admin)
example: SELECT object_id FROM accessible_pull_r_can_read_security_advisories_and_vul_e8c3d69b('user', 'alice');
usage: WHERE <repo column> IN (SELECT object_id FROM accessible_pull_r_can_read_security_advisories_and_vul_e8c3d69b('user', 'alice'))
calls: accessible_repository_can_admin
note: Returns repository ids, not pull_request ids: filter pull_request rows on their repo column. ...JSON output (--format json, for both forms) is one report:
| Field | Description |
|---|---|
source | database or file |
schema_file, database_schema | Where the model came from, and the schema the functions are in |
melange_version, deployed_codegen_version, codegen_skew, codegen_ahead | This melange’s codegen version, the deployed one, whether they differ, and whether the deployed one is newer |
checked, bodies_checked | Whether statuses (and bodies) come from the database |
exposure | The normalized exposure ({} parts are the default) |
summary | Counts over the whole model, whatever the filters: relations, exposed, functions, installed, missing, signature_differs, body_changed, codegen_differs, stale_overloads, orphans, unmanaged |
relations[] | type, relation (as the model spells them), exposed, dispatchers (the public ones that answer for it), examples[] (dispatcher, example, and usage for accessible_objects: a call of each of dispatchers for this relation), depends_on (type#relation), functions[], not_installed[] (kind, reason: not_exposed, family_off, on_demand, not_eligible or no_access_path, detail) |
relations[].functions[] | name (the SQL name), kind, public, type, relation, link, parent_type, parent_relations, truncated, signature (args[] of name, type, default; returns, language, paged), example, usage, calls, note, status (not_checked, installed, missing, signature_differs, body_changed, codegen_differs), detail, stale_overloads |
dispatchers[] | The same fields, with answers (the relations it routes, type#relation) and rendered_with (the public dispatcher created in the same SQL) |
orphans[], unmanaged[] | name and arguments of installed functions the model does not generate |
collisions[] | name and owners: a name generated for more than one relation (for example a_b#c and a#b_c). CREATE OR REPLACE keeps the last; rename one of them |
notes[] | Codegen version skew, a missing record, collisions |
explain
Return the resolution trace for a check — every attempted branch, contributing tuples, per-branch success/failure. See the Explaining Decisions guide for the trace structure.
melange explain user:alice viewer document:1 --db postgres://localhost/mydbFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--format | tree | tree (unicode pretty-print) or json (raw Trace JSONB) |
--max-nodes | 0 | Cap on trace nodes. 0 defers to the session GUC melange.max_explain_nodes, then to 100 |
--color | auto | auto (TTY + NO_COLOR unset), always, or never. See Colour Output below. |
Tree output:
✓ user:alice has viewer on document:1 └── via userset: via [group#member] → group:engineering └── direct: user:alice → member → group:engineering
Failure with attempted branches:
✗ user:bob does NOT have viewer on document:1 └── union of 3 branches ├── ✗ no direct grant ├── ✗ implied: implied via editor └── ✗ via userset: via [group#member] → group:engineering └── union of 1 branches └── ✗ no direct grant
--format=json returns the raw Trace JSONB for tooling.
Explain reads the exposure recorded by the last
migration. When the relation is not exposed, it exits with an error that
names type#relation and the setting to change instead of the database’s
M2003: sql.relations.include (or --include-relation, which replaces the
list, so pass it with every pattern already included). A relation the model
does not define is still explained as denied.
When the database was migrated with sql.functions.explain off, explain
compiles the explain functions from the recorded model and creates them in
pg_temp for one rolled-back transaction
(on demand). That needs a writable
primary, the TEMP privilege and a melange of the recorded codegen version;
otherwise explain exits with an error that says which is missing and how to
fix it, including turning sql.functions.explain back on.
expand
Return the OpenFGA-shaped UsersetTree for a (object, relation) pair — the structured “who has access?” answer. See the Expanding Permissions guide for the tree structure and the shallow-by-default resolution model.
melange expand document:1 viewer --db postgres://localhost/mydbFlags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--format | tree | tree (unicode pretty-print) or json (raw UsersetTree JSONB) |
--flatten | false | Print the flat, deduplicated user list instead of the tree. Leaf.Users only — computed and TTU pointers are not chased |
--recursive | false | Print the flat list and chase Leaf.Computed / TTU pointers with follow-up Expand calls (implies --flatten) |
--subject-type | (unset) | Melange extension. Narrow Leaf.Users to a single subject type |
--max-leaf | 0 | Melange extension. Cap each Leaf.Users list. 0 means no cap |
--color | auto | auto (TTY + NO_COLOR unset), always, or never. See Colour Output below. |
Tree output:
document:1#viewer • union of 2
├── document:1#viewer • users
│ ├── user:alice
│ ├── user:bob
│ └── group:eng#member
└── document:1#viewer • computed pointer
└── computed → document:1#editor (melange expand document:1#editor to chase)Flattened user list:
$ melange expand document:1 viewer --flatten
group:eng#member
user:alice
user:bob--flatten lists the users in the tree’s Leaf.Users, sorted, and does not chase pointers. --recursive chases every Leaf.Computed and Leaf.TupleToUserset pointer with follow-up Expand calls. Cost is N round-trips per N distinct pointers; suitable for admin flows, not the request path. --format=json returns the raw UsersetTree JSONB for tooling.
Expand follows the recorded exposure like
explain: a relation expand_permission does not answer for fails with a
message that names type#relation and the setting to change
(sql.relations.include). expand_permission answers for every relation an
exposed relation’s pointers lead to, so --recursive and pointers into
relations that are installed but not exposed keep working. With
sql.functions.expand off, expand creates the expand functions in pg_temp
on demand, as explain does, and
--recursive makes all its calls in that one transaction.
studio
Serve a local, read-only web console for a database (experimental). The model is read from the database, so no schema file is required. See the Studio guide for the pages, required privileges, and limits.
melange studio --env staging
melange studio --db postgres://localhost/mydb --addr 127.0.0.1:7070Flags:
| Flag | Default | Description |
|---|---|---|
--db | (from config) | PostgreSQL connection string |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--schema | (config, else schemas/schema.fga) | Local schema file for the Health page’s file and drift checks |
--addr | 127.0.0.1:0 | Loopback address to listen on. Port 0 picks a free port. Non-loopback addresses are refused |
Studio prints its URL on stderr and runs until Ctrl-C. Every connection is opened with default_transaction_read_only=on. Two features open a read-write transaction that is always rolled back: Explain with what-if tuples, which creates a temporary view, and Explain or Expand against a database migrated with sql.functions.explain or sql.functions.expand off, which creates those functions in pg_temp (on demand). Both need a writable primary and the TEMP privilege. The global --no-update-check flag also hides the top bar’s update badge.
Colour output
melange explain and melange expand colourise identifiers in tree output to match the OpenFGA VS Code extension’s openfga-dark theme. Types render green, relations cyan, type restrictions ([user], [group#member]) mint, keywords / delimiters grey, dim prose and tree connectors dim grey. The ✓ / ✗ result markers in the header render as bold white glyphs on a coloured background chip.
Colours are emitted as 24-bit ANSI true colour so the mapping matches the VS Code palette on modern terminals. --color=never disables all escapes for piped writers or legacy terminals. --color=auto (default) enables colour when stdout is a TTY and NO_COLOR is unset.
--format=json output is never colourised — the raw JSONB is unaffected by --color.
Client Commands
generate client
Generate type-safe client code from your schema: type and relation constants, constructors, and the exact names of the accessible functions migrate installs. See Generated Code for the output.
melange generate client \
--runtime go \
--schema schemas/schema.fga \
--output internal/authz \
--package authzThe client follows the sql: section of melange.yaml: relation constants for the relations sql.relations exposes (or generate.client.relations when set), and function names for what a migration with sql.relations and sql.functions installs for them. The --no-<family> flags of migrate are not seen here, so keep the families in melange.yaml. See Which Relations.
Flags:
| Flag | Default | Description |
|---|---|---|
--runtime | (required) | Target runtime: go, typescript |
--schema | schemas/schema.fga | Path to schema.fga file |
--output | stdout | Output directory for generated code |
--package | authz | Package name for generated code |
--id-type | string | ID type for constructors (string, int64, uuid.UUID) |
--include-relation | generate.client.relations.include, see below | Generate constants only for relations matching this pattern, relation or type#relation (repeatable) |
--exclude-relation | generate.client.relations.exclude, see below | Generate no constants for relations matching this pattern (repeatable). With no client include pattern, it narrows the inherited sql.relations |
--filter | "" | Deprecated: a relation name prefix applied after the patterns. Use --include-relation 'can_*' |
--check | false | Write nothing: compare the output directory with a fresh generation, and with a database the client’s names with it (see below) |
--db | With --check: the database to check the client’s names against. The database check runs only with --db, --env or MELANGE_ENV (with --env, the configured database with that environment applied); database.url alone does not start it | |
--db-schema | (config, else public) | With --check: the PostgreSQL schema melange was migrated into |
--format | text | With --check: output format, text or json |
--strict | false | With --check: exit 1 on warnings too |
--db, --db-schema, --format and --strict without --check are a configuration error (exit 2).
The relation patterns resolve with the precedence flag, MELANGE_GENERATE_CLIENT_RELATIONS_* variable, generate.client.relations in the config file, then sql.relations, then every relation. Each list follows that precedence on its own. Without a client include pattern the client starts from sql.relations, include and exclude, and client exclude patterns only narrow it: --exclude-relation can_edit gives constants for the exposed relations except can_edit. A client include pattern replaces sql.relations, so the client can also name relations migrate does not expose (such as roles used when writing tuples).
When generate.client.runtime is configured and --include-relation, --exclude-relation or --filter is given, the command prints a hint to stderr: doctor and --check without the flags read generate.client.relations from melange.yaml, so the patterns belong there.
Example with all options:
melange generate client \
--runtime go \
--schema schemas/schema.fga \
--output internal/authz \
--package authz \
--id-type int64 \
--include-relation 'can_*'Output to stdout:
melange generate client --runtime go --schema schemas/schema.fgaGenerated code example:
// schema_gen.go
package authz
import "github.com/pthm/melange/melange"
// Object types
const (
TypeUser melange.ObjectType = "user"
TypeOrganization melange.ObjectType = "organization"
TypeRepository melange.ObjectType = "repository"
)
// Relation constants (the relations matching "can_*")
const (
RelCanRead melange.Relation = "can_read"
RelCanWrite melange.Relation = "can_write"
RelCanDelete melange.Relation = "can_delete"
)
// Accessible function names, as installed
const (
SQLAccessibleRepositoryCanRead = "accessible_repository_can_read"
)
// Type-safe constructors
func User(id int64) melange.Object {
return melange.Object{Type: TypeUser, ID: fmt.Sprint(id)}
}
func Repository(id int64) melange.Object {
return melange.Object{Type: TypeRepository, ID: fmt.Sprint(id)}
}
// Wildcard constructors
func AnyUser() melange.Object {
return melange.Object{Type: TypeUser, ID: "*"}
}Supported runtimes:
| Runtime | Description |
|---|---|
go | schema_gen.go: constants, constructors and accessible function name constants |
typescript | types.ts, schema.ts, sql.ts, index.ts: constants, factories and name maps |
Checking a generated client
--check checks the two links between a generated client and the database:
- Files against the configuration. It regenerates the client in memory and compares it with the files in the output directory (
--outputorgenerate.client.output, which--checkrequires; without one it exits 2). No database is needed. Only the generated file names are compared; other files in the directory are ignored. Before comparing, CRLF line endings become LF, the header’smelange version:andsource:lines are dropped (they change with the release and with the directory generation ran from), and trailing whitespace at the end of the file is removed. Any other difference is drift, so a formatter that rewrites the generated files (prettier, for one) makes them differ: exclude them from formatting. - Configuration against the database. With
--db,--envorMELANGE_ENV, it checks every name the configured client uses against the database’s last migration (melange_migrations), the model and exposure it recorded, andpg_procin--db-schema. When the files match, this covers the files too. When they differ, the output says that the database check covers the names the configuration generates.
Pass the same relation flags to --check that the client was generated with; without them it compares with what melange.yaml generates.
# Before merge: is the committed client what melange.yaml generates?
melange generate client --check
# After migrate: does production install everything the client names?
melange generate client --check --env productionRun the database check after migrate: before it, every pending exposure change is reported as an error. Use diff and status before migrating.
The database check reports names the client uses that the database does not answer for as expected. A client narrower than the database (or than sql.relations) is never reported.
| Code | Severity | Meaning |
|---|---|---|
function_not_installed | error | An accessible function the client names is not installed: its family was off, its relation not exposed, the deployed model generates none for it, or it is missing from pg_proc |
function_signature | error | Installed with other arguments than this melange generates |
function_collision | error | The model generates the name for more than one relation; the database keeps one definition, so a call may answer for another relation. Rename one of the relations |
function_owner | error | The name belongs to another relation in the database’s SQL API (a collision, or a name another codegen version computes differently); info when a newer melange migrated the database |
relation_not_exposed | error | melange.yaml exposes the relation and the database was migrated without it, so check_permission raises M2003 |
function_internal | warning | Installed only as an internal function (the relation is not exposed, or sql.functions.accessible was off), so a later migration may drop it or change its signature |
function_orphan | warning | Installed and recorded, but this melange does not generate it for the deployed model, so the next migrate drops it; info when a newer melange migrated the database |
function_unmanaged | warning | A function no migration recorded has the name, such as the application’s own |
relation_undefined | warning | The deployed model does not define the relation, so check_permission denies it |
relation_internal | info | The client has a constant for a relation neither melange.yaml nor the database exposes (constants used for writing tuples) |
family_off | info | melange.yaml turns list_objects, list_subjects, explain or expand on and the database has it off; the client names none of their functions |
Each error and warning has a fix. A fix that runs migrate follows what a plain melange migrate would do, as doctor’s fix hints do. A database built from generate migration files records nothing, so the check compares under the local exposure; a database migrated by an older melange without a recorded model is compared with the local schema under the recorded exposure. Both add a note.
--check exits 1 on any file drift or database error, and on a warning only with --strict; info findings never fail it. Text output lists each drifted file as <output>/<file>: missing or differs (first difference at line N), with the version that generated it when it differs from this melange, then the findings. With --format json:
{
"files": [{"file": "schema_gen.go", "status": "differs", "line": 42, "on_disk_version": "v0.9.0"}],
"database": {
"findings": [
{"code": "function_not_installed", "severity": "error", "type": "document", "relation": "can_view",
"link": "parent", "function": "accessible_document_can_view_by_parent",
"message": "...", "fix": "Run 'melange migrate' to apply the local schema and melange.yaml's sql section"}
],
"errors": 1, "warnings": 0, "functions_checked": 7, "relations_checked": 6
}
}database is null without a database. Doctor runs the same check as its Generated Client category.
generate migration
Generate versioned SQL migration files for use with external migration frameworks (golang-migrate, Atlas, Flyway, etc.). Instead of applying SQL directly like melange migrate, this command produces .sql files you commit, review, and apply through your existing workflow.
For a conceptual overview of when to use this versus melange migrate, see Running Migrations.
melange generate migration \
--schema schemas/schema.fga \
--output db/migrationsFlags:
| Flag | Default | Description |
|---|---|---|
--schema | schemas/schema.fga | Path to current .fga schema file (required) |
--db-schema | (config, else public) | PostgreSQL schema for melange objects |
--output | (stdout) | Output directory for migration files |
--name | melange | Migration name suffix used in filenames |
--format | split | Output format: split (.up.sql/.down.sql) or single |
--up | false | Output only the UP migration (stdout mode only) |
--down | false | Output only the DOWN migration (stdout mode only) |
--db | - | Database URL. Compare against most recent migration record |
--git-ref | - | Git ref. Compare against schema at that commit/branch/tag |
--previous-schema | - | File path. Compare against a previous .fga file |
generate migration also takes the SQL API exposure flags
(--include-relation, --exclude-relation, --no-<family>). The SQL is
generated under the local exposure: the sql: section of the configuration
with those flags on top. A restricted exposure is recorded in the UP header
(-- Exposure: {...}).
--db, --git-ref, --previous-schema) are mutually exclusive. When none is specified, a full migration is generated containing all functions.Output modes:
When --output is specified, timestamped files are written to that directory:
db/migrations/20260322143000_melange.up.sql
db/migrations/20260322143000_melange.down.sqlWhen --output is omitted (stdout mode), you must specify --up or --down to select which migration to print. This is useful for piping into other tools:
melange generate migration --schema schemas/schema.fga --git-ref main --up | psql "$DATABASE_URL"Output formats:
| Format | Files | Use case |
|---|---|---|
split | TIMESTAMP_NAME.up.sql, TIMESTAMP_NAME.down.sql | golang-migrate, Atlas, most frameworks |
single | TIMESTAMP_NAME.sql with UP and DOWN sections | Flyway, frameworks expecting a single file |
Comparison modes:
By default, the UP migration includes every generated function (full mode). To emit only what changed, use one of:
--db- Reads the previous function inventory from themelange_migrationstable. Most precise, but requires database access.--git-ref- Compiles the schema from a git ref and compares. No database needed, suitable for CI.--previous-schema- Compiles a previous schema from a local file and compares.
When a comparison mode is active:
- Only functions with changed SQL bodies (or newly added) are included in UP
- Orphaned functions (removed from schema, or outside a narrower exposure) get
DROP FUNCTION IF EXISTS ...statements withoutCASCADE, so the migration fails if a view, policy or function depends on one - Dispatcher functions are always included regardless of changes
Previous exposure:
Emitting only the changed functions needs the exposure the previous functions were generated with: a function the previous exposure did not install has no previous body to compare, and leaving it out would leave the database without it. Each comparison mode finds the previous exposure differently:
| Mode | Previous exposure |
|---|---|
--db | The exposure recorded with the most recent migration |
--git-ref | The sql: section of the config file at that ref (with the current MELANGE_SQL_* variables applied, but not this run’s flags) |
--previous-schema | Unknown |
For --git-ref, the config file is the one config discovery finds at the ref
from the current directory, so deleting a restricted melange.yaml widens
back to the default like removing its sql: section does. With --config, it
is that file at its path relative to the repository root. When the ref has no
config file and none is in use now, the previous exposure is the defaults with
the current variables. The previous exposure is unknown, and a note is
printed, when the file cannot be read at the ref (not tracked, or invalid) or
when discovery finds a different file at the ref from the one in use now: the
file in use may be untracked, or a file that took priority at the ref may have
been deleted since. MELANGE_SQL_* variables are not versioned: the current
ones apply to both sides, so after changing them compare with --db instead.
When the previous exposure is unknown, UP includes every function (with
-- Previous exposure unknown: every function is included in the header),
whatever the current exposure. Orphans are still dropped: the previous schema
is compiled under the default exposure, which installs every function any
other exposure does except the check_permission_unexposed helper, and the
helper is added to the drops when the current exposure does not install it.
Examples:
# First migration (full - all functions)
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations
# Incremental migration comparing against database
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations \
--db postgres://localhost/mydb
# Incremental migration comparing against git
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations \
--git-ref main
# Preview changes to stdout
melange generate migration \
--schema schemas/schema.fga \
--git-ref HEAD~1 \
--up
# Single-file format for Flyway
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations \
--format single \
--git-ref mainUtility Commands
init
Initialize a new Melange project with an interactive wizard. Detects your project type (Go or TypeScript) and scaffolds a config file, starter schema, and runtime dependency. It also asks whether to add a Melange section for coding agents to AGENTS.md (or CLAUDE.md if that is the only one present, or a new AGENTS.md); for an existing project, use melange init agent.
melange initFlags:
| Flag | Default | Description |
|---|---|---|
-y, --yes | false | Accept all defaults without prompting |
--no-install | false | Skip installing runtime dependencies |
--schema | melange/schema.fga | Schema file path |
--db | postgres://localhost:5432/mydb | Database URL |
--template | org-rbac | Starter model: org-rbac, doc-sharing, minimal, none |
--runtime | (auto-detected) | Client runtime: go, typescript |
--output | internal/authz (Go) / src/authz (TS) | Client output directory |
--package | authz | Client package name (Go only) |
--id-type | string | Client ID type: string, int64, uuid.UUID |
--migration-strategy | (prompted) | How migrations are applied: builtin (melange migrate) or versioned (generated SQL files) |
--migration-output | migrations/ | Output directory for versioned migration files |
--migration-format | split | Versioned migration format: split (.up.sql/.down.sql) or single |
--migration-name | melange | Versioned migration name suffix used in filenames |
--agents | false | Add a Melange section to AGENTS.md / CLAUDE.md without asking. The wizard asks; -y skips it unless this is set |
Project detection:
Melange inspects the current directory for project files:
| File | Detected Runtime | Default Output |
|---|---|---|
go.mod | Go | internal/authz |
package.json | TypeScript | src/authz |
When a project is detected, client code generation is enabled by default and the runtime dependency is installed automatically (go get github.com/pthm/melange/melange for Go, npm install @pthm/melange for TypeScript). If both go.mod and package.json exist, Go takes precedence.
For TypeScript projects, the package manager is auto-detected from lock files: bun.lockb/bun.lock → bun, pnpm-lock.yaml → pnpm, yarn.lock → yarn, otherwise npm.
Starter models:
| Template | Description |
|---|---|
org-rbac | Organization with role hierarchy and repository permissions (default) |
doc-sharing | Google Docs-style owner/editor/viewer model |
minimal | Bare-bones model with just type user |
none | Skip schema file creation |
Directory convention:
By default, init creates a melange/ directory containing both the config and schema:
myproject/
├── melange/
│ ├── config.yaml
│ └── schema.fga
└── ...If the schema path is outside the melange/ directory (e.g., --schema schemas/auth.fga), the config is placed at the project root as melange.yaml instead.
Safety:
- Refuses to overwrite an existing config file in
--yesmode (use interactive mode to confirm) - Skips schema creation if the file already exists in
--yesmode
Examples:
# Interactive wizard
melange init
# Accept all defaults (in a Go project)
melange init -y
# Custom schema and database, skip dependency install
melange init -y --schema melange/auth.fga --db postgres://prod:5432/app --no-install
# Minimal schema with no client generation
melange init -y --template minimalinit agent
Print a Markdown section for coding agents describing the project’s Melange setup and workflow, filled in from the config file: schema and config paths, generated client location, and whether to run melange migrate or melange generate migration. Append it to the instructions file your agent reads:
melange init agent >> AGENTS.mdThe output starts with a blank line so it can be appended to any file. It is the same section the melange init wizard offers to add. See Using Coding Agents for sample output.
config show
Display the effective configuration after merging defaults, config file, environment variables, and any selected environment profile.
melange config showFlags:
| Flag | Default | Description |
|---|---|---|
--source | false | Show the config file path and active environment |
--reveal-secrets | false | Print passwords in cleartext instead of masking them |
Passwords — in both database.url and the discrete password field, across the
base config and every environment profile — are masked by default, including
values resolved from ${VAR} references. Pass --reveal-secrets to print them.
Example — inspect the resolved production profile:
melange config show --env production --sourceOutput:
Config file: /path/to/project/melange.yaml
Environment: production
Database:
Host: ""
Name: ""
Password: ""
Port: 5432
SSLMode: prefer
Schema: ""
URL: postgres://prod-user:****@prod-db:5432/app
User: ""
...
Schema: schemas/schema.fgaThe keys are the Go field names, sorted alphabetically, not the melange.yaml
keys.
This is useful for debugging configuration issues and understanding which values
are in effect for a given environment. The SQL block shows the resolved
sql: section, defaults included; the
exposure flags of other commands are not applied.
env list
List the environment profiles defined in your
config and their connection targets. The active environment is marked with *.
melange env listOutput:
Environments:
* local postgres://localhost:5432/mydb_dev
production ${PROD_DATABASE_URL}
staging staging.db.internal:5432/app
Default: local
Active: local (marked with *)Targets are shown as configured — ${VAR} references are left literal (not
expanded) and any URL password is redacted, so the listing is safe to share.
version
Print version information.
melange versionOutput:
melange v1.0.0 (commit: abc1234, built: 2024-01-15)license
Print license and third-party notices.
melange licenseThis displays the Melange license and attribution for all embedded third-party dependencies.
Exit Codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error (validation, runtime, IO), or generate client --check found drift or an error |
| 2 | Configuration error (invalid config file, missing required settings) |
| 3 | Schema parse error |
| 4 | Database connection error |
| 5 | migrate refused: a newer melange already migrated the database |
The CI gates exit non-zero on an intentional gate failure, not just tool errors:
melange diff --exit-code exits 1 when a change is breaking, and melange migrate --if-deployed-checksum exits 1 when the deployed model has drifted. In both cases
the accompanying message explains the condition.
Common Workflows
Development Setup
With melange init (recommended):
melange initThis creates a config file and starter schema. Then run commands without flags:
# Validate schema
melange validate
# Apply to database
melange migrate
# Generate Go code
melange generate clientWithout configuration file:
# 1. Validate the schema
melange validate --schema schemas/schema.fga
# 2. Apply to local database
melange migrate \
--db postgres://localhost/myapp_dev \
--schema schemas/schema.fga
# 3. Generate Go code
melange generate client \
--runtime go \
--schema schemas/schema.fga \
--output internal/authz \
--package authzCI/CD Pipeline
Use environment variables for credentials:
# Set database URL from CI secrets
export MELANGE_DATABASE_URL="$DATABASE_URL"
# Validate schema (fails fast if syntax error)
melange validate
# Preview migration (optional, for review)
melange migrate --dry-run
# Apply migrations
melange migrate
# Run health checks
melange doctor
# Check the generated client against production
melange generate client --check --env productionBefore merge, melange generate client --check (no database) fails the build when the committed client is not what melange.yaml generates.
Keep --force out of routine pipelines. A plain migrate already re-applies
after a Melange upgrade, and --force turns the dependent-object refusal into a
DROP ... CASCADE: a schema change, a narrower exposure or a codegen change
that removes a function an RLS policy calls would drop the policy and widen
access to its table instead of failing the deploy.
Gated deploy against a live environment. Fail the build on a breaking change, then apply only if the environment hasn’t drifted since you inspected it:
# Fail review if the change narrows access
melange diff --env production --exit-code
# Capture the state you reviewed
CURRENT=$(melange status --env production --format json | jq -r .deployed.schema_checksum)
# … approval gate …
# Apply only if production is still at that checksum
melange migrate --env production --if-deployed-checksum "$CURRENT"Schema Updates
When you modify your .fga schema:
# 1. Validate changes
melange validate
# 2. Regenerate client code
melange generate client
# 3. Apply to database
melange migrateOr as a single workflow with explicit flags:
melange validate --schema schemas/schema.fga && \
melange generate client --runtime go --output internal/authz && \
melange migrate --db "$DATABASE_URL"External Migration Frameworks
If you use golang-migrate, Atlas, Flyway, or a similar tool, replace melange migrate with melange generate migration:
# First time - generate a full migration
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations
# After schema changes - generate an incremental migration
melange generate migration \
--schema schemas/schema.fga \
--output db/migrations \
--git-ref main
# Commit the schema change and migration together
git add schemas/schema.fga db/migrations/
git commit -m "Add editor relation to document type"
# Apply with your framework
migrate -path db/migrations -database "$DATABASE_URL" upSee Running Migrations for guidance on choosing between built-in and external migration strategies.
Troubleshooting
When permission checks aren’t working as expected, use doctor to diagnose issues:
# Run comprehensive health checks
melange doctor
# With verbose output for more details
melange doctor --verbose
# Check effective configuration
melange config show --sourceCommon scenarios where doctor helps:
Permission checks returning unexpected results - Doctor validates that your schema, generated functions, and tuples are all in sync.
After updating Melange - Doctor detects if the codegen version has changed and functions need regenerating.
New environment setup - Doctor validates the complete authorization stack is properly configured.
Data migration issues - Doctor samples tuples and validates they reference valid types and relations.
Slow permission checks - Doctor detects missing expression indexes and inefficient view patterns that cause performance degradation at scale.
Programmatic Alternative
For programmatic schema management without the CLI, use the Go API:
import (
"github.com/pthm/melange/pkg/parser"
"github.com/pthm/melange/pkg/migrator"
)
// Parse schema
types, err := parser.ParseSchema("schemas/schema.fga")
if err != nil {
log.Fatal(err)
}
// Apply, recording the deployed model in melange_migrations
err = migrator.Migrate(ctx, db, "schemas/schema.fga")migrator.Migrate and migrator.MigrateFromString record the schema they
applied, so the database stays self-describing and status, schema pull, and
diff keep working against it. Migrator.MigrateWithTypes (used with
pre-parsed types) deliberately skips that bookkeeping. Reach for it only when
you don’t want a migration record, such as in test fixtures. For the same
reason it cannot change the SQL API exposure.
With options (dry-run, force, skip-if-unchanged, exposure):
import (
"os"
"github.com/pthm/melange/pkg/compiler"
"github.com/pthm/melange/pkg/migrator"
)
// Dry-run: output SQL to stdout
opts := migrator.MigrateOptions{
DryRun: os.Stdout,
}
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", opts)
// Force migration even if unchanged
opts := migrator.MigrateOptions{
Force: true,
}
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", opts)
// Normal migration with skip detection
opts := migrator.MigrateOptions{}
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", opts)
if skipped {
log.Println("Schema unchanged, migration skipped")
}
// Compare-and-swap: apply only if the database is still at this checksum
deployed := "3f9a...c21b"
opts := migrator.MigrateOptions{
IfDeployedChecksum: &deployed,
}
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", opts)
var changed *migrator.DeployedModelChangedError
if errors.As(err, &changed) {
log.Printf("database drifted: expected %s, found %s", changed.Expected, changed.Actual)
}
// Restrict the SQL API. Exposure nil (the default) keeps the exposure the
// database recorded; a pointer to the zero value restores the default.
opts := migrator.MigrateOptions{
Exposure: &migrator.Exposure{
Relations: compiler.RelationPatterns{Include: []string{"can_*"}},
},
}
skipped, err := migrator.MigrateWithOptions(ctx, db, "schemas/schema.fga", opts)
var dependents *migrator.DependentObjectsError
if errors.As(err, &dependents) {
// Views or policies call functions this migration would drop.
for _, d := range dependents.Dependents {
log.Printf("%s depends on %s", d.Object, d.Function)
}
}Unlike the CLI, which always applies the exposure in melange.yaml, a library
call without Exposure keeps the recorded one, so an application that
migrates on startup does not undo a restriction applied with melange migrate.
Changing the exposure needs a migration that records it. Migrator.MigrateWithTypes,
and Migrator.MigrateWithTypesAndOptions without SchemaContent (outside a
dry run), record nothing: asked for an exposure other than the recorded one (or the default when
none is recorded), they return *migrator.UnrecordedExposureChangeError and
apply nothing. With pre-parsed types or an embedded schema, pass the schema
text so the migration is recorded:
e := migrator.Exposure{
Relations: compiler.RelationPatterns{Include: []string{"can_*"}},
}
err := migrator.NewMigrator(db, "").MigrateWithTypesAndOptions(ctx, types, migrator.InternalMigrateOptions{
SchemaContent: schemaContent,
SchemaFormat: migrator.FormatSingle,
Exposure: &e,
})Run health checks with the melange doctor command (see above). The doctor
package is internal to the CLI and is not a supported programmatic API; for
automation, run the command and check its exit code (non-zero on failure).
See Checking Permissions for the full Go API reference.