1. guides
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. guides

Defining models

A model is the mapping between a JavaScript object and a database table. It
names the table, declares the columns and their types, and carries the options
that decide how Prorm writes SQL for that table — timestamps, soft deletes,
schema, indexes, hooks and scopes.
There are two ways to declare one. prorm.define() takes a plain object of
attributes and is the direct, runtime-only route. Decorators (@Table,
@Column) declare the same thing on a TypeScript class and are registered with
prorm.addModel(). Both produce the same model object with the same static
methods; pick whichever fits the codebase.

prorm.define()#

import { Prorm, DataTypes } from 'ts-prorm-orm';

const prorm = new Prorm({ dialect: 'sqlite', storage: ':memory:' });
await prorm.connect();

const User = prorm.define(
  'User',
  {
    id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING(100), allowNull: false },
    email: { type: DataTypes.STRING(255), allowNull: false, unique: true },
    role: { type: DataTypes.ENUM('admin', 'user'), defaultValue: 'user' },
    bio: { type: DataTypes.TEXT() },
    age: { type: DataTypes.INTEGER() },
    meta: { type: DataTypes.JSON() },
  },
  { tableName: 'users', timestamps: true },
);

await prorm.sync();
The sync() call emits one CREATE TABLE. The attribute map is the same on
every engine; the column types, quoting and "create only if missing" guard are
not:
ENUM becomes a real ENUM(...) on MySQL and a CHECK constraint on SQLite;
on PostgreSQL and SQL Server it is a plain string column, so the allowed values
are enforced by Prorm's validation rather than by the database (see
Enums for native PostgreSQL enum types). JSON stays JSON where
the engine has it and falls back to text where it does not — ask for
DataTypes.JSONB() when you want PostgreSQL's binary JSON. See
Data types for the full cross-dialect table.
[!NOTE]
define() is synchronous but schedules the CREATE TABLE in the background.
prorm.sync() awaits those pending creates before it runs, which is why the
normal startup shape is define every model, then await prorm.sync() once.

A model in a real project#

In an application, each model usually lives in its own module as a function
that takes the connection, and one file wires them together. That keeps
circular imports out of association code and makes the connection easy to swap
in tests.
src/
  db/
    index.ts        # creates the Prorm, calls every define*, then sync()
    models/
      user.ts       # defineUser(prorm)
      post.ts       # definePost(prorm)
  server.ts
import { DataTypes, type Prorm } from 'ts-prorm-orm';

export function defineUser(prorm: Prorm) {
  return prorm.define(
    'User',
    {
      id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
      email: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
        validate: { isEmail: true },
      },
      name: { type: DataTypes.STRING(100), allowNull: false },
      role: { type: DataTypes.ENUM('admin', 'member', 'viewer'), defaultValue: 'member' },
      passwordHash: { type: DataTypes.STRING(255), hidden: true },
      lastLoginAt: { type: DataTypes.DATE() },
    },
    {
      tableName: 'users',
      paranoid: true,
      indexes: [{ fields: ['role'] }],
    },
  );
}
import { Prorm } from 'ts-prorm-orm';
import { defineUser } from './models/user';
import { definePost } from './models/post';

export const prorm = new Prorm({
  dialect: 'postgres',
  host: process.env.PGHOST,
  database: process.env.PGDATABASE,
  username: process.env.PGUSER,
  password: process.env.PGPASSWORD,
});

export const User = defineUser(prorm);
export const Post = definePost(prorm);

User.hasMany(Post, { foreignKey: 'authorId', as: 'posts' });
Post.belongsTo(User, { foreignKey: 'authorId', as: 'author' });

export async function initDb() {
  await prorm.connect();
  if (process.env.NODE_ENV !== 'production') await prorm.sync();
}
hidden: true on passwordHash means user.toJSON() — and so
res.json(user) — never carries it, while the value is still readable as
user.passwordHash inside the server.

Attribute options#

