compiler

package
v0.11.0 Latest Latest
Warning

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

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

README

compiler

Package compiler provides public APIs for compiling OpenFGA schemas to SQL.

This is a thin wrapper around internal/sqlgen that exposes only the public types and functions needed by external consumers. For most use cases, prefer pkg/migrator which handles the full migration workflow.

Package Responsibilities

  • Expose SQL generation types for advanced use cases
  • Provide access to relation analysis for tooling
  • Enable custom SQL generation pipelines

Public API

Types
// GeneratedSQL contains all SQL generated from a schema for check functions.
type GeneratedSQL struct {
    Functions            []string // Specialized check functions per relation
    NoWildcardFunctions  []string // Check functions excluding wildcard matches
    Dispatcher           string   // Main check_permission dispatcher
    DispatcherNoWildcard string   // Dispatcher excluding wildcards
    BulkDispatcher       string   // check_permission_bulk
    ExplainFunctions     []string // explain_<type>_<relation> functions
    ExplainDispatcher    string   // explain_permission dispatcher
    ExpandFunctions      []string // expand_<type>_<relation> functions
    ExpandDispatcher     string   // expand_permission dispatcher
}

// ListGeneratedSQL contains all SQL generated for list functions.
type ListGeneratedSQL struct {
    ListObjectsFunctions       []string        // list_<type>_<relation>_obj functions
    ListSubjectsFunctions      []string        // list_<type>_<relation>_sub functions
    AccessibleObjectsFunctions []NamedFunction // accessible_* functions, then the accessible_objects dispatcher
    ListObjectsDispatcher      string          // list_accessible_objects dispatcher
    ListSubjectsDispatcher string   // list_accessible_subjects dispatcher
}

// RelationAnalysis contains the analyzed features of a relation.
type RelationAnalysis struct {
    ObjectType  string
    Relation    string
    CanGenerate bool
    // Feature flags: HasDirect, HasImplied, HasWildcard, etc.
}
Functions
// AnalyzeRelations classifies all relations and gathers data needed for SQL generation.
var AnalyzeRelations func(types []schema.TypeDefinition, closure []schema.ClosureRow) []RelationAnalysis

// ComputeCanGenerate computes which relations can have functions generated.
var ComputeCanGenerate func(analyses []RelationAnalysis) []RelationAnalysis

// GenerateSQL generates specialized check_permission functions from relation analyses.
var GenerateSQL func(analyses []RelationAnalysis, inline InlineSQLData, databaseSchema string) (GeneratedSQL, error)

// GenerateListSQL generates the list and accessible functions.
var GenerateListSQL func(analyses []RelationAnalysis, inline InlineSQLData, databaseSchema string) (ListGeneratedSQL, error)

// GenerateSQLWithOptions, GenerateListSQLWithOptions, CollectFunctionNamesWithOptions and
// CollectNamedFunctionsWithOptions take GenerateSQLOptions{Exposure: ...} to generate
// only the exposed SQL API (Exposure, RelationPatterns, FunctionFamilies).

// AccessibleFunctions returns the installed accessible_<t>_<r> and
// accessible_<t>_<r>_by_<link> functions of the exposed relations.
var AccessibleFunctions func(analyses []RelationAnalysis, exposure Exposure) ([]AccessibleFunction, error)

// ParentKeyFunctions and ParentKeyFunctionsWithOptions describe the parent-key functions.

// GenerateTraceSQL generates the explain and expand functions into another schema (on demand).
var GenerateTraceSQL func(analyses []RelationAnalysis, inline InlineSQLData, databaseSchema string, opts TraceSQLOptions) (TraceSQL, error)

// DispatcherFunctionNames lists the dispatchers, in the order DOWN migrations drop them.
var DispatcherFunctionNames []string

// CollectFunctionNames returns all generated function names for tracking.
var CollectFunctionNames func(analyses []RelationAnalysis) []string

// BuildInlineSQLData builds inline SQL data from closure and analyses.
var BuildInlineSQLData func(closure []schema.ClosureRow, analyses []RelationAnalysis) InlineSQLData

Usage Examples

Generate SQL for Inspection
import (
    "github.com/pthm/melange/pkg/parser"
    "github.com/pthm/melange/pkg/schema"
    "github.com/pthm/melange/pkg/compiler"
)

