English
Getting started
This guide covers a first entity, repository and query:
- Install
- Define an entity
- Wire a repository
- Basic CRUD
- JSON columns
- Notes
- Configuration
Install
bash
pnpm add @c9up/atlasDefine an entity
ts
import { BaseEntity, Entity, PrimaryKey, Column } from '@c9up/atlas'
@Entity('users')
export class User extends BaseEntity {
@PrimaryKey() declare id: string
@Column() declare email: string
@Column() declare status: string
}Wire a repository
ts
import { BaseRepository } from '@c9up/atlas'
import type { DatabaseConnection } from '@c9up/atlas'
export class UserService {
constructor(private db: DatabaseConnection) {}
repo() {
return new BaseRepository(User, this.db)
}
}Basic CRUD
ts
const users = service.repo()
const created = await users.create({
id: crypto.randomUUID(),
email: 'a@b.com',
status: 'active',
})
await users.save(created)
const one = users.findOrFail(created.id)
users.updateById(created.id, { status: 'disabled' })
users.delete(created)JSON columns
A column holding a JSON document keeps its JavaScript shape on both sides:
ts
@Entity('instruments')
class Instrument extends BaseEntity {
@PrimaryKey() declare id: string
@Column.json() declare metadata: Record<string, unknown> | null
@Column.json({ type: 'json' }) declare tags: string[] | null
}
instrument.metadata = { isin: 'CH0012032048' }
instrument.tags = ['XSWX', 'XVTX']
await repo.save(instrument)
const found = await repo.find(instrument.id)
found.tags // ['XSWX', 'XVTX'] — an array, not a stringAtlas serialises the value when it writes the row and parses it when it reads one. Nothing in the application converts by hand, and the three dialects behave identically: Postgres decodes JSON itself, while SQLite and MySQL hold text.
@Column.json() declares jsonb; pass { type: 'json' } for the textual form. The type is also what adds the Postgres ::jsonb cast, so @Column({ type: 'jsonb' }) does the same thing — the decorator says it in one place and cannot be mistyped.
Give the column its own prepare / consume when the document needs a different encoding; yours wins over the automatic one:
ts
@Column.json({
prepare: (value) => encrypt(JSON.stringify(value)),
consume: (value) => JSON.parse(decrypt(String(value))),
})
declare secrets: Record<string, string>null stays null — it is never stored as the string "null". On SQLite, where the column is TEXT and nothing enforces the shape, text that will not parse comes back as the raw string rather than failing the whole row: the other columns stay readable, and nothing is rewritten.
A list bound to a column that is not declared JSON is refused
Atlas refuses a top-level array as a single bind:
[E_ARRAY_PARAM] Parameter $1 is an array, which cannot be bound as a single value.The usual cause is a list meant for an IN — and on Postgres those bytes are read as a binary array header, which reports a nonsensical dimension count instead of a type error. Use whereIn(column, values) for a list, and declare the column for a JSON value. On a raw query with no entity behind it, pass JSON.stringify(value).
Notes
- Validate business inputs before
save. - Prefer typed repository methods over ad-hoc SQL.
- For dynamic columns, use explicit whitelists.
Configuration
The configure hook
Atlas ships a configure entrypoint that the framework runs when you add the package to a project. It wires the provider, seeds the database env vars, and writes a starter config/database.ts:
ts
import { configure } from '@c9up/atlas'You don't call it by hand — the framework's configure command invokes it and passes the codemods it needs. After it runs you'll have:
@c9up/atlas/providerregistered.DB_HOST/DB_PORT/DB_DATABASE/DB_USER/DB_PASSWORDadded to your env.- A
config/database.tswith a Postgres connection built fromDATABASE_URL(or the individualDB_*vars).
SQLite production pragmas
For SQLite in production, spread SQLITE_PROD_PRAGMAS into your connection's pragmas. It's the canonical WAL recipe — journal_mode = WAL (writers don't block readers) plus synchronous = NORMAL (one fsync per commit), which drops INSERT latency by roughly 5–10x versus SQLite's defaults without sacrificing crash durability:
ts
import { defineConfig, SQLITE_PROD_PRAGMAS } from '@c9up/atlas'
export default defineConfig({
default: 'sqlite',
connections: {
sqlite: {
url: 'sqlite:data/app.db',
pragmas: { ...SQLITE_PROD_PRAGMAS, foreign_keys: 'ON' },
},
},
})The constant is frozen, so spread it — app-specific overrides (like foreign_keys) stay literal alongside it.
Naming strategy
By default Atlas maps camelCase TS properties to snake_case DB columns, pluralises table names, and derives <parent>_<pk> foreign keys. That behaviour lives in CamelCaseNamingStrategy, exposed as the defaultNamingStrategy singleton and applied to every entity that doesn't opt out.
To adapt Atlas to a legacy schema (PascalCase columns, prefixed tables, custom pivot names), implement the NamingStrategy interface and attach it to an entity with a static namingStrategy field:
ts
import { BaseEntity, Entity, CamelCaseNamingStrategy } from '@c9up/atlas'
import type { NamingStrategy } from '@c9up/atlas'
class LegacyStrategy extends CamelCaseNamingStrategy implements NamingStrategy {
// Legacy tables are singular and PascalCase: "AppUser", not "app_users".
tableName(className: string): string {
return className
}
}
@Entity()
export class AppUser extends BaseEntity {
static namingStrategy = new LegacyStrategy()
}The NamingStrategy interface covers the full surface:
tableName(className)— table name for an entity class.columnName(propertyName)— DB column for a TS property (userId→user_id).propertyName(columnName)— reverse mapping, used when hydrating rows.serializedName(propertyName)— field name emitted bytoJSON().relationLocalKey(kind, parentPk)— local key for a relation.relationForeignKey(kind, parentClass, parentPk)— foreign key on the owning side.relationPivotTable(aClass, bClass)— default pivot table for amanyToMany.paginationMetaKeys?()— optional remap ofPaginator.toJSON()meta keys.
Extend CamelCaseNamingStrategy and override only the hooks you need — the rest keep the default behaviour.
Resolution walks the prototype chain, so a subclass inherits its parent's strategy unless it declares its own. getNamingStrategy(entityClass) returns the strategy in effect for a given class, falling back to defaultNamingStrategy:
ts
import { getNamingStrategy } from '@c9up/atlas'
const strategy = getNamingStrategy(AppUser)
strategy.tableName('AppUser') // 'AppUser'