Every value in the attributes map is an AttributeOptions object (or a bare
data type, which is shorthand for { type }).
OptionEffect
typeThe column's data type. Required.
allowNullfalse emits NOT NULL. Defaults to nullable.
defaultValueColumn default. A function is evaluated per-insert in JS; DataTypes.NOW maps to the dialect's current-timestamp default.
primaryKeyMarks the column part of the primary key.
autoIncrementAUTOINCREMENT / SERIAL / IDENTITY depending on dialect.
uniquetrue, a constraint name, or { name, msg } for a custom UniqueConstraintError message. A duplicate the database rejects is thrown as UniqueConstraintError — see Validation.
uniqueKeyGroups several columns into one composite unique constraint by sharing a name.
references{ model, key } — emits a REFERENCES clause. See Indexes & constraints.
fieldThe physical column name when it differs from the attribute name — see Column names.
commentColumn comment, where the dialect supports one.
validatePer-field validation rules — see Validation.
get / setAttribute-level accessors, used by virtual fields.
hiddenExcluded from toJSON() by default.
virtualComputed on the instance, never stored — see virtual fields.
secureHash the value before every write and never store the plain text. true (scrypt), 'bcrypt', 'argon2', or an adapter — see Passwords.
The bare-type shorthand keeps simple columns short:
const Tag = prorm.define('Tag', {
  label: DataTypes.STRING(50), // same as { type: DataTypes.STRING(50) }
  slug: { type: DataTypes.STRING(60), allowNull: false, unique: true },
  createdBy: { type: DataTypes.INTEGER(), references: { model: 'users', key: 'id' } },
});

Model options#

The third argument controls table-level behaviour.
OptionEffect
tableNameExplicit table name. Without it the model name is lower-cased and pluralised (User → users).
freezeTableNameUse the model name verbatim instead of pluralising.
schema / schemaDelimiterQualify the table (schema.table). PostgreSQL schema, MySQL database.
timestampsAdds createdAt / updatedAt. On by default; set false to opt out.
createdAt / updatedAt / deletedAtRename those columns.
paranoidSoft deletes — see below.
underscoredRenames no column: attributes keep their names, and a snake_case column is mapped with field (see the note below).
primaryKeyA string, or an array for a composite key.
indexes / constraints / uniqueKeysDeclarative index and constraint definitions created during sync().
hooksLifecycle handlers — see Hooks.
scopes / defaultScopeReusable query fragments — see Scopes.
validateModel-level (multi-field) validators.
classMethods / instanceMethodsExtra statics and instance methods merged onto the model.
hiddenMap of attribute names to hide from toJSON().
engine, charset, collate, rowFormat, initialAutoIncrement, commentMySQL/MariaDB CREATE TABLE options.
tablespace, inherit, partitionByPostgreSQL CREATE TABLE options.
validateOnInsert / validateOnUpdate / skipValidationsWhen validation runs.
[!WARNING]
underscored and the timestamps. In a define() / addModel() model
the CREATE TABLE, update(), save() and the paranoid queries all use
createdAt / updatedAt / deletedAt whether or not underscored is set;
only the object create() returns carries created_at / updated_at keys
under underscored: true. To store snake_case timestamps, name them
explicitly: { createdAt: 'created_at', updatedAt: 'updated_at', deletedAt: 'deleted_at' }, which every path honours. The SQL-objects layer (triggers,
routines) snake-cases every column under underscored; the two are being
aligned.
Global defaults can be set once on the connection and are merged under
per-model options:
import { Prorm } from 'ts-prorm-orm';

const config = {
  dialect: 'postgres' as const,
  database: 'app',
  // `define` is read at runtime but is not declared on PrormOptions yet,
  // so pass the config through a variable rather than an inline literal.
  define: { timestamps: true, paranoid: true },
};
const prorm = new Prorm(config);
A model with no declared primary key gets an implicit auto-increment id, and
timestamps: false removes both stamp columns:
const Tag = prorm.define('Tag', { label: DataTypes.STRING(50) }, { timestamps: false });

Column names (field)#

An attribute can live in a column of another name. Everything you write stays
in attribute names; prorm translates to the column on the way to the database
and back again.
const User = prorm.define('User', {
  id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, field: 'user_id' },
  email: { type: DataTypes.STRING, unique: true, field: 'email_address' },
});