// Parse schema
types, _ := parser.ParseSchema("schema.fga")

// Compute closure
closure := schema.ComputeRelationClosure(types)

// Analyze relations
analyses := compiler.AnalyzeRelations(types, closure)
analyses = compiler.ComputeCanGenerate(analyses)

// Build inline data
inline := compiler.BuildInlineSQLData(closure, analyses)

// Generate SQL
sql, err := compiler.GenerateSQL(analyses, inline, "")
if err != nil {
    log.Fatal(err)
}

// Inspect generated functions
for i, fn := range sql.Functions {
    fmt.Printf("Function %d:\n%s\n\n", i, fn)
}

// Inspect dispatcher
fmt.Printf("Dispatcher:\n%s\n", sql.Dispatcher)
Analyze Relation Features
types, _ := parser.ParseSchema("schema.fga")
closure := schema.ComputeRelationClosure(types)
analyses := compiler.AnalyzeRelations(types, closure)

for _, a := range analyses {
    fmt.Printf("%s.%s: CanGenerate=%v\n",
        a.ObjectType, a.Relation, a.CanGenerate)
}
Custom SQL Pipeline
// For advanced use: generate SQL without applying to database
types, _ := parser.ParseSchema("schema.fga")
closure := schema.ComputeRelationClosure(types)

analyses := compiler.AnalyzeRelations(types, closure)
analyses = compiler.ComputeCanGenerate(analyses)
inline := compiler.BuildInlineSQLData(closure, analyses)

checkSQL, _ := compiler.GenerateSQL(analyses, inline, "")
listSQL, _ := compiler.GenerateListSQL(analyses, inline, "")

// Write to files for review
os.WriteFile("check_functions.sql", []byte(checkSQL.Dispatcher), 0644)
os.WriteFile("list_functions.sql", []byte(listSQL.ListObjectsDispatcher), 0644)

When to Use This Package

Use pkg/migrator instead for most use cases:

// Simple: one function handles everything
err := migrator.Migrate(ctx, db, "schema.fga")

Use pkg/compiler when you need:

  • SQL inspection - View generated SQL before applying
  • Custom pipelines - Generate SQL for non-PostgreSQL targets
  • Tooling - Build analyzers or documentation generators
  • Dry-run output - Generate migration scripts for review

Relationship to Other Packages

pkg/parser  ->  pkg/schema  ->  pkg/compiler  ->  pkg/migrator
   |               |               |                  |
   v               v               v                  v
 Parse FGA      Transform      Generate SQL      Apply to DB

The compiler package sits between schema analysis and database migration, providing the SQL generation step.

Dependency Information

This package re-exports types from internal/sqlgen. It depends on:

  • github.com/pthm/melange/internal/sqlgen - SQL generation implementation
  • github.com/pthm/melange/pkg/schema - Schema types (via sqlgen)

Documentation

Overview

Package compiler provides public APIs for compiling OpenFGA schemas to SQL.

It is a thin wrapper around internal/sqlgen that exposes only the types and functions needed by external consumers. The package covers four concerns:

  • Check and list SQL generation: AnalyzeRelations, GenerateSQL, GenerateListSQL, CollectFunctionNames, CollectNamedFunctions, and their *WithOptions variants, which take GenerateSQLOptions (including the Exposure that selects the generated SQL API).
  • AccessibleFunctions, the names of the installed accessible functions of the exposed relations, which client generation emits.
  • GenerateTraceSQL, which generates only the explain and expand functions, into another schema, for running them on demand.
  • Migration file generation: GenerateMigrationSQL and MigrationOptions, which assemble versioned UP/DOWN SQL files from already-compiled output.

For applying generated SQL directly to a database, use pkg/migrator instead.

Index

Constants

View Source
const NotExposedErrCode = sqlgen.NotExposedErrCode

NotExposedErrCode is the SQLSTATE public dispatchers raise for a relation the model defines but the exposure does not expose.

View Source
const UnexposedFunctionName = sqlgen.UnexposedFunctionName

UnexposedFunctionName is the raising helper generated when an exposure leaves something out.

Variables

View Source
var AccessibleFunctions = sqlgen.AccessibleFunctions

AccessibleFunctions returns the accessible functions a migration under an exposure installs for the relations it exposes, sorted by type, relation and link. Client generation emits these names.

