Skip to content

defineSchema / table ​

Declare the tables, columns, access rules, triggers and RPCs that AccessNexus compiles to SQL and a typed SDK. Guide: Schema.

defineSchema ​

ts
// Manual mode: every table declares `columns`
function defineSchema<T extends SchemaDef>(tables: T, options?: SchemaOptions): T;

// Database mode: columns come from a Supabase `Database` type
function defineSchema<DB extends SupabaseDatabase>(
  tables: SupabaseSchemaInput<DB>,
  options?: SchemaOptions,
): SchemaDef;

interface SchemaOptions {
  rpcs?: Record<string, RpcDef>;
  channels?: Record<string, ChannelDef>;
  functions?: Record<string, EdgeFunctionDef>;
  enums?: EnumDef[] | Record<string, readonly string[]>;
}
ParameterTypeDefaultDescription
tablesRecord<string, TableDef> or SupabaseSchemaInput<DB>requiredTable name to table definition. Names must be lowercase snake_case.
options.rpcsRecord<string, RpcDef>undefinedPostgres functions built with rpc(). Stored as a non-enumerable __rpcs property, so Object.keys(schema) lists only tables.
options.channelsRecord<string, ChannelDef>undefinedPrivate Realtime channels (Broadcast / Presence) built with channel(); names are lowercase snake_case. Stored as a non-enumerable __channels property. {} removes every channel policy on the next push.
options.functionsRecord<string, EdgeFunctionDef>undefinedSupabase Edge Functions built with edgeFunction(), keyed by function name ('invite-member'). Stored as a non-enumerable __functions property.
options.enumsEnumDef[] or Record<string, readonly string[]>undefinedShared Postgres enums from defineEnum() (or a { name: values } map). Each one is one CREATE TYPE <name>, used by columns, RPC args and returns.table as 'enum:<name>'. An undeclared name is UNKNOWN_ENUM. Stored as a non-enumerable __enums property.

The schema file must export default the result. The CLI loads it with esbuild, so it may import sibling files.

Mode detection ​

The mode is detected at runtime, not from the generic argument:

ModeDetected whenGenerates
Manualat least one table declares columnsDDL migrations, RLS, triggers, RPCs, SDK (types.ts + client.ts)
Databaseno table declares columnsRLS, triggers, RPCs, SDK (client.ts typed from your Database). No DDL migrations.

Mixing modes (some tables with columns, some without) is reported by validate as MISSING_COLUMNS.

Checks performed by defineSchema ​

defineSchema throws an Error whose message starts with [AccessNexus] (the CLI reports it as SCHEMA_INVALID) when:

  • a table or column name does not match /^[a-z][a-z0-9_]*$/;
  • primaryKey is not a declared column (manual mode);
  • a references key is not a declared column (manual mode);
  • a reference is not table.column or schema.table.column;
  • a two-part reference (table.column) names a table that is not in the schema. Three-part references (auth.users.id) are never checked.

Everything else (column types, policy columns, reserved words, trigger options) is checked by accessnexus validate; see Errors.

Manual mode ​

ts
import { defineSchema, policy, rpc, table } from 'accessnexus';

export default defineSchema({
  todos: table({
    columns: {
      id: 'uuid',
      user_id: 'uuid',
      title: 'text',
      done: { type: 'boolean', default: 'false' },
    },
    primaryKey: 'id',
    references: { user_id: 'auth.users.id' },
    policies: {
      select: policy.isOwner('user_id'),
      insert: policy.isOwner('user_id'),
      update: policy.isOwner('user_id'),
      delete: policy.isOwner('user_id'),
    },
  }),
}, {
  rpcs: {
    count_open: rpc({
      returns: 'int',
      language: 'sql',
      body: 'SELECT count(*)::int FROM todos WHERE user_id = (SELECT auth.uid()) AND NOT done;',
    }),
  },
});

Database mode ​

Pass your Supabase-generated Database type as the generic argument and omit columns. Table names, primaryKey, references keys and softDelete are autocompleted from the type. List only the tables you configure.

ts
import { defineSchema, policy, rpc } from 'accessnexus';
import type { Database } from './database.types.js';

