Skip to content

atlas ​

@c9up/atlas: the ORM: entities and models, repositories, a query builder compiled to SQL by a Rust engine, migrations, a schema builder, seeders, factories and test helpers, on PostgreSQL, MySQL and SQLite. Guide: ORM.

Installation ​

bash
pnpm add @c9up/atlas

ream configure @c9up/atlas registers the provider and the @c9up/atlas/commands commands, writes config/database.ts and adds DB_HOST, DB_PORT, DB_DATABASE, DB_USER and DB_PASSWORD to .env. Factories that use faker need @faker-js/faker; the db() test plugin needs @c9up/helix (both optional peers).

Atlas runs on two Rust binaries: the query compiler and the database driver. Both come in one small package per platform, @c9up/atlas-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/atlas lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the binaries would be left out.

There is no JavaScript fallback. Without the binaries, the first query throws E_ATLAS_NAPI_NOT_FOUND and the first connection throws E_ATLAS_DB_DRIVER_NOT_FOUND. Both messages name the package to install, for example @c9up/atlas-linux-x64-gnu.

Entry points ​

ImportContents
@c9up/atlasEverything below except the services: models, repositories, queries, decorators, schema and migrations, seeders, factories, test helpers, commands, events, errors
@c9up/atlas/providerAtlasProvider (default export)
@c9up/atlas/services/dbdb (default export), the connection registry and createDbService
@c9up/atlas/ormBaseEntity, BaseModel, BaseRepository, the entity decorators and the hooks
@c9up/atlas/schemaMigration (also as BaseSchema), Schema, TableBuilder, ColumnBuilder, ForeignKeyBuilder, AlterViewBuilder, SchemaDumper, RawSql
@c9up/atlas/factoriesfactory, Factory, FactoryBuilder, makeFactoryCommand
@c9up/atlas/seedersBaseSeeder, Seeder, runSeeders, runSeederDirectory, dbSeedCommand, makeSeederCommand
@c9up/atlas/testinguseTransaction, truncateAll, testUtils, createDbAssertions, db (helix plugin), Database, factory
@c9up/atlas/types/relationsThe relation property types HasOne, BelongsTo, HasMany, ManyToMany, HasOneThrough, HasManyThrough
@c9up/atlas/commandsThe command loader: getMetaData, getCommand, primaryConnectionName
@c9up/atlas/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/atlas ​

Models and repositories

ExportKindDescription
BaseModelclassActive-record base: static finders and writers on the model's connection, instance save() / delete().
BaseEntityclassBase of an entity: dirty tracking, fill and merge, relations, serialization, domain events.
BaseRepositoryclassData-mapper access to one entity class on a given connection.
ModelQueryclassThe query a model or repository builds; resolves to entity instances.
PaginatorclassA page of results: items, meta (total, perPage, currentPage, lastPage, firstPage), URL helpers.
setAtlasStrictModefunctionsetAtlasStrictMode(enabled: boolean): void: raw SQL entry points (whereRaw, joinRaw…) throw in application code.
isAtlasStrictModefunctionisAtlasStrictMode(): boolean.
DomainEventtypeAn event an entity records, flushed after it is saved.
CreateOptionsinterface{ quiet?: boolean; allowExtraProperties?: boolean }.
RepositoryOptionsinterface{ dialect?: AtlasDialect; scope?: QueryScope }.
DatabaseConnectioninterfaceWhat a repository runs on: dialect?, execute, query, transaction?.
QueryScopetype(query: ModelQuery<BaseEntity>, table: string) => void.
ScopedPivotinterfacePivot constraints of a scoped many-to-many query.

Decorators and hooks

ExportKindDescription
EntityfunctionEntity(tableName: string): ClassDecorator.
Column / columnfunctioncolumn(options?: ColumnOptions), with column.date(options?), column.dateTime(options?) and column.json(options?). Date columns hydrate to a chronos DateTime.
PrimaryKeyfunctionPrimaryKey(options?): PropertyDecorator.
computedfunctioncomputed(): MethodDecorator: a getter included in serialization.
BelongsTo / HasOne / HasMany / HasOneThrough / HasManyThrough / ManyToManyfunctionRelation decorators; the lower-case forms (belongsTo…) are the same functions.
SoftDeletesfunctionSoftDeletes(): ClassDecorator: delete() sets deleted_at; queries leave deleted rows out, the filter ANDed with the query's clauses as one group.
hasSoftDeletesfunctionhasSoftDeletes(target): boolean.
scopefunctionDeclare a reusable query scope on a model.
beforeSave, afterSave, beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete, beforeFind, afterFind, beforeFetch, afterFetch, beforePaginate, afterPaginatefunctionLifecycle hook decorators: (): MethodDecorator.
addHook / removeHookfunctionRegister or drop a hook without a decorator.
getEntityMetadata, getColumnMetadata, getRelationMetadata, getPrimaryKey, getDateColumnConfigfunctionRead what the decorators recorded.
ColumnOptionsinterface{ type?; nullable?; default?; columnName?; serializeAs?; serialize?; … }.
DateTimeColumnOptions / DateColumnConfiginterface{ autoCreate?: boolean; autoUpdate?: boolean } and the recorded config.
JsonColumnOptionsinterfaceColumnOptions & { type?: 'json' | 'jsonb' }; jsonb by default.
ColumnAdapterinterface{ consume(raw): T; prepare(value): unknown }: converts a column between the database and the entity.
ManyToManyOptionsinterfacePivot table, keys and pivot columns of a many-to-many relation.
ColumnMetadata / EntityMetadata / RelationMetadatainterfaceRecorded metadata.
HookEvent / HookHandler / HookKindtypeHook names and handler signature.
ScopeFntypeA scope's function.

Queries and connections