await User.create({ email: 'ann@example.com' });
// INSERT INTO "users" ("email_address") VALUES (?)
await User.findAll({ attributes: ['id', 'email'], where: { email: { [Op.like]: '%@example.com' } } });
// SELECT "user_id" AS "id", "email_address" AS "email" FROM "users" WHERE "email_address" LIKE ?
The mapping applies to the table sync() creates (columns, indexes, unique
keys, foreign keys, CHECKs, partition keys), to every write (create,
bulkCreate, update, upsert, increment, destroy, restore), to every
read (where, col(), order, group, having, attributes, count and
the aggregates, includes and the foreign keys of associations), to the rows
that come back (instances and raw: true), and to the typed query builder,
views and triggers built from the model. Timestamps and deletedAt declared
as attributes with a field are stored there too. In a decorated class, use
@Field('email_address') or @Column({ type, field }).
Adding a field to an attribute of an existing table is a rename:
sync({ alter: true }) adds the new column and treats the old one as a column
the model no longer has, so move the data yourself (or rename the column in a
migration) first.
A raw SQL string — literal(), prorm.query() — is sent as written; it names
columns, not attributes.

Timestamps#

Timestamps are on unless you turn them off (timestamps: false). Prorm adds
two DATE columns, both NOT NULL DEFAULT CURRENT_TIMESTAMP, so the database
stamps new rows. They are ordinary columns: you can query, index and order by
them.
import { Op } from 'ts-prorm-orm';

const lastWeek = await User.findAll({
  where: { createdAt: { [Op.gte]: new Date(Date.now() - 7 * 86_400_000) } },
  order: [['createdAt', 'DESC']],
});
What gets written depends on how you write:
// Instance save: every attribute, including the stamps, is written back.
const grace = await User.findByPk(7);
grace.name = 'Grace';
await grace.save();

// Static update: the columns you pass, plus the updatedAt stamp.
await User.update({ age: 31 }, { where: { id: 7 } });

// silent: true leaves updatedAt alone.
await User.update({ age: 31 }, { where: { id: 7 }, silent: true });
The static Model.update() stamps updatedAt in the same statement unless
you (or a beforeUpdate hook) set it yourself, or pass silent: true. Before
4.9.2 it wrote only the values you gave it.
Rename a stamp column with a string:
prorm.define('Event', { name: DataTypes.STRING(50) }, {
  tableName: 'events',
  createdAt: 'created_on',
});

Soft deletes (paranoid)#

A paranoid model never issues DELETE. destroy() writes a timestamp into
deletedAt, and every read silently adds deletedAt IS NULL.
const attrs = {
  id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  name: { type: DataTypes.STRING(100), allowNull: false },
};
const User = prorm.define('User', attrs, { tableName: 'users', paranoid: true });

await User.destroy({ where: { id: 1 } });
await User.findAll();                                  // excludes the row
await User.findAll({ paranoid: false });               // includes it
await User.restore({ where: { id: 1 } });
await User.count();                                    // aggregates honour it too
await User.destroy({ where: { id: 1 }, force: true }); // a real DELETE
The deletedAt column is added to the attribute map automatically when
paranoid is set, so it exists in the CREATE TABLE (as a nullable
TIMESTAMP/DATETIME) without you declaring it.
[!TIP]
A unique column on a paranoid table still sees soft-deleted rows: a user who
deleted their account cannot sign up again with the same email until the old
row is force-deleted. Either destroy({ force: true }) on account deletion,
or scrub the unique value before the soft delete.

Decorator models#

The same model as a class. Decorators record metadata; prorm.addModel() reads
that metadata and builds the identical model object.
import { Table, Column, PrimaryKey, AutoIncrement, AllowNull, Unique, Default, Field, DataTypes, Model } from 'ts-prorm-orm';

@Table({ tableName: 'users', timestamps: true, paranoid: true })
class User extends Model {
  @PrimaryKey
  @AutoIncrement
  @Column(DataTypes.INTEGER())
  id!: number;

  @AllowNull(false)
  @Column(DataTypes.STRING(100))
  name!: string;

  @Unique
  @Column(DataTypes.STRING(255))
  email!: string;

  @Default('user')
  @Column(DataTypes.ENUM('admin', 'user'))
  role!: string;

