Skip to content

Errors

All error types, sentinel values, and helper functions in the github.com/pthm/melange/melange package.

Sentinel Errors

ErrorMeaningCommon Cause
ErrNoTuplesTablemelange_tuples view or table not foundView not created, wrong search path
ErrInvalidSchemaSchema parsing failedSyntax error in .fga file
ErrMissingFunctionRequired PostgreSQL function missingMigration not run, or Melange updated without re-migrating
ErrCyclicSchemaCycle detected in relation graphCircular implied-by chain
ErrBulkCheckDeniedAt least one bulk check was deniedReturned by BulkCheckResults.AllOrError()
ErrContextualTuplesUnsupportedQuerier does not support contextual tuplesA Querier other than *sql.DB, *sql.Tx or *sql.Conn (for example a custom wrapper)
ErrInvalidContextualTupleContextual tuple failed validationMalformed or schema-invalid tuple

All sentinel errors work with errors.Is:

allowed, err := checker.Check(ctx, subject, relation, object)
if melange.IsNoTuplesTableErr(err) {
    // melange_tuples view is missing
}

Error Helper Functions

FunctionChecks for
IsNoTuplesTableErr(err error) boolErrNoTuplesTable
IsInvalidSchemaErr(err error) boolErrInvalidSchema
IsMissingFunctionErr(err error) boolErrMissingFunction
IsCyclicSchemaErr(err error) boolErrCyclicSchema
IsBulkCheckDeniedErr(err error) boolErrBulkCheckDenied
IsValidationError(err error) boolValidationError
GetValidationErrorCode(err error) intReturns code from ValidationError, or 0

ValidationError

type ValidationError struct {
    Code    int
    Message string
}

Methods:

  • Error() string implements the error interface
  • ErrorCode() int returns the OpenFGA-compatible error code

Error Codes

CodeConstantMeaning
2000ErrorCodeValidationInvalid request (bad input)
2001ErrorCodeAuthorizationModelNotFoundAuthorization model not found
2002ErrorCodeResolutionTooComplexResolution depth or complexity limit exceeded
allowed, err := checker.Check(ctx, subject, relation, object)
if melange.IsValidationError(err) {
    code := melange.GetValidationErrorCode(err)
    switch code {
    case melange.ErrorCodeValidation:
        // bad input
    case melange.ErrorCodeResolutionTooComplex:
        // depth limit hit
    }
}

BulkCheckDeniedError

type BulkCheckDeniedError struct {
    Subject  Object
    Relation Relation
    Object   Object
    Index    int   // Position in original request order
    Total    int   // Total denied checks in batch
}

Methods:

  • Error() string implements the error interface
  • Unwrap() error returns ErrBulkCheckDenied

Returned by BulkCheckResults.AllOrError() when at least one check is denied:

err := results.AllOrError()
if err != nil {
    var denied *melange.BulkCheckDeniedError
    if errors.As(err, &denied) {
        log.Printf("denied: %s %s %s (and %d others)",
            denied.Subject, denied.Relation, denied.Object, denied.Total-1)
    }
}

PostgreSQL Error Mapping

The runtime maps PostgreSQL error codes to sentinel errors:

SQLSTATEPostgreSQL ErrorMapped To
42P01Undefined tableErrNoTuplesTable
42883Undefined function (check_permission, list_accessible_*, explain_permission or expand_permission)ErrMissingFunction
M2002Custom (raised by generated functions)ValidationError with code 2002
M2003Custom (raised by a public dispatcher for a relation the model defines but the exposure does not expose)ValidationError with code 2000 and the database message

Every Checker method that calls a public function maps these codes: Check, CheckWithContextualTuples, bulk checks, the ListObjects* and ListSubjects* methods, Explain, Expand and ExpandRecursive, whether the driver reports the error when the query is sent or while its rows are read.

M2003 only occurs when the database was migrated with a restricted SQL API exposure (the sql: section of melange.yaml). The ValidationError message is the database’s, which names the relation and the type:

_, err := checker.Check(ctx, user, "viewer", doc)
if melange.GetValidationErrorCode(err) == melange.ErrorCodeValidation {
    // err.Error() == `relation "viewer" on type "document" is not exposed`
}

A relation the model does not define is not an error: checks deny and lists return nothing. See SQL API: M2003.

The M2003 mapping, and expand_permission in the 42883 mapping, are in the runtimes released after v0.10.3. With v0.10.3 and earlier, M2003 comes back as the driver’s error wrapped with the function name (match on its SQLSTATE), and a missing expand_permission is not ErrMissingFunction.

TypeScript client

@pthm/melange maps M2003 and the melange 42883 case on every Checker method that calls a public function, including bulk checks. It does not map M2002 or 42P01:

SQLSTATEThrown
M2003ValidationError with code 2000 (ErrorCodeValidation) and the database message; the driver error is its cause
42883 naming a melange functionMissingFunctionError; the driver error is its cause

Other database errors, including M2002 and 42P01, are thrown unchanged as the driver’s error; match them on its code. The mapping is in releases after v0.10.3; earlier releases throw the driver’s error for both codes.

Migration Errors

pkg/migrator returns typed errors from Migrate, MigrateWithOptions, MigrateFromString, Migrator.MigrateWithTypes and Migrator.MigrateWithTypesAndOptions; match them with errors.As.

ErrorMeaning
*migrator.DeployedModelChangedErrorIfDeployedChecksum did not match the deployed schema checksum; nothing was applied
*migrator.DatabaseAheadErrorThe functions were generated by a newer melange; nothing was applied (melange migrate exits with code 5)
*migrator.DependentObjectsErrorFunctions the migration would drop have dependents (views, materialized views, RLS policies, rules, BEGIN ATOMIC functions)
*migrator.UnrecordedExposureChangeErrorA migration that records nothing (MigrateWithTypes, or MigrateWithTypesAndOptions without SchemaContent and without DryRun) was asked for an exposure other than the recorded one, or the default when none is recorded; nothing was applied

DependentObjectsError.Dependents lists each dependent object and the function it depends on. Migrate checks for dependents before applying anything. When a dependent is created by another session after that check, the drop itself fails with SQLSTATE 2BP01 (dependent_objects_still_exist), since an unforced drop does not CASCADE; the error is still a DependentObjectsError (its Err holds the database error), and the migration is not recorded. Set MigrateOptions.Force (melange migrate --force) to drop the functions with CASCADE, dropping the dependents too. See Dependent objects.

Next Steps