export default defineSchema<Database>({
  profiles: {
    primaryKey: 'id',
    policies: {
      select: policy.isOwner('id'),
      update: policy.isOwner('id'),
    },
  },
}, {
  rpcs: { get_stats: rpc() },
});

A Database-mode table accepts SupabaseTableDef: primaryKey, references, policies, triggers, enableRLS, indexes, softDelete. There is no columns and no onDelete (no DDL is generated).

WARNING

In Database mode validate cannot check column names (it has no column list). A typo in policy.isOwner('usr_id') is only caught by Postgres at push time.

table ​

ts
function table<TColumns extends Record<string, ColumnInput>>(def: TableDef<TColumns>): TableDef<TColumns>;

Returns the definition with two normalizations:

  • enableRLS becomes true when policies is set.
  • When softDelete is set and no trigger.softDelete is present, a soft-delete trigger on that column is appended to triggers.

TableDef ​

ts
interface TableDef<TColumns extends Record<string, ColumnInput>> {
  columns: TColumns;
  primaryKey?: keyof TColumns & string;
  references?: Partial<Record<keyof TColumns & string, string>>;
  onDelete?: Partial<Record<keyof TColumns & string, ForeignKeyAction>>;
  policies?: TablePolicies;
  triggers?: TableTriggers;
  enableRLS?: boolean;
  indexes?: IndexDef[];
  softDelete?: keyof TColumns & string;
  realtime?: boolean | { replicaIdentity?: 'default' | 'full' };
}
OptionTypeDefaultDescription
columnsRecord<string, ColumnInput>required (manual mode)Column name to type string or ColumnDef.
primaryKeycolumn nameundefinedSingle-column primary key. Without it validate warns NO_PRIMARY_KEY; the SDK, seed upserts and soft delete then assume id.
compositePrimaryKeycolumn namesundefinedInstead of primaryKey: ['org_id', 'user_id'] → PRIMARY KEY (org_id, user_id). Seed upserts use all of them; not allowed with softDelete (INVALID_PRIMARY_KEY).
references{ [column]: 'table.column' | 'schema.table.column' }undefinedForeign keys. Equivalent to references on a ColumnDef; when both are set, the column-level one wins.
onDelete{ [column]: ForeignKeyAction }no actionON DELETE action per referencing column. See Foreign keys.
policiesTablePoliciesundefinedOne rule per operation: { select?, insert?, update?, delete? }, plus all? applied to every operation without its own key (details), each built with policy or definePermissions.
triggersTriggerRule[][]Built with trigger.
enableRLSbooleantrueOnly false has an effect: RLS is not enabled for the table.
indexesIndexDef[][]Explicit indexes. See IndexDef.
softDeletecolumn nameundefinedDELETE becomes UPDATE ... SET <column> = NOW(); the SDK filters <column> IS NULL. The column should be 'timestamptz?'.
realtimeboolean | { replicaIdentity }undefined (unmanaged)Supabase Realtime (Postgres Changes): true adds the table to the supabase_realtime publication and gives the SDK a typed subscribe; false removes it. See Realtime.

Unknown keys (for example polices) are reported by validate as UNKNOWN_TABLE_KEY.

RLS defaults ​

Every table gets ALTER TABLE ... ENABLE ROW LEVEL SECURITY and FORCE ROW LEVEL SECURITY.

Table definitionResult
policies setRLS on; operations without a rule are denied.
no policiesRLS on, no policies: deny-all for anon and authenticated (service role only). validate warns NO_POLICIES.
enableRLS: false, no policiesNo RLS file is generated; the table is open to the anon key. validate warns RLS_DISABLED.
enableRLS: false with policiesvalidate error RLS_DISABLED_WITH_POLICIES.

WARNING

enableRLS: false makes the table readable and writable by anyone holding your public anon key. Use it only for a table that is meant to be open.

Column types ​

A column is a type string, or a ColumnDef object. Append ? to any type to make it nullable; otherwise the column is NOT NULL (primary keys get PRIMARY KEY instead).