  // Stored in the `display_name` column. `@Column({ type, field })` does the same.
  @Field('display_name')
  @Column(DataTypes.STRING(100))
  displayName!: string;
}

const UserModel = prorm.addModel(User);
await prorm.sync();
addModel() returns the model static, and the class itself is also usable — the
returned object is what carries findAll, create and the rest. The full
decorator set (constraints, dialect-specific column types, associations, audit,
encryption) is documented in Decorators.

Custom methods#

classMethods and instanceMethods attach behaviour without subclassing:
const User = prorm.define('User', attrs, {
  tableName: 'users',
  classMethods: {
    async findByEmail(this: ModelStatic, email: string) {
      return this.findOne({ where: { email } });
    },
  },
  instanceMethods: {
    displayName(this: { name: string; email: string }) {
      return `${this.name} <${this.email}>`;
    },
  },
});

const u = await User.findByEmail('ada@example.com');
u.displayName();

Introspecting a model#

CallReturns
Model.getTableName()The resolved table name (schema-qualified if set).
Model.getAttributes()The raw attribute map.
Model.rawAttributesSame map, as a property.
Model.describe()The table as the database reports it, via DESCRIBE/information_schema.
Model.associationsRegistered associations keyed by alias.
prorm.getModels()Map of every model on the connection.
prorm.model(name) / prorm.hasModel(name)Look one up by name.
A startup check that the database and the model agree is a common use:
const described = await User.describe();
const missing = Object.keys(User.getAttributes()).filter((name) => !(name in described));
if (missing.length) {
  throw new Error(`users is missing column(s): ${missing.join(', ')}; run the migrations`);
}

Synchronising the schema#

prorm.sync() creates the tables for every defined model, in dependency order
so that referenced tables exist before the tables that reference them.
CallBehaviour
sync()CREATE TABLE IF NOT EXISTS for each model.
sync({ force: true })DROP TABLE then CREATE TABLE — destroys data.
sync({ alter: true })Diffs the live table against the model and issues ALTER TABLE for added/changed columns. Columns the model no longer has are kept, with a warning.
sync({ alter: { drop: true } })Also drops columns that no longer exist on the model ('hard' is the same).
sync({ alter: { drop: 'soft' } })4.9.2+: parks those columns under a _prorm_dropped_ name instead of dropping them — see Soft-dropping columns.
sync({ match: /_dev$/ })Only runs when the configured database name matches.
Model.sync()Just that one model.
Model.drop() / Model.truncate()DROP TABLE / TRUNCATE.
How one sync() call decides what to do for each model:
A worked alter run on SQLite: the table was created with name nullable and
a nickname column; the model now makes name required, adds email and no
longer has nickname.
prorm.define('User', {
  id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  name: { type: DataTypes.STRING(100), allowNull: false }, // was nullable
  email: DataTypes.STRING(255),                            // new
  // nickname: removed from the model
}, { tableName: 'users' });

await prorm.sync({ alter: true });
await prorm.sync({ alter: { drop: 'soft' } });
SQLite cannot change a column's nullability in place, so Prorm rebuilds the
table inside a transaction, then adds the new column. The rebuilt
CREATE TABLE is the table's own definition with the one column edited, so
its foreign keys, CHECK and UNIQUE constraints survive; before 4.9.2 the
rebuild re-derived the columns and dropped them. nickname survives the
first call with a warning, and the second call archives it:
SQL emitted on SQLite
[!CAUTION]
sync({ force: true }) drops every table the connection can see, not
only the ones your models declare. Never point it at a shared or production
database, and guard it with match (sync({ force: true, match: /_test$/ }))
so a mis-set database name skips instead of wiping.
sync() is a development convenience. For versioned, reviewable schema change
use Migrations, and for generating those migrations from a
model diff see Schema diffing.

Next: Data types — which type to reach for, and how each one maps per engine.

Related reading#

Data types — every DataTypes.* and its per-dialect SQL
Querying — the finder methods on a model
Associations — hasOne / hasMany / belongsTo / belongsToMany
Indexes & constraints
Validation, Hooks, Scopes
Modified at 2026-10-04 00:40:16
Previous
Models from an existing database
Next
Multiple databases
Built with