Project Structure
This guide explains Melange’s codebase layout and the purpose of each component.
Module Structure
Melange is organized as multiple Go modules for clean dependency isolation:
melange/
├── go.mod # Root module (github.com/pthm/melange) — also the CLI
├── main.go # CLI entrypoint (package main)
├── melange/
│ └── go.mod # Runtime module (github.com/pthm/melange/melange)
├── clients/
│ └── typescript/ # TypeScript client
├── pkg/ # Public packages (extension surface)
├── internal/ # Sealed implementation (CLI, sqlgen, clientgen, …)
└── test/
└── go.mod # Integration-test module (never released)| Module | Purpose | Dependencies |
|---|---|---|
Root (github.com/pthm/melange) | CLI + schema parsing, code generation | OpenFGA parser, pq driver |
Runtime (github.com/pthm/melange/melange) | Checker, cache, types, errors | stdlib only |
Test (github.com/pthm/melange/test) | Integration tests + OpenFGA oracle | testcontainers, pgx, openfga-server (never released) |
Install the CLI from the root module:
go install github.com/pthm/melange@latestRuntime Module (melange/)
The runtime module has zero external dependencies and provides the permission checking API:
melange/
├── go.mod
├── melange.go # Object, Relation, Querier interfaces
├── checker.go # Checker implementation
├── cache.go # Permission result caching
├── decision.go # Decision overrides for testing
├── errors.go # Sentinel errors and helpers
└── validator.go # Input validationKey Files
melange.go - Core types:
Object- Type + ID resource identifierObjectLike/SubjectLike- Interfaces for domain modelsRelation/RelationLike- Relation typesQuerier- Interface for DB, Tx, Conn
checker.go - Permission checking:
Checker- Main API for permission checksCheck()- Single permission checkListObjects()/ListSubjects()- List operationsMust()- Panic on failure
cache.go - Caching:
CacheinterfaceCacheImpl- In-memory implementation with TTL
decision.go - Testing utilities:
Decisiontype (Allow/Deny/Unset)- Context-based decision propagation
Root Module Packages
Public Packages (pkg/)
pkg/
├── schema/ # Schema types, validation, closure computation
├── parser/ # OpenFGA DSL parsing
├── migrator/ # Database migration APIs
├── compiler/ # SQL code generation APIs
└── clientgen/ # Client code generation APIspkg/schema - Schema handling:
TypeDefinition- Object type with relationsRelationDefinition- Individual relation rulesAuthzModel- Database row representation- Validation and cycle detection
pkg/parser - Schema parsing:
ParseSchema(path)- Parse.fgafileParseSchemaString(dsl)- Parse DSL string- Wraps the official OpenFGA language parser
- Converts OpenFGA AST to
schema.TypeDefinitionslice - Only package that imports the OpenFGA parser dependency
pkg/migrator - Migration:
Migrate(ctx, db, schemaPath)- One-step migrationMigrateFromString(ctx, db, dsl)- Migrate from stringMigrateWithOptions(ctx, db, schemaPath, opts)- Dry run, force, exposure, drift guardPlanWithOptions(ctx, db, schemaPath, opts)/Migrator.Plan- Predict what an unforced migrate would do (skip, record only, apply, refuse) without changing the database
pkg/clientgen - Client code generation:
Generate(runtime, types, cfg)- Generate client codeListRuntimes()- Available generators
Library Packages (internal/)
internal/
├── cli/ # Config resolution and cobra commands
├── clientgen/ # Generator registry, implementations and --check comparison
│ ├── generator.go # Generator interface
│ ├── go/ # Go generator
│ └── typescript/ # TypeScript generator
├── sqlapi/ # Generated SQL API model: functions report, on-demand explain/expand, client name checks
├── sqlgen/ # SQL DSL, query builders, code generation internals
├── studio/ # melange studio web console
└── doctor/ # CLI health check logicSQL Generation
SQL is generated from the internal/sqlgen package:
internal/sqlgen/
├── sqldsl/ # SQL DSL core (sql.go, expr.go, cte.go, ...)
├── plpgsql/ # Function builders (PlpgsqlFunction, SqlFunction)
├── analysis/ # Relation pattern analysis
├── check_queries.go # Permission check queries
├── check_render.go # Check function rendering
├── list_objects_*.go # list_objects and accessible function generation
├── list_subjects_*.go # list_subjects generation
├── exposure.go # SQL API exposure
└── *.go # Additional helpersKey Functions
check_permission() - Core permission check:
- Takes subject, relation, object
- Returns 1 (allowed) or 0 (denied)
- Handles direct tuples, implied relations, parent inheritance, exclusions
list_accessible_objects() - Find accessible objects:
- Returns object IDs the subject can access
- Recursive relations are listed by a breadth-first PL/pgSQL walk that raises M2002 instead of truncating
list_accessible_subjects() - Find subjects with access:
- Returns subject IDs that have access to object
- Recursive relations are listed by a breadth-first PL/pgSQL walk that raises M2002 instead of truncating
CLI
The CLI is part of the root module: a thin main.go at the module root delegates
to the command package under internal/.
main.go # package main → internal/cli/command.Execute()
internal/cli/
├── config.go # config resolution, exit codes (package cli)
├── command/ # cobra commands (validate, migrate, doctor, …)
└── render/ # explain/expand renderingThe old github.com/pthm/melange/cmd/melange module is retired. Its final
published version (cmd/melange/v0.8.7) is an error-shim that prints the new
install path and exits non-zero, so go install …/cmd/melange@latest fails loudly
instead of installing a stale binary. The source is gone from the tree, but the
tag and the module proxy keep serving it; never delete cmd/melange/v* tags.
Commands:
validate- Check a schema without a databasegenerate client- Generate type-safe client codemigrate- Apply schema to databasestatus- Check migration statusdoctor- Health check
Test Module
The integration tests live in a separate github.com/pthm/melange/test module so
their heavy dependencies (testcontainers, pgx, the OpenFGA server oracle) stay out
of the root module’s graph. It is wired via go.work for local/CI development and
is never released. In-package unit tests (*_test.go under pkg/, internal/,
melange/) stay in their own modules.
test/
├── go.mod # github.com/pthm/melange/test (never released)
├── benchmark_test.go # Performance benchmarks
├── integration_test.go # Integration tests
├── openfgatests/ # OpenFGA compatibility suite
│ ├── client.go # Test client
│ ├── runner.go # Test execution
│ └── *_test.go # Test files
├── cmd/dumptest/ # Test case inspector
├── cmd/dumpsql/ # SQL dump tool
├── cmd/explaintest/ # EXPLAIN ANALYZE for test cases
├── cmd/dumpinventory/ # Function inventory dump
├── cmd/benchreport/ # Benchmark report tables
└── testutil/ # Test utilities
└── testdata/ # Test schemasOpenFGA Test Suite
The openfgatests package runs OpenFGA’s official test suite against Melange:
client.go - Test client:
- Uses
pkg/parserfor schema parsing - Creates database schema
- Executes assertions
runner.go - Loads embedded YAML cases and runs them by category or pattern:
- Category-based test runners
- Pattern matching
- Benchmark wrappers
Language Clients
clients/
├── README.md # Overview and contribution guide
└── typescript/ # TypeScript client
├── package.json
├── tsconfig.json
└── src/The Go runtime lives at melange/ for clean imports:
import "github.com/pthm/melange/melange"Other language clients live under clients/ as their package managers don’t have Go’s path constraints.
Documentation
docs/
├── hugo.yaml # Hugo configuration
├── content/
│ ├── _index.md # Landing page
│ └── docs/ # Documentation pages
├── layouts/ # Custom layouts
├── assets/ # CSS/JS assets
└── themes/hextra/ # Hugo theme (submodule)Making Changes
Adding a Feature
- Runtime changes go in
melange/ - Parser changes go in
pkg/parser/ - SQL generation changes go in
internal/sqlgen/ - Tests go in
test/or the appropriate*_test.gofile
SQL Generation Changes
When modifying SQL generation in internal/sqlgen/:
- Update the query builder
- Run
just test-openfgato verify compatibility - Run
just bench-openfgato check performance impact
Studio Views
melange studio renders its pages from templ files in
internal/studio/. The generated *_templ.go files are committed, so ordinary
builds and go install need no extra step. After editing a .templ file:
- Run
just studio-generate(formats and regenerates) and commit the result just studio-generate-check(also part ofjust checkand CI) fails on unformatted templates and on stale or orphaned generated files
just studio-watch --db <dsn> [--schema <file>] regenerates, rebuilds and restarts
studio on every change under internal/studio/, with live reload at
http://127.0.0.1:7331.
Adding a Language Generator
- Create
internal/clientgen/<language>/generate.go - Implement the
Generatorinterface - Register in
init()function - Import in
pkg/clientgen/api.go
Adding Tests
For OpenFGA compatibility tests, the test cases come from the embedded OpenFGA test suite. To test custom scenarios:
func TestCustomScenario(t *testing.T) {
db := testutil.EmptyDB(t)
// Apply schema
err := migrator.MigrateFromString(ctx, db, `
model
schema 1.1
type user
type doc
relations
define owner: [user]
`)
require.NoError(t, err)
// Create tuples view
// Test assertions
}