TypePostgresGenerated TS type
'uuid'UUIDstring
'text'TEXTstring
'varchar'VARCHARstring
'int'INTEGERnumber
'smallint'SMALLINTnumber
'bigint'BIGINTnumber
'serial'SERIALnumber
'float'DOUBLE PRECISIONnumber
'decimal'NUMERICnumber
'numeric', 'numeric(10)', 'numeric(10,2)'NUMERIC, NUMERIC(10), NUMERIC(10,2)number
'boolean'BOOLEANboolean
'json'JSONJson
'jsonb'JSONBJson
'date'DATEstring
'timestamp'TIMESTAMPstring
'timestamptz'TIMESTAMPTZstring
'time'TIMEstring
'text[]'TEXT[]string[]
'int[]'INTEGER[]number[]
'uuid[]'UUID[]string[]
"enum('a','b')"<table>_<column>_enum'a' | 'b'
'enum:<name>'<name> (shared enum)union of the values
any of the above + ?same, nullable... | null

Exported types: ScalarType (the types above), NullableType (`${ScalarType}?`), ColumnType (ScalarType | NullableType), ColumnInput (ColumnType | ColumnDef).

Unknown types are reported as UNKNOWN_COLUMN_TYPE, with a suggestion for common aliases (string to text, integer to int, bool to boolean, datetime to timestamptz, object to jsonb, ...).

Enums ​

Write the values inside enum(...), quoted: "enum('draft','published')". Each enum column gets its own Postgres type named <table>_<column>_enum, created with an idempotent DO $$ ... $$ block. Two enum columns with the same values are still two distinct types: cast through text (v.role::text::org_members_role_enum) when comparing them in SQL.

To share one type between columns and RPCs, declare it once with defineEnum and register it in defineSchema(tables, { enums }). The column type is then 'enum:<name>' ('enum:<name>?' when nullable): the Postgres type is <name>, there is nothing to cast, and the SDK types it as a union and as Database['public']['Enums'][<name>].

ts
import { defineEnum, defineSchema, table } from 'accessnexus';

const memberRole = defineEnum('member_role', ['owner', 'admin', 'member', 'viewer']);

export default defineSchema({
  org_members: table({
    columns: { id: 'uuid', user_id: 'uuid', role: { type: memberRole.type, default: "'member'" } },
    primaryKey: 'id',
  }),
}, { enums: [memberRole] });

Primary key defaults ​

Primary key typeNo default setEffect
'uuid'DEFAULT gen_random_uuid()DEFAULT public.accessnexus_uuidv7() when adapterOptions.uuidGeneration is 'v7'
'bigint'GENERATED ALWAYS AS IDENTITY
othernone

In the SDK's <Table>Create type, a uuid or bigint primary key is optional.

ColumnDef ​

ts
interface ColumnDef {
  type: ColumnType;
  default?: string;
  unique?: boolean;
  check?: string;
  references?: string;
  onDelete?: ForeignKeyAction;
}
FieldTypeDefaultDescription
typeColumnTyperequiredAny type from the table above.
defaultstringundefinedRaw SQL emitted after DEFAULT. See below.
uniquebooleanfalseAdds UNIQUE.
checkstringundefinedRaw SQL emitted as CHECK (<expr>), e.g. 'amount >= 0'.
referencesstringundefinedForeign key target: 'table.column' or 'schema.table.column' (e.g. 'auth.users.id').
onDeleteForeignKeyActionno actionON DELETE action. Requires references.

default and check are emitted verbatim. Functions and numbers need no quotes ('now()', 'gen_random_uuid()', '0', 'false'); a string or enum literal needs its own single quotes inside the JS string: default: "'todo'". A bare word such as default: 'todo' would be read by Postgres as a column name; validate reports it as INVALID_DEFAULT, and also rejects a quoted enum default that is not one of the enum's values.

ts
import { defineSchema, policy, table } from 'accessnexus';