ExportKindDescription
QueryBuilderclassA table query builder compiled by the Rust engine: select, where, whereIn, whereNull, whereExists, orderBy, groupBy, having, limit, offset, union, with, paginate, toSQL.
RawSqlclassA raw SQL fragment with its bindings, built by db.raw().
transactionfunctiontransaction<T>(db: DatabaseConnection, callback: (trx: TransactionClient) => Promise<T> | T, options?: TransactionOptions): Promise<T>.
createNapiConnectionfunctioncreateNapiConnection(url: string, poolMin = 1, poolMax = 10, pragmas?, retry?: ConnectRetryOptions, observability?: ObservabilityOptions): Promise<AsyncDatabaseConnection>.
getAtlasDialect / setAtlasDialectfunctionThe process-wide default dialect.
registerColumnCast / registerTableCastsfunctionregisterColumnCast(table, column, type): cast a bound value to a column type (PostgreSQL).
SQLITE_PROD_PRAGMASconst{ journal_mode: 'WAL', synchronous: 'NORMAL' }.
CamelCaseNamingStrategy / defaultNamingStrategy / getNamingStrategyclass / const / functionHow property names map to column names, and relations to keys.
AsyncDatabaseConnectioninterface{ dialect; query; execute; runInTransaction(batch); transaction?(); listen?; close(); ping() }.
TransactionClientinterfaceA connection bound to one transaction, with query builders and nested savepoints.
TransactionOptionsinterface{ isolationLevel?: IsolationLevel; … }.
IsolationLeveltype'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable'.
ConnectRetryOptions / ObservabilityOptions / QueryMetainterfaceConnect retries, query events, the model a query belongs to.
ListenFn / ListenOptions / Notification / NotificationHandler / UnlistentypePostgreSQL LISTEN / NOTIFY through db.listen().
AtlasDialecttype'sqlite' | 'postgres' | 'mysql'.
WhereOperator / WhereClause / ExistsClause / OrderByClause / CteDefinition / QueryResulttypeQuery builder shapes.
NamingStrategy / RelationKindtype

Schema, migrations and seeders

ExportKindDescription
Migration / BaseSchemaclassAbstract base of a migration.
MigrationRunnerclassRuns a directory of migrations on a DatabaseAdapter.
SchemaclassDDL builder: tables, views, indexes, schemas.
TableBuilder / ColumnBuilderclassColumns, keys, indexes and checks of one table.
SchemaDumperclassWrites the live schema to a .sql file and a manifest.
readSchemaDumpManifest / schemaDumpManifestPathfunctionRead the manifest next to a dump.
renderPgCreateTable / renderPgForeignKeyDdlfunctionPostgreSQL DDL of an introspected table.
introspectTablefunctionintrospectTable(db, dialect, table, schema?): Promise<IntrospectedColumn[] | null>.
checkSchemafunctioncheckSchema(entities, db, dialect): Promise<SchemaFinding[]>: compare models' columns with the live schema.
verifySchemafunctionSame, then throw (mode: 'throw', default) or warn on drift.
runSchemaCheckfunctionSame, printed; resolves to an exit code.
formatSchemaFindings / suggestColumn / typesCompatiblefunctionHelpers of the schema check.
BaseSeeder / SeederclassAbstract base of a seeder: run(), this.db, static environment.
runSeeders / runSeederDirectoryfunctionRun seeder instances, or every seeder file of a directory.
DatabaseAdapterinterfaceWhat MigrationRunner runs on; runInTransaction(batch) makes each migration atomic.
MigrationRecord / MigrationState / MigrationStatustypeMigration tracking.
SchemaFinding / SchemaFindingKindtype'missing-table' | 'missing-in-db' | 'type-mismatch' | 'missing-in-model'.
IntrospectedColumn / PgForeignKey / SchemaDumperOptions / SchemaDumpManifest / SchemaDumpResulttype
ColumnDefinition / ColumnType / DefaultValue / AlterOperation / CheckExpression / CheckOperator / CheckValue / ColumnPosition / ForeignKeyReference / IndexDefinition / ReferentialAction / TableConstraintSpec / TableOptionsSpec / TextVarianttypeSchema builder shapes.

Commands, factories, testing, events, errors

ExportKindDescription
defineConfigfunctiondefineConfig(config: AtlasDatabaseConfig): AtlasDatabaseConfig.
configurefunctionThe ream configure hook.
makeMigrationCommand, migrationRunCommand, migrationRollbackCommand, migrationStatusCommand, migrationResetCommand, migrationRefreshCommand, migrationFreshCommand, migrationUnlockCommand, dbWipeCommand, dbSeedCommand, makeSeederCommand, makeFactoryCommand, schemaDumpCommand, schemaGenerateCommand, schemaCheckCommandfunctionBuild each command class with its options (see @c9up/atlas/commands).
generateSchemaFile / renderSchemaFilefunctionWhat schema:generate writes.
argument / flagfunctionCommand argument and flag metadata.
MigrationCommandOptions / SeederCommandOptions / FactoryCommandOptions / SchemaDumpCommandOptions / SchemaGenerateOptions / AtlasCommandClass / CommandOptions / ArgumentMetaData / FlagMetaDatatype
factory / Factoryfunction / constModel factories (see @c9up/atlas/factories).
FactoryContextinterfaceWhat a factory callback receives.
useTransaction / truncateAllfunctionTest isolation (see @c9up/atlas/testing).
TestTransactioninterface{ trx: TransactionClient; rollback: () => Promise<void> }.
onDbQueryfunctiononDbQuery(listener: DbQueryListener): () => void: every statement of a connection with debug: true.
prettyPrintQueryfunctionprettyPrintQuery(event: DbQueryEvent): string.
onUnsafeStatementfunctiononUnsafeStatement(listener: UnsafeStatementListener): () => void: every statement the Rust compiler refused.
clearDbQueryListeners / clearUnsafeStatementListenersfunction
DbQueryEvent / DbQueryListener / UnsafeStatementEvent / UnsafeStatementListenertype
errorsnamespaceThe package's errors, one class per code, see Errors

@c9up/atlas/provider ​

ExportKindDescription
default (AtlasProvider)providerReads config/database.ts (the database key), opens every connection, seats the default one on services/db, verifies the schema when verifySchema is set, runs pending migrations at boot only when migrations.autoRun is on, and closes the connections on shutdown.
AtlasAppContextinterfaceThe host the provider needs.
ConnectionConfig / AtlasDatabaseConfiginterfaceSee Configuration.

@c9up/atlas/services/db ​