View Source
var AnalyzeRelations = sqlgen.AnalyzeRelations

AnalyzeRelations classifies all relations and gathers data needed for SQL generation.

View Source
var BuildInlineSQLData = sqlgen.BuildInlineSQLData

BuildInlineSQLData builds inline SQL data from closure and analyses.

View Source
var CollectFunctionNames = sqlgen.CollectFunctionNames

CollectFunctionNames returns all generated function names for tracking.

View Source
var CollectFunctionNamesWithOptions = sqlgen.CollectFunctionNamesWithOptions

CollectFunctionNamesWithOptions is CollectFunctionNames with options.

View Source
var CollectNamedFunctions = sqlgen.CollectNamedFunctions

CollectNamedFunctions returns specialized functions paired with their SQL.

View Source
var CollectNamedFunctionsWithOptions = sqlgen.CollectNamedFunctionsWithOptions

CollectNamedFunctionsWithOptions is CollectNamedFunctions with options.

View Source
var ComputeCanGenerate = sqlgen.ComputeCanGenerate

ComputeCanGenerate computes which relations can have functions generated.

View Source
var DispatcherFunctionNames = sqlgen.DispatcherFunctionNames

DispatcherFunctionNames lists the dispatcher functions generated for every model, in the order DOWN migrations drop them.

View Source
var GenerateListSQL = sqlgen.GenerateListSQL

GenerateListSQL generates specialized list functions from relation analyses.

View Source
var GenerateListSQLWithOptions = sqlgen.GenerateListSQLWithOptions

GenerateListSQLWithOptions is GenerateListSQL with options.

View Source
var GenerateSQL = sqlgen.GenerateSQL

GenerateSQL generates specialized check_permission functions from relation analyses.

View Source
var GenerateSQLWithOptions = sqlgen.GenerateSQLWithOptions

GenerateSQLWithOptions is GenerateSQL with options.

View Source
var GenerateTraceSQL = sqlgen.GenerateTraceSQL

GenerateTraceSQL generates the explain and/or expand functions a migration with an exposure and those families on would install, created in a separate function schema (pg_temp, for explain and expand on demand).

View Source
var ParentKeyFunctions = sqlgen.ParentKeyFunctions

ParentKeyFunctions returns the parent-key functions generated under the default exposure.

View Source
var ParentKeyFunctionsWithOptions = sqlgen.ParentKeyFunctionsWithOptions

ParentKeyFunctionsWithOptions returns the parent-key functions generated under opts.Exposure.

View Source
var ValidateRelationPattern = sqlgen.ValidateRelationPattern

ValidateRelationPattern reports whether a relation pattern is valid.

Functions

This section is empty.

Types

type AccessibleFunction added in v0.11.0

type AccessibleFunction = sqlgen.AccessibleFunction

AccessibleFunction is an accessible function a migration installs for an exposed relation: accessible_<t>_<r>, or with Link set its parent-key form accessible_<t>_<r>_by_<link>, under its installed, unqualified name.

type Exposure added in v0.11.0

type Exposure = sqlgen.Exposure

Exposure selects the generated SQL API: the relations the public dispatchers answer for and the function families generated.

type FunctionFamilies added in v0.11.0

type FunctionFamilies = sqlgen.FunctionFamilies

FunctionFamilies enables an Exposure's optional function families.

type GenerateSQLOptions added in v0.11.0

type GenerateSQLOptions = sqlgen.GenerateSQLOptions

GenerateSQLOptions tunes code generation for the *WithOptions functions. The zero value is the default.

type GeneratedSQL

type GeneratedSQL = sqlgen.GeneratedSQL

GeneratedSQL contains all SQL generated from a schema for check functions.

type InlineSQLData

type InlineSQLData = sqlgen.InlineSQLData

InlineSQLData contains inline SQL data for generated functions.

type ListGeneratedSQL

type ListGeneratedSQL = sqlgen.ListGeneratedSQL

ListGeneratedSQL contains all SQL generated for list functions.

type MigrationOptions added in v0.7.4

