Models
Models define your data structure with Drizzle ORM tables. You declare the table, then build the model class from it with ModelFactory.defineEntity. The settings of @model (hidden columns, default filter, row scope, limits) have their own guide: Model Settings.
Creating a Basic Model
// src/models/entities/user.model.ts
import { model } from '@venizia/ignis';
import {
PostgresIdEnricher,
PostgresTzEnricher,
ModelFactory,
} from '@venizia/ignis-connectors/postgres';
import type { TEntityObject } from '@venizia/ignis-connectors/postgres';
import { pgTable, text } from 'drizzle-orm/pg-core';
export const userTable = pgTable('User', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
...PostgresTzEnricher.generateColumnDefs(),
name: text('name').notNull(),
email: text('email').notNull(),
});
@model()
export class User extends ModelFactory.defineEntity({ table: userTable }) {}
export type TUser = TEntityObject<typeof User>;Key points:
- The table is a plain, exported drizzle table - drizzle-kit reads it for migrations
TABLE_NAMEis read off the table, so the name'User'is written once- The id is a UUID v7 text key, from
PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }) TEntityObject<typeof User>is the row type
Creating a Model with Relations
// src/models/entities/configuration.model.ts
import { model } from '@venizia/ignis';
import {
PostgresDataTypeEnricher,
PostgresIdEnricher,
PostgresTzEnricher,
PostgresUserAuditEnricher,
ModelFactory,
one,
} from '@venizia/ignis-connectors/postgres';
import { foreignKey, index, pgTable, text, unique } from 'drizzle-orm/pg-core';
import { userTable } from './user.model';
export const configurationTable = pgTable(
'Configuration',
{
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
...PostgresTzEnricher.generateColumnDefs(),
...PostgresDataTypeEnricher.generateColumnDefs(),
...PostgresUserAuditEnricher.generateColumnDefs({
created: { dataType: 'string', columnName: 'created_by' },
modified: { dataType: 'string', columnName: 'modified_by' },
}),
code: text('code').notNull(),
description: text('description'),
group: text('group').notNull(),
},
def => [
unique('UQ_Configuration_code').on(def.code),
index('IDX_Configuration_group').on(def.group),
foreignKey({
columns: [def.createdBy],
foreignColumns: [userTable.id],
name: 'FK_Configuration_createdBy_User_id',
}),
],
);
@model()
export class Configuration extends ModelFactory.defineEntity({
table: configurationTable,
relations: () => ({
creator: one(userTable, {
fields: [configurationTable.createdBy],
references: [userTable.id],
}),
modifier: one(userTable, {
fields: [configurationTable.modifiedBy],
references: [userTable.id],
}),
}),
}) {}Key points:
- Relations are keyed by name -
creatorandmodifierare the names you pass toinclude - Each relation points at a table (
userTable), never at another model class, so two models that relate both ways never import each other - Both relations point at
userTablethrough two different columns, so each names itsfieldsandreferences. Aonewith exactly one foreign key to its target needs neither - see Howonefinds its columns
Understanding Enrichers
Enrichers are helper functions that generate common database columns automatically.
Without enrichers:
static override schema = pgTable('User', {
id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
modifiedAt: timestamp('modified_at', { withTimezone: true }).notNull().defaultNow(),
createdBy: text('created_by'),
modifiedBy: text('modified_by'),
// ... your fields
});With enrichers:
static override schema = pgTable('User', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }), // id (text with UUID default)
...PostgresTzEnricher.generateColumnDefs(), // createdAt, modifiedAt
...PostgresUserAuditEnricher.generateColumnDefs({
created: { dataType: 'string', columnName: 'created_by' },
modified: { dataType: 'string', columnName: 'modified_by' },
}), // createdBy, modifiedBy
// ... your fields
});Available Enrichers
| Enricher | Columns Added | Use Case |
|---|---|---|
PostgresIdEnricher.generateColumnDefs() | id (text or number) | Every table |
PostgresTzEnricher.generateColumnDefs() | createdAt, modifiedAt | Track timestamps |
PostgresUserAuditEnricher.generateColumnDefs() | createdBy, modifiedBy | Track who created/updated |
PostgresDataTypeEnricher.generateColumnDefs() | dataType, tValue, nValue, etc. | Configuration tables |
The functions these classes replace (generateIdColumnDefs, generateTzColumnDefs, ...) are removed; devz codemod namespace-functions moves your calls. SQLite has the same classes under Sqlite* names.
:::note User Audit Options The PostgresUserAuditEnricher enricher defaults both columns to dataType: 'number' (integer user ids) - pass dataType: 'string' for text ids. It also supports an allowAnonymous option (default: true). Set to false to require authenticated user context and throw errors for anonymous operations:
...PostgresUserAuditEnricher.generateColumnDefs({
created: { dataType: 'string', columnName: 'created_by', allowAnonymous: false },
modified: { dataType: 'string', columnName: 'modified_by', allowAnonymous: false },
}):::
TIP
For a complete list of enrichers and options, see the Schema Enrichers Reference.
Hidden Properties
Protect sensitive data by configuring properties that are never returned through repository queries. Hidden properties are excluded at the SQL level for maximum security and performance.
import { model } from '@venizia/ignis';
import { PostgresIdEnricher, ModelFactory } from '@venizia/ignis-connectors/postgres';
import { pgTable, text } from 'drizzle-orm/pg-core';
export const userTable = pgTable('User', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
email: text('email').notNull(),
password: text('password'), // Hidden from queries
secret: text('secret'), // Hidden from queries
});
@model({
settings: {
properties: { hidden: ['password', 'secret'] }, // Never returned via repository
},
})
export class User extends ModelFactory.defineEntity({ table: userTable }) {}Behavior:
| Operation | Behavior |
|---|---|
find(), findOne(), findById() | Hidden excluded from SELECT |
create(), updateById(), deleteById() | Hidden excluded from RETURNING |
| Where clause filtering | Hidden fields can be used in filters by server code on the repository. A generated controller refuses a request filter that names one (400) |
| Direct connector query | Hidden fields included (bypasses repository) |
When you need to access hidden data, use the connector directly:
// Repository query - excludes hidden
const user = await userRepo.findById({ id: '123' });
// { id: '123', email: 'john@example.com' }
// Connector query - includes all fields
const connector = userRepo.connector;
const [fullUser] = await connector
.select()
.from(userTable)
.where(eq(userTable.id, '123'));
// { id: '123', email: 'john@example.com', password: '...', secret: '...' }TIP
For complete hidden properties documentation, see the Models Reference.
Default Filter
Apply automatic filters to all repository queries. This is commonly used for soft-delete patterns:
@model({
settings: {
query: { filter: { where: { isDeleted: false } } },
properties: { hidden: ['deletedAt'] },
},
})
export class Article extends ModelFactory.defineEntity({ table: articleTable }) {}The default filter (set with settings.query.filter) is applied automatically to all read operations. Bypass it with shouldSkipDefaultFilter: true in the options:
// Normal query - auto-filters out soft-deleted records
const articles = await articleRepo.find({ filter: {} });
// Include deleted records
const allArticles = await articleRepo.find({
filter: {},
options: { shouldSkipDefaultFilter: true },
});Unique Keys
A repository's upsert finds the existing row by a unique key. Declare the key once, as a handle on the table's unique index, and keep it on the entity as static keys:
// src/models/entities/self-order-cache.model.ts
import { model, ScopeWriteGuards } from '@venizia/ignis';
import { ModelFactory } from '@venizia/ignis-connectors/postgres';
import { UniqueKeys } from '@venizia/ignis-connectors/relational';
import { sql } from 'drizzle-orm';
import { jsonb, pgTable, text, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
import { currentMerchantId } from '@/utilities/merchant';
export const selfOrderCacheTable = pgTable(
'SelfOrderCache',
{
id: uuid('id').primaryKey().defaultRandom(),
merchantId: text('merchant_id').notNull(),
cacheKey: text('cache_key').notNull(),
value: jsonb('value').notNull(),
expiresAt: timestamp('expires_at'),
deletedAt: timestamp('deleted_at'),
},
(t) => [
uniqueIndex('self_order_cache_merchant_key')
.on(t.merchantId, t.cacheKey)
.where(sql`${t.deletedAt} is null`),
],
);
@model({
settings: {
access: {
resolve: () => ({ merchantId: currentMerchantId() }),
write: { mode: ScopeWriteGuards.ASSIGN },
},
},
})
export class SelfOrderCache extends ModelFactory.defineEntity({ table: selfOrderCacheTable }) {
static readonly keys = {
merchantCacheKey: UniqueKeys.of({
table: selfOrderCacheTable,
index: 'self_order_cache_merchant_key',
}),
};
}UniqueKeys.of reads the index from the Drizzle declaration when the module loads. It throws at boot when:
- no index, unique constraint or
.unique()column of the table has that name; - the index is not unique;
- one of its entries is an expression (
lower(email)), not a column; - the table is neither a Postgres nor a SQLite table.
The handle carries the key's columns, typed as the table's properties, and the table itself. A handle of another table is a compile error where this table's key is expected. A partial index keeps its where, and a unique constraint keeps nullsNotDistinct. Write a partial index predicate with literals (sql`${t.status} = 'live'`), not a bound value (sql`${t.status} = ${status}`): SQLite cannot match a partial index from a bound parameter, and refuses the upsert. The primary key needs no handle: upsert uses it when on is omitted.
static keys is a convention, not a setting: the framework does not read it. It keeps every key of the table in one place, next to the model. See Upsert for the call.
Authorization Settings
Declare your model's authorization principal directly in @model settings. The decorator auto-populates AUTHORIZATION_SUBJECT for type-safe references in route configs:
import { AuthorizationActions, model } from '@venizia/ignis';
import { PostgresIdEnricher, ModelFactory } from '@venizia/ignis-connectors/postgres';
import { pgTable, text } from 'drizzle-orm/pg-core';
export const articleTable = pgTable('Article', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
title: text('title').notNull(),
});
@model({
settings: {
authorize: { principal: 'article' },
},
})
export class Article extends ModelFactory.defineEntity({ table: articleTable }) {}
// Use in route configs - no hardcoded strings
authorize: {
action: AuthorizationActions.READ,
resource: Article.AUTHORIZATION_SUBJECT, // 'article'
}TIP
For full authorization integration details, see the Authorization Usage Reference.
Model Metadata Types
The @model decorator accepts the following metadata:
| Field | Type | Description |
|---|---|---|
type | 'entity' | Optional; ModelTypes.ENTITY is the only value and the default |
tableName | string | Optional explicit table name |
migration.use | boolean | Default true. false marks the model for your migration tooling to skip (see Migrations) |
settings.properties.hidden | string[] | Properties excluded from all query results |
settings.properties.stamped | ReadonlyArray<string> | ReadonlySet<string> | Properties the generated create and update bodies leave out. Default: createdBy, modifiedBy, createdAt, modifiedAt, deletedAt |
settings.query.filter | TFilter | Default filter auto-applied to all queries |
settings.query.limit.default | number | Default row limit when a query omits limit (must be a positive integer; falls back to 10) |
settings.authorize.principal | string | Authorization subject name for this model |
Migrations
IGNIS generates no migrations. drizzle-kit reads the schema file you give it (migration-schema.ts in the examples) and writes the SQL; the framework only applies the files at startup. migration: { use: false } on a model is a marker in the public registry for tooling of yours that decides which models to migrate. IGNIS itself does not read it.
// scripts/migrated-tables.ts
import { MetadataRegistry } from '@venizia/ignis';
import '@/models/entities'; // importing the models registers them
const migrated = [...MetadataRegistry.getInstance().getAllModels()]
.filter(([, entry]) => entry.metadata?.migration?.use !== false)
.map(([tableName]) => tableName);
console.log(migrated.join('\n'));Feed that list to whatever builds your drizzle-kit schema file. examples/vert lists its tables by hand in src/migration-schema.ts, and that is the simplest way. The registry entry carries migration: { use }; the old skipMigrate field is gone.
Model Template
import { model } from '@venizia/ignis';
import { PostgresIdEnricher, ModelFactory } from '@venizia/ignis-connectors/postgres';
import type { TEntityObject } from '@venizia/ignis-connectors/postgres';
import { pgTable, text } from 'drizzle-orm/pg-core';
export const myModelTable = pgTable('MyModel', {
...PostgresIdEnricher.generateColumnDefs({ id: { dataType: 'string' } }),
name: text('name').notNull(),
});
@model()
export class MyModel extends ModelFactory.defineEntity({ table: myModelTable }) {}
export type TMyModel = TEntityObject<typeof MyModel>;The class form - BaseEntity with a static schema - still works. See Definition patterns and the defineEntity reference.