export default defineSchema({
  invoices: table({
    columns: {
      id: 'uuid',
      owner_id: { type: 'uuid', references: 'auth.users.id', onDelete: 'cascade' },
      number: { type: 'text', unique: true },
      amount: { type: 'decimal', check: 'amount >= 0' },
      status: { type: "enum('draft','sent','paid')", default: "'draft'" },
      created_at: { type: 'timestamptz', default: 'now()' },
      notes: 'text?',
    },
    primaryKey: 'id',
    policies: {
      select: policy.isOwner('owner_id'),
      insert: policy.isOwner('owner_id'),
      update: policy.isOwner('owner_id'),
      delete: policy.none(),
    },
  }),
});

Foreign keys ​

A reference is 'table.column' (a table in this schema) or 'schema.table.column' (a table outside it, such as 'auth.users.id'). It can be declared on the column (ColumnDef.references) or in the table's references map.

ts
type ForeignKeyAction = 'cascade' | 'set null' | 'restrict' | 'no action';
onDeleteGeneratedEffect when the parent row is deleted
omittedREFERENCES t(c)Same as 'no action': the delete fails while children exist.
'no action'ON DELETE NO ACTIONThe delete fails while children exist (checked at end of statement).
'restrict'ON DELETE RESTRICTThe delete fails while children exist (checked immediately).
'cascade'ON DELETE CASCADEChildren are deleted.
'set null'ON DELETE SET NULLThe column is set to NULL. The column must be nullable.

validate reports INVALID_ON_DELETE for an unknown action, an onDelete on a column without a foreign key, or 'set null' on a NOT NULL column, and CASCADE_INTO_SOFT_DELETE for 'cascade' on a table that uses soft delete.

WARNING

Cascades run as the table owner: RLS does not stop them. Only cascade where deleting the parent should delete every child, whoever owns it.

Tables are emitted in dependency order (referenced tables first). Every foreign key column gets an index (see below).

IndexDef ​

ts
interface IndexDef {
  columns: string[];
  unique?: boolean;
  name?: string;
}
FieldTypeDefaultDescription
columnsstring[]requiredIndexed columns, in order.
uniquebooleanfalseCREATE UNIQUE INDEX.
namestringidx_<table>_<col1>_<col2>[_uniq]Named from the content, not the position: _uniq is added to a unique index, and _2, _3... to a clash. Reordering indexes generates no DDL.

IndexDef is not exported from accessnexus; write the objects inline.

AccessNexus also creates these indexes automatically (CREATE INDEX IF NOT EXISTS):

IndexColumnsSkipped when
idx_<table>_<col>_fkeach foreign key columnthe column is the primary key, is unique, or a declared index starts with that column (so the declared index already serves the foreign key)
idx_<table>_<col>_rlseach column used by policy.isOwner, policy.belongsTo or a column side of policy.matchesFieldthe column is the primary key or already indexed above
idx_<table>_active_pk(<primaryKey>) WHERE <softDelete> IS NULLthe table has no softDelete or no primaryKey

Schemas generated before 0.4.1 named indexes by position (..._<n>). The first generate after upgrading adds one migration that renames them (ALTER INDEX ... RENAME, never drop and create) and drops foreign-key indexes that a declared index now covers.

Identifiers ​

Identifiers are emitted unquoted, so table, column, RPC and trigger names must be lowercase snake_case (INVALID_IDENTIFIER) and must not be Postgres reserved words such as order, user, group, limit, select (RESERVED_IDENTIFIER).

TypeDescription
SchemaDefRecord<string, TableDef>
TableDef<TColumns>Manual-mode table, above.
SupabaseTableDef<TRow>Database-mode table (no columns, no onDelete).
SupabaseSchemaInput<DB>{ [table in TableNamesOf<DB>]?: SupabaseTableDef<RowOf<DB, table>> }
SupabaseDatabaseConstraint matching any Supabase-generated Database type.
TablesOf<DB>, TableNamesOf<DB>, RowOf<DB, T>, InsertOf<DB, T>, UpdateOf<DB, T>, FunctionsOf<DB>, FunctionNamesOf<DB>, PublicSchema<DB>Helpers over the public schema of a Database type.
GenericTable, GenericSchemaStructural shapes of a Supabase table and schema.
TablePolicies{ select?: PolicyRule; insert?: PolicyRule; update?: PolicyRule; delete?: PolicyRule }
TableTriggersTriggerRule[]

Released under the MIT License.