type MigrationOptions struct {
	// DatabaseSchema is the PostgreSQL schema for melange objects.
	// When set, DROP FUNCTION statements are schema-qualified.
	DatabaseSchema string
	// Version is the melange CLI/library version (e.g., "v0.7.3").
	Version string
	// SchemaChecksum is the SHA256 of the current schema content.
	SchemaChecksum string
	// CodegenVersion is the codegen version string.
	CodegenVersion string
	// PreviousFunctionNames enables orphan-aware output when non-nil.
	PreviousFunctionNames []string
	// PreviousSource describes where previous state came from (for header comment).
	// e.g., "database", "git:abc1234", "file:old.fga"
	PreviousSource string
	// PreviousChecksums maps function_name → SHA256(sql_body) from the previous state.
	// When set alongside NamedFunctions, only functions whose SQL body has changed (or
	// are new) are included in the UP migration. Dispatchers are always included
	// regardless. If nil, all specialized functions are emitted unconditionally.
	PreviousChecksums map[string]string
	// NamedFunctions pairs each specialized function name with its SQL body for
	// checksum comparison. Required alongside PreviousChecksums for change detection;
	// if either is absent, change detection is skipped and all functions are emitted.
	NamedFunctions []NamedFunction
	// Exposure is the exposure the SQL was generated with (GenerateSQLOptions),
	// recorded in the UP header when it is not the default.
	Exposure Exposure
	// PreviousExposure is the exposure the previous state was generated with,
	// nil when unknown (a previous schema read from git or a file). Change
	// detection needs it once Exposure is restricted: a function the previous
	// exposure did not install has no previous checksum to compare, so with an
	// unknown previous exposure every function is emitted (full output) while
	// orphans are still dropped. With the default Exposure, nil is taken to
	// be the default too, as the previous schema is taken to be the deployed
	// one: a previous state generated under a restricted exposure must say so
	// here, or the functions it left out are not emitted.
	PreviousExposure *Exposure
	// PreviousExposureUnknown says the previous exposure is unknown even with
	// the default Exposure, overriding the assumption above: every function is
	// emitted (full output) while orphans are still dropped. A caller sets it
	// when the previous state may have been generated under a restricted
	// exposure it cannot recover.
	PreviousExposureUnknown bool
}

MigrationOptions controls migration SQL generation.

type MigrationSQL added in v0.7.4

type MigrationSQL struct {
	Up   string
	Down string
}

MigrationSQL holds the UP and DOWN SQL for a single versioned migration. UP contains CREATE OR REPLACE statements for all current functions, plus DROP statements for any orphaned functions detected via comparison mode. DOWN drops all functions installed by UP; restoring a prior state requires re-applying that version's UP migration.

func GenerateMigrationSQL added in v0.7.4

func GenerateMigrationSQL(
	generatedSQL GeneratedSQL,
	listSQL ListGeneratedSQL,
	expectedFunctions []string,
	opts MigrationOptions,
) MigrationSQL

GenerateMigrationSQL is the terminal step of the generate migration pipeline. It assembles UP and DOWN SQL from functions already compiled by GenerateSQL and GenerateListSQL. Call CollectFunctionNames and CollectNamedFunctions first to populate expectedFunctions and opts.NamedFunctions respectively.

When opts.PreviousFunctionNames is nil the output includes every function (full mode). When set, orphaned functions are dropped in UP and checksum-based filtering is applied if opts.PreviousChecksums is also provided.

type NamedFunction added in v0.7.4

type NamedFunction = sqlgen.NamedFunction

NamedFunction pairs a function name with its generated SQL body.

type ParentKeyFunction added in v0.11.0

type ParentKeyFunction = sqlgen.ParentKeyFunction

ParentKeyFunction describes a generated parent-key accessible function.

type RelationAnalysis

type RelationAnalysis = sqlgen.RelationAnalysis

RelationAnalysis contains the analyzed features of a relation.

type RelationPatterns added in v0.11.0

type RelationPatterns = sqlgen.RelationPatterns

RelationPatterns selects an Exposure's exposed relations.

type TraceSQL added in v0.11.0

type TraceSQL = sqlgen.TraceSQL

TraceSQL is a model's explain and expand functions with their dispatchers, generated apart from a migration.

type TraceSQLOptions added in v0.11.0

type TraceSQLOptions = sqlgen.TraceSQLOptions

TraceSQLOptions configures GenerateTraceSQL.

Jump to

Keyboard shortcuts

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