ExportKindDescription
default (db)constThe DbService of the default connection.
createDbServicefunctioncreateDbService(resolve: () => AsyncDatabaseConnection, readOnly?: boolean): DbService.
setDb / getDb / clearDbfunctionSeat, read and drop the default connection.
registerConnection / unregisterConnection / getConnectionfunctionNamed connections: registerConnection(name, connection, config?).
connectionManagerfunctionconnectionManager(): ConnectionManager.
setDatabaseConfig / getDatabaseConfig / clearDatabaseConfig / connectionConfigFor / primaryConnectionNamefunctionThe config the provider booted with; connectionConfigFor(name?) merges a connection over the top level.
DbServiceinterfaceSee below.
DbQueryOptionsinterface{ client?: QueryExecutor; mode?: 'read' | 'write' }.
ConnectionOptionsinterface{ mode?: 'read' | 'write' }.
Member of DbServiceSignatureDescription
from / table / queryfrom(table: string): DatabaseQueryBuilderA table query; from() also takes a subquery and an alias.
insertQueryinsertQuery(options?: DbQueryOptions): DatabaseQueryBuilderAn insert.
rawQueryrawQuery<T>(sql: string, bindings?: unknown[] | Record<string, unknown>): RawQueryBuilder<T>Raw SQL with positional or named bindings.
raw / refraw(sql: string, params?): RawSqlA raw fragment, a column reference.
modelQuerymodelQuery<Q>(model: { query(): Q }): QA model's query on this connection.
connectionconnection(name?: string, options?: ConnectionOptions): DbServiceAnother connection, or a read replica with mode: 'read'.
executeexecute(sql: string, params?: unknown[]): Promise<{ rowsAffected: number }>
transaction / runInTransactionas on the connectionManaged or manual transaction; a batch run atomically.
listenas on the connectionPostgreSQL LISTEN / NOTIFY.
truncate / truncateAllTablestruncate(table: string, cascade?: boolean): Promise<void>
getAdvisoryLock / releaseAdvisoryLockgetAdvisoryLock(key: string | number): Promise<boolean>
manager / dialectgetters
ping / closeping(): Promise<void>

@c9up/atlas/testing ​

ExportKindDescription
useTransactionfunctionuseTransaction(db: AsyncDatabaseConnection): Promise<TestTransaction>: run a test inside a transaction rolled back after it.
truncateAllfunctiontruncateAll(db: AsyncDatabaseConnection, ignoreTables?: readonly string[]): Promise<void>.
testUtilsfunctiontestUtils(conn, options?: DbTestUtilsOptions): { db(): DbTestUtils }: migrate(), truncate(), seed(files?), withGlobalTransaction().
createDbAssertionsfunctioncreateDbAssertions(conn: DbConnectionLike): DbAssertions: assertHas, assertMissing, assertCount, assertEmpty.
dbfunctiondb(conn: DbConnectionLike): Plugin: helix plugin setting ctx.db to the assertions.
DatabaseclassA small async database for tests: query, queryWithParams, execute, close, asAdapter().
factory / Factory / FactoryBuilderfunction / const / interfaceAs in @c9up/atlas/factories.
DbTestUtils / DbTestUtilsOptionsinterface{ migrationsDir?; seedersDir?; ignoreTables? }.
DbAssertions / DbConnectionLikeinterface

@c9up/atlas/factories ​

ExportKindDescription
factoryfunctionfactory<T extends BaseEntity>(entityClass, defaults): FactoryBuilder<T>.
FactoryconstFactory.define(entityClass, defaults).build(), and Factory.stubId(generator?).
FactoryBuilderinterfacemerge, mergeRecursive, state, apply, client, connection, relation, with, tap, newUp, pivotAttributes, query, before, after, make, makeMany, makeStubbed, makeStubbedMany, create(db?), createMany(count, db?).
makeFactoryCommandfunctionThe make:factory command.

@c9up/atlas/commands ​

CommandDescription
migration:runRun pending migrations (--schema-path bootstraps from a dump).
migration:rollbackRoll back the latest batch, or --batch=N; --force in production.
migration:statusApplied and pending migrations.
migration:resetRoll back every migration.
migration:refreshRoll back every migration, then run them again.
migration:freshDrop every table, then run every migration.
migration:unlockClear a stuck migration lock.
db:wipeDrop every table, the migrations table included.
db:seedRun seeders (--files=A,B, --connection=name).
make:migrationScaffold a timestamped migration.
make:seederScaffold a seeder.
make:factoryScaffold a factory.
schema:dumpDump the schema to a .sql file and a manifest (--prune, --connection, --path).
schema:generateIntrospect the database and generate model classes.
atlas:checkCompare the models with the live schema.

Commands that destroy data refuse to run in production without --force while migrations.disableRollbacksInProduction is on. With the option off, db:wipe, migration:fresh, migration:rollback, migration:reset and migration:refresh ask for confirmation in production, as migration:run does; a missing or failed prompt counts as no.

BaseModel ​

GroupMembers
Findfind, findOrFail, findBy, findByOrFail, findMany, findManyBy, first, firstOrFail, all, query(options?)
Writecreate, createMany, createQuietly, createManyQuietly, firstOrCreate, firstOrNew, updateOrCreate, updateOrCreateMany, fetchOrCreateMany, fetchOrNewUpMany, truncate
Connectionstatic connection, $connection(), $repo(options?), transaction(callback, options?) or transaction(options?)
Instancesave(), saveQuietly(), delete(), deleteQuietly(), useTransaction(trx), useConnection(name), $trx

BaseEntity ​

GroupMembers
State$isNew, $isPersisted, $isLocal, $isDeleted, $isDirty, $dirty, $primaryKeyValue, isDirty(...)
Attributesfill(values), merge(values), setExtra / getExtra, enableForceUpdate()
Relationsload, loadOnce, loadCount, loadAggregate, related(name), associate, dissociate, attach, detach, sync
Reloadrefresh(), fresh()
Outputserialize(options?), toJSON(), toObject()
Domain eventsaddDomainEvent, getDomainEvents, hasDomainEvents, domainEventCount, clearDomainEvents, flushDomainEvents

BaseRepository ​

new BaseRepository(entityClass, db: DatabaseConnection, options?: RepositoryOptions).

GroupMembers
Queryquery(), find(id), findOrFail(id), findBy(column, value), findByOrFail, findMany, findManyBy, all(), allWithTrashed(), onlyTrashed(), where(column, value)
Writecreate(data, options?), createMany(rows), createQuietly, createManyQuietly, save(entity), saveQuietly, saveMany(entities), upsert(data, uniqueBy), firstOrCreate(where, create?), firstOrNew(where, create?), updateOrCreate(where, data, options?), updateOrCreateMany(key, rows, options?), fetchOrCreateMany, fetchOrNewUpMany, updateById(id, data), updateWhere(column, value, data)
Deletedelete(entity), deleteQuietly, forceDelete(entity), restore(entity), truncate()
Countersincrement(id, column, amount?) or increment(id, { colA: 1 }); decrement likewise
RelationsloadRelation(entity, name, callback?), relatedProxy(entity, name), loadCount(entity, name, alias?), loadAggregate(entity, name, builder), refresh(entity), fresh(entity)
Low leveluseTransaction(trx), raw(sql, ...params), execute, getTableName(), getPrimaryKeyColumn()

ModelQuery ​

A ModelQuery is PromiseLike: await runs it. Every where* and having* method has and* and or* forms.

GroupMembers
Wherewhere, whereNot, whereNull, whereNotNull, whereIn, whereNotIn, whereBetween, whereNotBetween, whereLike, whereILike, whereColumn, whereNotColumn, whereExists, whereNotExists, whereRaw(sql, bindings), whereExpr(column, operator, value), whereJson, whereNotJson, whereJsonPath, whereJsonSubset / whereJsonSuperset and their Of and Not forms
Relationspreload(relation, callback?), preloadOnce, sideload, has, doesntHave, whereHas, whereDoesntHave, withCount(relation, callback?), withAggregate(relation, callback)
PivotwherePivot, whereNotPivot, wherePivotIn, whereInPivot, whereNotInPivot, whereNullPivot, whereNotNullPivot, pivotColumns
Select and aggregatesselect, distinct, distinctOn, count, countDistinct, sum, sumDistinct, avg, avgDistinct, min, max, selectAggregate, as(alias)
Joinsjoin, innerJoin, leftJoin, leftOuterJoin, rightJoin, rightOuterJoin, fullOuterJoin, crossJoin, joinOn(table, left, right), joinRaw(fragment), with on, onVal, onIn, onNull, onBetween, onExists and their negations
GroupinggroupBy, groupByRaw, having*, groupLimit, groupOrderBy
Order and pagesorderBy, orderByRaw, limit, offset, forPage, paginate(page, perPage), cursorPaginate({ perPage, cursor, orderBy })
Sets and CTEsunion, unionAll, intersect, intersectAll, except, exceptAll, with, withRecursive, withMaterialized, withNotMaterialized
Scopes and conditionsapply(callback), withScopes(callback), if, unless, ifDialect, unlessDialect, match
Soft deleteswithTrashed, onlyTrashed, restore, forceDelete
LockingforUpdate, forShare, forNoKeyUpdate, forKeyShare, skipLocked, noWait, timeout
Runexec(), first(), firstOrFail(), sole(), exists(), doesntExist(), pluck(column), all()
Writeupdate(patch, returning?), delete(returning?), increment(column, amount) or increment({ … }), decrement likewise
InspecttoSQL(), toQuery(), toNative(), debug(flag), comment(text), reporterData, clone(), useTransaction(trx)
ClearclearSelect, clearWhere (the relation key, scope and soft-delete filter stay), clearOrder, clearHaving, clearLimit, clearOffset
GroupwrapExisting(): close the clauses chained so far into one group

The eight aggregates share one signature. Each takes a column, with an alias inline, as a second argument, or as the key of an object, and returns the builder. The value comes back as a column of the result row, in $extras on the model builder:

ts
const [row] = await db.from('sales').count('* as total')
Number(row.total)

const [order] = await Order.query().sum('amount as spent').countDistinct('sku', 'items')
Number(order.$extras.spent)

None of them runs the query on its own. On db.from(), the argument is a column or *: an expression is refused with E_UNSAFE_IDENTIFIER; give it to select() instead (select('sum(price * quantity) as total')).

The DatabaseQueryBuilder that db.from() returns has the same filtering, join, grouping, set and locking methods, plus insert, multiInsert, returning, onConflict(...).ignore() / .merge(), update, delete / del, increment, decrement, withSchema and paginate.

insert() takes one row or an array of rows; an array works like multiInsert(). A row with no column inserts one row of defaults: INSERT INTO "t" DEFAULT VALUES on Postgres and SQLite, INSERT INTO `t` () VALUES () on MySQL. An empty array has no row, so insert([]) and multiInsert([]) fail with E_ATLAS_EMPTY_INSERT. Several rows that set no column fail the same way: only one row can take every default. On SQLite, an upsert (onConflict()) of a row with no column fails with E_UNSUPPORTED, because SQLite takes no ON CONFLICT after DEFAULT VALUES.

onConflict() with no column means any unique constraint. With ignore(), it compiles ON CONFLICT DO NOTHING on Postgres and SQLite, and INSERT IGNORE on MySQL. With merge(), it compiles ON CONFLICT DO UPDATE on SQLite and ON DUPLICATE KEY UPDATE on MySQL. Postgres needs the conflict columns to update a row, so onConflict().merge() fails there with E_UNSUPPORTED: name the columns, as in onConflict('email').merge().

Migration ​

MemberSignatureDescription
up / downabstract up(): Promise<void> | voidThe change and its reverse.
schemareadonly schema: SchemaThe DDL builder.
deferdefer(callback: (db) => Promise<void> | void): voidRun code against the connection after the schema statements, in the migration's transaction.
rawraw(expression: string): RawSqlA raw SQL expression for a column default, written as is.
nownow(): RawSqlCURRENT_TIMESTAMP on SQLite, NOW() elsewhere, for a column default.
disableTransactionsstatic disableTransactions = falseRun this migration outside a transaction.
dryRundryRun = falseSet while the runner collects SQL without writing.
getUpSQL / getDownSQLgetUpSQL(): Promise<string[]>The compiled statements.

MigrationRunner ​

new MigrationRunner(db: DatabaseAdapter, options?: { migrationsDir?; dialect?; tableName?; … }); database/migrations and table ream_migrations by default.

MemberSignatureDescription
initinit(): Promise<void>Create the tracking table.
statusstatus(): Promise<MigrationStatus[]>
migratemigrate(options?: { schemaPath?: string }): Promise<string[]>Run pending migrations, each atomically when the adapter has runInTransaction.
rollbackrollback(options?: { batch?: number; force?: boolean }): Promise<string[]>The last batch, or batch N.
reset / refreshrefresh(): Promise<{ rolled: string[]; executed: string[] }>Roll back everything; refresh then migrates again.
freshfresh(options?: { force?: boolean; schemaPath?: string }): Promise<{ rolled: string[]; executed: string[] }>Drop every table, then migrate.
wipewipe(options?: { force?: boolean }): Promise<void>Drop every table.
dryRundryRun()The SQL pending migrations would run, without writing.
loadDumploadDump(sqlPath: string): Promise<void>Run the statements of a schema dump.
forceUnlockforceUnlock(): Promise<boolean>Clear a stale lock.

Schema and TableBuilder ​

BuilderMembers
SchemacreateTable, createTableIfNotExists, createTableLike, alterTable / table, renameTable, dropTable, dropTableIfExists, hasTable, hasColumn, createIndex, dropIndex, createView, createViewOrReplace, alterView, renameView, dropView, dropViewIfExists, createMaterializedView, refreshMaterializedView, dropMaterializedView, dropMaterializedViewIfExists, createSchema, createSchemaIfNotExists, dropSchema, dropSchemaIfExists, withSchema, raw, toSQL, reset
TableBuilder columnsincrements, bigIncrements, id, integer, bigInteger, smallint, tinyint, mediumint, float, double, decimal, boolean, string, text, binary, uuid, enum, json, jsonb, date, time, dateTime, timestamp, timestamptz, timestamps, specificType
TableBuilder keys and constraintsprimary, unique, uniqueIndex, index, foreign, check, checkBetween, checkIn, checkNotIn, checkLength, checkPositive, checkNegative, checkRegex
TableBuilder alterationsrenameColumn, dropColumn, dropColumns, dropPrimary, dropUnique, dropIndex, dropForeign, dropChecks, dropTimestamps, setNullable, dropNullable, engine, charset, collate, comment
ColumnBuildernotNullable, nullable, defaultTo, unsigned, primary, unique, index, references, inTable, onDelete, onUpdate, comment, first, after, alter, check*

Configuration ​

config/database.ts, read under the database key.

OptionTypeDefaultDescription
connectionstring'primary'The default connection when connections is set (default is accepted as an older alias).
connectionsRecord<string, ConnectionConfig>—Named connections.
verifySchema{ entities; mode?: 'throw' | 'warn' }unsetCompare these models with the live schema after boot; throw by default.
prettyPrintDebugQueriesbooleanfalsePrint each statement of a debug connection.
<connection>.url / .connectionstring—sqlite:data/app.db, postgres://…, mysql://…. url wins.
<connection>.pool{ min?: number; max?: number }{ min: 1, max: 10 }Pool size (poolMin / poolMax are accepted too).
<connection>.debugbooleanfalseEmit a db:query event per statement.
<connection>.pragmasRecord<string, string | number>—SQLite pragmas, such as SQLITE_PROD_PRAGMAS.
<connection>.connectRetriesnumber0Extra attempts of the first connection.
<connection>.connectBackoffMsnumber200Base of the exponential backoff, capped at 30 s.
<connection>.connectTimeoutMsnumber—Per-attempt acquire timeout.
<connection>.migrations.pathsstring[]['database/migrations']Migration directories.
<connection>.migrations.tableNamestring'ream_migrations'Tracking table; a plain identifier.
<connection>.migrations.disableRollbacksInProductionbooleantrueRefuse rollback, reset, refresh, fresh and wipe in production without --force.
<connection>.migrations.autoRunbooleanfalseRun pending migrations at boot; ignored in development.
<connection>.migrations.naturalSortbooleanfalseSort 2_x before 10_x.
<connection>.migrations.disableTransactionsbooleanfalseRun every migration outside a transaction.
<connection>.seeders.pathsstring[]['database/seeders']Seeder directory (the first is used).
<connection>.seeders.naturalSortbooleanfalse
<connection>.factories.pathstring'database/factories'Where make:factory writes.
<connection>.schemaGenerationSchemaGenerateOptions—outputPath and options of schema:generate.

Container bindings ​

TokenResolves to
'atlas.db' / 'db'The default AsyncDatabaseConnection
'atlas.db.connection' / 'db.connection'The same connection
'atlas.db:<name>' / 'db:<name>'A named connection

All are typed on ContainerBindings once @c9up/atlas is imported.

Errors ​

Each code is a class of the errors namespace (import { errors } from '@c9up/atlas') and a @c9up/flare Exception: branch on error.code or on error instanceof errors.E_…. The status is 500, except E_ROW_NOT_FOUND (404); help, when set, says how to fix the cause. The Rust query compiler's and driver's refusals (E_UNSAFE_*, E_INJECTION_PATTERN, E_UNSUPPORTED, E_ATLAS_INSECURE_SSLMODE…) are rethrown as their class too, with the native error as cause. Every compiler refusal carries a code, a malformed spec (E_ATLAS_INVALID_SPEC) and a compiler panic (E_ATLAS_INTERNAL) included. See Error handling for the classes that carry data.

CodeRaised when
E_ROW_NOT_FOUNDA query that must return a row found none: findOrFail, findByOrFail, refresh, fresh, firstOrFail(), sole().
E_MASS_ASSIGNMENTfill() / merge() (and create, createMany, updateOrCreate) set an attribute outside fillable, or listed in guarded.
E_EXTRA_PROPERTIESfill() / merge(), or updateOrCreate / updateOrCreateMany on a found row, named a property that is not a declared column.
E_UNKNOWN_COLUMNA value was assigned to a key that is not a column. Pass { allowExtraProperties: true } to keep unknown keys in $extras.
E_INVALID_COLUMNA query names a column the entity does not declare.
E_INVALID_FIND_VALUEfind() was called without a usable primary key value.
E_MODEL_NOT_PERSISTEDAn operation that needs a stored row (delete(), refresh(), load*()…) ran on a local instance.
E_MISSING_PRIMARY_KEYThe same operation ran on a persisted projection that holds no primary key.
E_MODEL_DELETEDsave() was called on a deleted instance.
E_MISSING_OWNER_KEYassociate() was given a parent whose key is not set.
E_RELATION_NOT_LOADEDA relation was read before it was loaded. Call .preload() on the query or .load() on the instance.
E_OPTIMISTIC_LOCKA save lost an optimistic lock: another transaction modified the row since it was read.
E_STRICT_MODERaw SQL refused by strict mode (a repository's raw(), a db.raw() value written by a repository, or whereRaw() / havingRaw() / joinRaw() on a model query).
E_NO_INTERACTIVE_TRANSACTIONThe connection has no interactive transaction() (a model transaction, or useTransaction() in tests).
E_ARRAY_PARAMA list was bound to a single placeholder. Expand it into one placeholder per element.
E_UNMANAGED_DB_CONNECTIONA connection name that is not registered: a model's static connection, db.connection(name), a factory's connection(name), manager.connect(name).
E_ATLAS_MISSING_CONNECTIONNo connection to use at all: no default one (atlas has not booted), a default the config does not declare, or a repository built without a connection.
E_ATLAS_EMPTY_SELECTselect() was called with no columns. Provide at least one column name.
E_ATLAS_INVALID_PAGEpaginate() was called with page < 1.
E_ATLAS_INVALID_PER_PAGEpaginate() was called with perPage < 1.
E_ATLAS_INVALID_PAGINATIONA page, page size or row count that is not a finite, non-negative integer.
E_ATLAS_INVALID_CTE_NAMEA CTE name must be a valid identifier (letters, numbers, underscores).
E_ATLAS_INVALID_OPERATORA where() or wherePivot() operator outside the allowed list.
E_ATLAS_INVALID_INCREMENTincrement() / decrement() was given an amount that is not a finite number.
E_INVALID_DATE_COLUMN_VALUEA date column was given a value that is not a valid date.
E_ATLAS_UNDEFINED_BINDINGA query value is undefined. Validate the input first; use whereNull() to match NULL.
E_ATLAS_DIALECT_MISMATCHuseTransaction(trx) was given a transaction of another dialect than the query was built for. Start the transaction on the query's connection, or build the query from the transaction.
E_ATLAS_RAW_BINDINGSA raw fragment's placeholders and bindings do not match: a placeholder with no binding, a binding no placeholder uses, ? mixed with $N or with named bindings, or a ?? binding that is not a string.
E_ATLAS_RAW_VALUEA db.raw() was used where it cannot go: defaultTo(db.raw()) with bindings, or a raw value compared with an operator that takes none (IS NULL, BETWEEN).
E_ATLAS_NON_FINITE_NUMBERdefaultTo() was given a number that is not a SQL number (NaN, Infinity).
E_ATLAS_FACTORY_FAKER_MISSINGA factory uses faker, an optional peer of atlas that is not installed.
E_ATLAS_NAPI_NOT_FOUNDThe Rust query compiler is not loaded. The message names the platform package to install; cause holds the load failure. See Troubleshooting.
E_ATLAS_INSECURE_SSLMODEThe connection asks for sslmode=prefer or allow (URL or PGSSLMODE), which fall back to plaintext without saying so. Use disable or verify-full. See Encrypted connections.
E_ATLAS_LISTEN_UNSUPPORTEDLISTEN / NOTIFY was used on a connection that is not PostgreSQL.
E_ATLAS_LISTEN_CONNECTThe listener could not open its own PostgreSQL connection.
E_ATLAS_LISTEN_CONNECTIONThe listener's connection failed; every subscription is told.
E_ATLAS_LISTEN_CHANNELA LISTEN channel name is empty, longer than 63 bytes, or holds a NUL.
E_ATLAS_LISTEN_CLOSEDThe listener was closed while a request was pending.
E_ATLAS_LISTEN_EVENTThe native listener reported an event atlas does not define.
E_ATLAS_MIGRATION_INVALID_TABLE_NAMEmigrations.tableName is not a plain identifier.
E_MISSING_SCHEMA_FILESA migration recorded as applied has no file in the migrations directory, so it cannot be rolled back.
E_ATLAS_MIGRATION_INVALIDA migration file does not default-export a class.
E_ATLAS_MIGRATION_DUPLICATETwo migration files share a name.
E_ATLAS_MIGRATION_COMPILE_EMPTYA migration compiled to no SQL statement.
E_UNABLE_ACQUIRE_LOCKAnother run holds the migration lock. Wait for it, or clear a stale lock with migration:unlock.
E_UNABLE_RELEASE_LOCKThe run succeeded, but its migration lock had been cleared under it (migration:unlock during the run), so another run may have migrated at the same time.
E_ROLLBACK_DISABLED_IN_PRODUCTIONA rollback, reset, refresh, fresh or wipe in production without --force.
E_ATLAS_DRY_RUN_WRITEA migration tried to write while running under dryRun().
E_DEFER_REQUIRES_TRANSACTIONA migration uses this.defer() on an adapter without an interactive transaction().
E_MYSQL_FK_REQUIRES_TRANSACTIONSuspending MySQL foreign-key checks needs an interactive transaction() to restore them.
E_SCHEMA_DUMP_DIALECT_MISMATCHThe schema dump was made for another dialect.
E_SCHEMA_DUMP_TABLE_MISMATCHThe schema dump uses another migrations tracking table.
E_SEEDER_DIR_NOT_FOUNDThe seeders directory does not exist.
E_SEEDER_INVALIDA seeder file does not export a seeder class.
E_SEEDER_INVALID_PATHA seeder path resolves outside the seeders directory.
E_NO_CONNECTIONschema.<method>() needs a live connection; it is available inside a migration, not on a standalone Schema.
E_ALTER_EMPTYschema.alterTable() declared no operation.
E_ATLAS_EMPTY_TABLEschema.createTable() declared no column.
E_ALTER_MISUSE.alter() does not follow a column definition, or an alter-only method was used on a new table.
E_CHECK_EMPTYA check constraint (or checkBetween) was given no value or interval.
E_CHECK_RANGEcheckBetween was given an interval that is not [min, max].
E_CONSTRAINT_EMPTYA constraint lists no columns.
E_ENUM_EMPTYAn enum column declares no values.
E_EMPTY_VIEW_SELECTA view has no SELECT, or a materialized view was asked of a dialect that has none.
E_SPECIFIC_TYPE_EMPTYspecificType() was given an empty type.
E_SQLITE_DECIMAL_PRECISIONA decimal precision SQLite cannot store exactly.
E_UNSUPPORTEDA SQL feature the connection's dialect does not have (DISTINCT ON off Postgres, UNION ALL variants on SQLite, advisory locks on SQLite, an upsert of a row with no column on SQLite, onConflict().merge() with no column on Postgres…).
E_UNSAFE_IDENTIFIERAn identifier is not a plain name: refused by atlas's own checks or by the Rust compiler.
E_UNSAFE_SQLThe Rust compiler refused a SQL fragment, or a keyword outside its allowed list (set operation, ORDER BY direction, lock mode, referential action…).
E_UNSAFE_EXPRESSIONThe Rust compiler refused an expression.
E_UNSAFE_LITERALThe Rust compiler refused a literal value.
E_INJECTION_PATTERNThe Rust compiler refused an input that looks like an injection attempt.
E_ATLAS_INVALID_SPECThe statement the Rust compiler received is malformed: a clause misses a field, a field has the wrong shape, or the spec does not parse. Atlas builds every spec itself, so this points at an atlas bug or at a spec built by hand.
E_ATLAS_EMPTY_INSERTAn INSERT or an upsert has no row (insert([]), multiInsert([])), or has several rows that set no column.
E_UNSUPPORTED_CLIENTThe connection names a dialect atlas does not know. Atlas compiles for sqlite, postgres (or postgresql) and mysql (or mariadb).
E_ATLAS_FACTORY_INVALIDmake:factory was given a name that is not a safe file name.
E_ATLAS_SEEDER_INVALIDmake:seeder was given a name that is not a safe file name.
E_ATLAS_NO_URLA connection config has no url (or connection), or the database config has neither a top-level url nor connections.
E_ATLAS_NOT_BOOTEDThe db service (@c9up/atlas/services/db) was used before AtlasProvider.boot() ran.
E_ATLAS_CONNECTION_UNAVAILABLEA container connection token was resolved before boot opened it, or after shutdown closed it.
E_ATLAS_BOOT_FAILEDAtlasProvider.boot() could not open one or more configured connections; cause holds the first failure.
E_ATLAS_READ_ONLYA write ran on a query builder scoped to a connection opened with { mode: 'read' }.
E_ATLAS_INVALID_PRAGMAA SQLite pragma key or value is outside [A-Za-z0-9_].
E_ATLAS_DB_DRIVER_NOT_FOUNDThe Rust database driver could not be loaded, or the loaded binary is stale. The message names the platform package to install; cause holds the load failure.
E_ATLAS_NO_REPOSITORYrefresh(), fresh(), load(), loadCount(), loadAggregate() or related() was called on an entity no repository hydrated.
E_ATLAS_FILLABLE_AND_GUARDEDA model declares both static fillable and static guarded.
E_ATLAS_INVALID_ENTITY_CLASSA relation's target (or through model) does not resolve to a BaseEntity subclass.
E_ATLAS_INVALID_HOOKA hook decorator is not on a static method, or addHook() was given something other than a function.
E_ATLAS_INVALID_DECORATORA date column decorator was applied to something other than a class property.
E_UNDEFINED_RELATIONSHIPA relation name the model does not declare (load(), withCount(), whereHas()…).
E_ATLAS_INVALID_RELATIONRelation metadata lacks what its kind needs: a @ManyToMany without pivot options, a through relation without a through model.
E_ATLAS_RELATION_UNSUPPORTED_OPERATIONrelated() was asked for an operation its relation does not have: a write on @BelongsTo other than associate() / dissociate(), a write on a read-only through relation, a bulk write on @HasOne.
E_ATLAS_ASSOCIATE_NULLassociate() was given null or undefined; use dissociate().
E_ATLAS_PIVOT_KEY_COLLISIONattach() / sync() extras name a pivot key column or a pivot timestamp column.
E_ATLAS_COLUMN_ADAPTERA @Column prepare / consume adapter threw (cause holds its error) or returned a Promise.
E_ATLAS_HAS_ONE_MULTIPLE_ROWSA @HasOne preload found more than one related row for a parent.
E_ATLAS_THROUGH_KEY_NOT_UNIQUEA through relation's secondLocalKey maps to several parents.
E_ATLAS_MULTIPLE_ROWSsole() matched more than one row.
E_ATLAS_SUBQUERY_ALIASselect() was given a subquery not named with .as().
E_ATLAS_INVALID_ALIASAn alias is not a bare identifier.
E_ATLAS_INVALID_EXPRESSIONA whereExpr() extra expression is not a tail of arithmetic: it holds a comment or another forbidden character, unbalanced parentheses, a SQL keyword, or a function outside the allowed list.
E_ATLAS_INVALID_JSON_PATHA whereJsonPath() path does not start with $.
E_ATLAS_INVALID_GROUP_LIMITgroupLimit() was given a value that is not a non-negative integer.
E_ATLAS_INVALID_LOCKskipLocked() / noWait() was used without a base row lock.
E_ATLAS_INVALID_COMMENTcomment() text contains */.
E_ATLAS_INVALID_JOINA string-form join() is missing its right operand.
E_ATLAS_INVALID_AGGREGATEA withAggregate() callback set no aggregate.
E_ATLAS_INVALID_PLUCKpluck() read a column whose value is an object or a relation.
E_ATLAS_UNKNOWN_SCOPEapply() reached a scope the model does not declare, or a model with no static scopes.
E_ATLAS_CURSOR_ORDER_REQUIREDcursorPaginate() was called without an order column.
E_ATLAS_INVALID_CURSORA cursorPaginate() cursor does not decode, or its tuple length does not match the order columns.
E_ATLAS_EMPTY_UPDATEAn update was given an empty payload: a model query's update(), or an UPDATE with no SET assignment that reached the compiler.
E_ATLAS_QUERY_TIMEOUTA query ran longer than its timeout(ms).
E_ATLAS_COMPILE_EMPTYThe query compiler returned no statement.
E_ATLAS_SCHEMA_MISMATCHverifySchema() in throw mode found drift between the models and the database; the message lists the findings.
E_ATLAS_SCHEMA_DUMP_MANIFESTA schema-dump manifest (.meta.json) is not version 1 with a schemaTableName.
E_ATLAS_SCHEMA_DUMP_SEQUENCEschema:dump read a sequence parameter from the catalog that is not an integer.
E_ATLAS_SCHEMA_DUMP_PRUNEschema:dump --prune ran without a migrationsDir.
E_ATLAS_SCHEMA_GENERATE_IDENTIFIERschema:generate read a table or column name that does not make a TypeScript identifier.
E_ATLAS_DB_ASSERTIONA database assertion (assertHas, assertMissing, assertCount, assertEmpty) does not hold.
E_ATLAS_FACTORY_NO_CONNECTIONA factory's create() has no connection: none passed and none bound with .client() / .connection().
E_ATLAS_FACTORY_STATEA factory state is not defined.
E_ATLAS_FACTORY_UNKNOWN_RELATIONA factory's with() names a relation the model does not declare, or one with no related factory.
E_ATLAS_FACTORY_PIVOT_LENGTHA factory's pivotAttributes array length differs from the related-row count.
E_ATLAS_FACTORY_UNSUPPORTED_RELATIONA factory's with() names a relation kind it cannot build (a through relation).
E_ATLAS_SEEDER_DIR_REQUIREDtestUtils().db().seed() ran without a seedersDir.
E_ATLAS_INTERNALAn invariant inside atlas broke, or the Rust compiler panicked or could not serialize what it compiled: always a bug in atlas itself.

Migration ​

  • AtlasError is gone: test error.code, or error instanceof errors.E_… with import { errors } from '@c9up/atlas'. Its hint is now help.
  • EntityNotFoundError becomes errors.E_ROW_NOT_FOUND, MassAssignmentError becomes errors.E_MASS_ASSIGNMENT, OptimisticLockError becomes errors.E_OPTIMISTIC_LOCK and RelationNotLoadedError becomes errors.E_RELATION_NOT_LOADED; their fields are unchanged, except those of E_ROW_NOT_FOUND (below).
  • A Rust compiler refusal (E_UNSAFE_*, E_INJECTION_PATTERN, E_UNSUPPORTED…) now carries its code in error.code; its message no longer starts with the code, so match error.code instead of the message.
  • error.name is now the class name (Exception for most codes), not AtlasError.
  • insert({}) now inserts a row of defaults. It used to resolve [] without running anything. A model saved with nothing set now inserts its row too: it used to be marked persisted with no row in the table.
  • insert([]) and multiInsert([]) now fail with E_ATLAS_EMPTY_INSERT. They used to resolve [].
  • E_ATLAS_INVALID_DATE_COLUMN_VALUE is now E_INVALID_DATE_COLUMN_VALUE, E_ATLAS_UNKNOWN_RELATION is now E_UNDEFINED_RELATIONSHIP, E_MIGRATION_LOCKED is now E_UNABLE_ACQUIRE_LOCK and E_ATLAS_MIGRATION_NOT_FOUND is now E_MISSING_SCHEMA_FILES.
  • A connection name that is not registered is now E_UNMANAGED_DB_CONNECTION ("Cannot connect to unregistered connection <name>"); E_ATLAS_MISSING_CONNECTION stays for a missing default connection and a repository built without one.
  • E_ROW_NOT_FOUND carries the model class on model (it was the class name on entityClass), and its message is always "Row not found": the lookup criteria stay on criteria and never reach the message, which an exception handler sends to the client.
  • E_MODEL_DELETED reads "Cannot mutate delete model instance", and a successful migration run whose lock was cleared under it now fails with E_UNABLE_RELEASE_LOCK.
  • whereExpr()'s extra expression must now be a tail of arithmetic that starts with +, -, * or /. A comment (--, /*, */), current_date and the like, a qualified name or a fragment that opens with a parenthesis is refused with E_ATLAS_INVALID_EXPRESSION; use whereRaw() with bindings instead.
  • A select() / having() expression is now parsed against a grammar. IS DISTINCT FROM, a row constructor (a, b), WITHIN GROUP, exists(…), a cast to an unlisted type and a bare current_user / session_user are refused with E_UNSAFE_EXPRESSION; give select() or having() a db.raw() fragment for those, and write "current_user" quoted for a column of that name.
  • On db.from(), count(), sum(), avg(), min(), max() and their Distinct forms now refuse anything but a column or * with E_UNSAFE_IDENTIFIER; move an expression to select('sum(price * quantity) as total').
  • groupBy() on db.from() and on QueryBuilder now refuses a value that is not a column name with E_UNSAFE_IDENTIFIER. An object { raw: '…' } used to be compiled as SQL; call groupByRaw(sql, bindings) or pass db.raw(sql, bindings) instead.
  • The constraint a relation adds (the key of related().query(), the correlation of whereHas() / withCount() / withAggregate(), the parent keys of a preload) and the @SoftDeletes filter are now ANDed with your clauses taken as one group. where(a).orWhere(b) on such a query used to return, update and delete rows of other parents, and deleted rows; it now stays inside the relation and the live rows. Queries without orWhere() are unchanged.
  • update(), delete(), increment() and decrement() on a many-to-many related().query() now change only the related rows linked to the parent. They used to ignore the pivot and reach every row of the related table.
  • clearWhere() on a related().query() now keeps the relation's key; it used to drop it and return the rows of every parent.
  • whereHas(), withCount() and withAggregate() on a @SoftDeletes related model now leave the deleted rows out; call withTrashed() in the callback to count them.
  • Bulk restore() now applies the repository scope and the key of a related().query(); it used to restore matching rows of every tenant.
  • updateOrCreate(), updateOrCreateMany() and related().updateOrCreate() now apply the payload of a found row with merge(): a key that is not a declared property or its column name throws E_EXTRA_PROPERTIES (it used to be written, { IsAdmin: 1 } past guarded, { Id: … } onto the primary key). Pass { allowExtraProperties: true } to keep such keys in $extras; on the new-row branch an unknown key throws E_UNKNOWN_COLUMN, as create() does.
  • upsert() on a repository with a scope no longer updates a conflicting row outside the scope (PostgreSQL, SQLite: that row is left as it is). On MySQL an upsert() with updateColumns on such a repository now fails with E_UNSUPPORTED; check that the rows belong to the tenant, then upsert through an unscoped repository.
  • cursorPaginate() now fires beforeFetch on its query and afterFetch on the page's items; exists() and doesntExist() now fire beforeFind. A filter a hook adds now applies to them.
  • db:seed without --environment now gates static environment on the application's environment, else REAM_ENV / NODE_ENV through the alias table (production when either says so). With neither variable set, a seeder that lists environments no longer runs; set NODE_ENV or pass --environment. prod, dev and test now match production, development and testing in the list.
  • With migrations.disableRollbacksInProduction: false, db:wipe, migration:fresh, migration:rollback, migration:reset and migration:refresh now ask for confirmation in production; without an answer (a non-interactive run) they do nothing. Pass --force in a deploy script.
  • save() now writes declared columns only; an undeclared property set on the instance is no longer turned into a column name.
  • A beforeFind, beforeFetch or beforePaginate hook now receives the query with the caller's clauses closed into one group (wrapExisting()), so a filter it adds guards every orWhere() branch.

See also ​