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

Transactions & Isolation Levels

Transactions group several statements into a single atomic unit of work: either every statement commits together, or the whole set is rolled back. prorm exposes transactions through a single prorm.transaction() method that supports both an automatic callback mode and a manual mode, along with isolation levels, savepoints, automatic retry of serialization failures, an optional ambient transaction, and per-query transaction routing.
The contract is the same on every engine: Prorm owns the lifecycle (begin,
nest, retry, commit, roll back) and the dialect owns the connection. An option
the engine cannot honour is refused with a TransactionError before any SQL is
sent, rather than silently dropped. Which engines can do what is in the
per-dialect pages under SQL dialects; this page covers
the mechanism.

Callback mode (auto commit / rollback)#

Pass an async callback to prorm.transaction(). prorm opens a transaction, runs your callback, and commits automatically when the callback resolves. If the callback throws, the transaction is rolled back and the error is re-thrown to you.
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({
  dialect: 'postgres',
  host: 'localhost',
  database: 'mydb',
  username: 'postgres',
  password: 'password',
});

await prorm.transaction(async (t) => {
  const from = await Account.findOne({ where: { id: 1 }, transaction: t });
  const to = await Account.findOne({ where: { id: 2 }, transaction: t });

  await from.decrement('balance', { by: 100, transaction: t });
  await to.increment('balance', { by: 100, transaction: t });
  // Reaching the end of the callback commits both updates.
});
The callback's return value becomes the resolved value of prorm.transaction(), so you can compute and return data from inside the transaction:
const placed = await prorm.transaction(async (t) => {
  const created = await Order.create({ userId: 1, total: 4200 }, { transaction: t });
  await OrderItem.bulkCreate(items, { transaction: t });
  return created; // committed, then returned to the caller
});
If anything inside the callback throws, nothing is persisted:
try {
  await prorm.transaction(async (t) => {
    await Account.update({ balance: 0 }, { where: { id: 1 }, transaction: t });
    throw new Error('Business rule violated');
  });
} catch (err) {
  // The UPDATE above was rolled back; the balance is unchanged.
  console.error(err);
}

How a nested transaction behaves#

A transaction inside another does not open a second transaction — it takes a
savepoint. That is what lets an inner failure be caught and handled without
discarding the outer work.
The asymmetry is the point: an inner rollback loses only the inner work, but an
outer rollback discards everything including the released savepoints.
The states a transaction and its savepoints move through, and which calls move
them, look like this:
The diagram shows that a savepoint always returns to the active transaction it
lives in, and that only the outermost commit or rollback ends the transaction;
a statement passed a finished handle throws TransactionError instead of
running outside any transaction.

Passing the transaction to queries#

Every query you want to run inside the transaction must receive the transaction object through the transaction option. This applies to model methods (create, bulkCreate, findAll, findOne, update, destroy, increment, decrement, …) as well as raw queries.
await prorm.transaction(async (t) => {
  // Model methods
  const ada = await User.create({ name: 'Ada' }, { transaction: t });
  const active = await User.findAll({ where: { active: true }, transaction: t });
  await ada.increment('loginCount', { by: 1, transaction: t });

  // Raw SQL
  await prorm.query('UPDATE settings SET value = $1 WHERE key = $2', {
    replacements: ['on', 'feature_x'],
    transaction: t,
  });
});
Queries that do not receive transaction: t run outside the transaction and will not be rolled back with it, so be deliberate about threading t through every call — or turn on the ambient transaction described in An ambient transaction.

An ambient transaction (transactionContext)#

new Prorm({ transactionContext: true }) propagates the transaction of a
prorm.transaction(async (t) => …) callback implicitly, through Node's
AsyncLocalStorage: every query and model call made inside the callback runs
in the transaction without being passed { transaction: t }, and
prorm.getTransaction() returns it.
import { Prorm } from 'ts-prorm-orm';

const prorm = new Prorm({ dialect: 'postgres', database: 'shop', transactionContext: true });

await prorm.transaction(async () => {
  await Order.create({ userId: 1, total: 4200 });        // in the transaction
  await OrderItem.bulkCreate(items);                       // in the transaction
  await AuditLog.create({ action: 'order' }, { transaction: null }); // outside it
});
Three details follow from how it works:
It is off by default, because it changes where statements without a
transaction option run.
{ transaction: null } opts one statement out; an explicit { transaction }
always wins over the ambient one.
The context follows the callback's logical flow across awaits, so a
helper called from inside the callback is inside the transaction too. Work
handed to a queue or a timer is not.
Nested transaction() calls find their parent through the same context
whether or not the option is on; the option only decides whether queries
read it.
The payoff is in layered code, where the function that writes is several calls
away from the one that decides where the transaction starts. None of these
helpers takes a t:
async function reserveStock(productId: number, quantity: number) {
  // Runs in whatever transaction the caller opened, or none.
  await Product.decrement('stock', { by: quantity, where: { id: productId } });
}

async function recordOrder(userId: number, productId: number, quantity: number) {
  const order = await Order.create({ userId, total: 0 });
  await OrderItem.create({ orderId: order.id, productId, quantity });
  return order;
}

// The route handler owns the transaction boundary.
async function checkout(req: { userId: number; productId: number; quantity: number }) {
  return prorm.transaction(async () => {
    await reserveStock(req.productId, req.quantity);
    return recordOrder(req.userId, req.productId, req.quantity);
  });
}

Isolation levels#

The isolation level controls how much concurrent transactions can see of each other's uncommitted work. Set it with the isolationLevel option. prorm accepts both the IsolationLevel enum and the equivalent ANSI SQL string.
await prorm.transaction(
  async (t) => {
    await SalesReport.findAll({ transaction: t });
  },
  { isolationLevel: 'SERIALIZABLE' },
);
The enum form is the same call with IsolationLevel.Serializable:
import { IsolationLevel } from 'ts-prorm-orm';

await prorm.transaction(
  async (t) => {
    await SalesReport.findAll({ transaction: t });
  },
  { isolationLevel: IsolationLevel.Serializable },
);
The supported ANSI levels are:
IsolationLevel enumString literal
IsolationLevel.ReadUncommitted'READ UNCOMMITTED'
IsolationLevel.ReadCommitted'READ COMMITTED'
IsolationLevel.RepeatableRead'REPEATABLE READ'
IsolationLevel.Serializable'SERIALIZABLE'
When no level is specified, the transaction runs at the engine's own default (READ COMMITTED on PostgreSQL, REPEATABLE READ on MySQL), unless isolationLevel was set on the Prorm options, which then applies to every root transaction. On PostgreSQL the level is emitted as part of the opening statement (BEGIN ISOLATION LEVEL ...).
The level is checked against the engine before BEGIN. A request for a weaker
level than the engine guarantees is honoured by running at least as strongly
(the standard allows this; PostgreSQL itself runs READ UNCOMMITTED as
READ COMMITTED). A request for a stronger level than the engine provides
throws TransactionError — Snowflake tops out at READ COMMITTED, DuckDB,
MotherDuck and BigQuery at REPEATABLE READ, and Oracle accepts only
READ COMMITTED and SERIALIZABLE.
Some dialects accept native, non-ANSI levels (for example SQL Server's SNAPSHOT, Db2's UR/CS/RS/RR abbreviations, or Oracle's READ ONLY). Those are intentionally kept out of the IsolationLevel enum and can only be passed as plain strings to the dialects that support them.

Other transaction options#

prorm.transaction() accepts the full TransactionOptions object:
await prorm.transaction(
  async (t) => {
    /* ... */
  },
  {
    isolationLevel: 'SERIALIZABLE',
    type: 'IMMEDIATE', // SQLite BEGIN type: 'DEFERRED' | 'IMMEDIATE' | 'EXCLUSIVE'
    autocommit: false,
    lock: 'UPDATE', // apply row locking to reads in the transaction
    readOnly: true,
    deferrable: 'INITIALLY DEFERRED',
    retry: { max: 3 },
    requireAtomic: true,
  },
);
isolationLevel – ANSI isolation level (enum or string), as above.
type – transaction start type used by SQLite: 'DEFERRED' (default), 'IMMEDIATE', or 'EXCLUSIVE'. Anything but DEFERRED is refused on other engines.
autocommit – toggles the driver's autocommit behavior for the transaction.
lock – applies a lock clause to queries in the transaction. Accepts true / 'UPDATE' (FOR UPDATE), 'SHARE' (FOR SHARE on PostgreSQL, LOCK IN SHARE MODE on MySQL), 'KEY SHARE' (PostgreSQL FOR KEY SHARE), or { of: Model } to lock only a specific table (PostgreSQL).
readOnly – BEGIN … READ ONLY (PostgreSQL) / START TRANSACTION READ ONLY (MySQL). Refused elsewhere.
deferrable – true / false for PostgreSQL's DEFERRABLE transaction mode; 'INITIALLY DEFERRED' / 'INITIALLY IMMEDIATE' runs SET CONSTRAINTS ALL … so deferrable constraints are checked at commit or per statement. Refused on engines without the feature.
retry – re-run the callback on a serialization failure or deadlock; see Retrying.
transaction – the parent to nest in (a savepoint), or null to force an independent root transaction from inside another callback.
requireAtomic – throw on the HTTP dialects (D1, rqlite, the Redshift Data API, Druid) whose "transaction" runs each statement as its own request and cannot be rolled back. By default those run the callback best-effort.
Every one of these is validated before BEGIN. The refusals all throw
TransactionError, whose message names the option and the engine:
mysql has no DEFERRABLE transaction mode; drop `deferrable`.
Transaction type 'IMMEDIATE' is SQLite's BEGIN mode; postgres has no equivalent.
d1 cannot make a transaction atomic: every statement runs as its own request and is applied immediately, and a rollback cannot undo it. Use the dialect's batch() for an all-or-nothing unit, or drop requireAtomic to run best-effort.
A nested transaction is a savepoint inside its parent, so it cannot set
isolationLevel, readOnly, deferrable, a non-DEFERRED type or retry;
doing so throws with the same shape of message.

What the engine receives#

The same options open the transaction with a different statement on each
engine. These are what the dialect builders produce (captured from
buildBeginSQL(), buildSetIsolationSQL() and buildStartTransactionSQL()):
Everything goes into the one BEGIN:
OptionsStatement
noneBEGIN
{ isolationLevel: 'SERIALIZABLE' }BEGIN ISOLATION LEVEL SERIALIZABLE
{ isolationLevel: 'REPEATABLE READ', readOnly: true }BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY
{ isolationLevel: 'SERIALIZABLE', readOnly: true, deferrable: true }BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE
deferrable: true is only legal on a SERIALIZABLE READ ONLY transaction,
the one shape where PostgreSQL can wait for a snapshot that can never fail
with a serialization error. Anything else throws before BEGIN:
PostgreSQL: DEFERRABLE applies only to a SERIALIZABLE READ ONLY transaction; pass { isolationLevel: 'SERIALIZABLE', readOnly: true, deferrable: true }.
The isolation level is a separate statement on the same connection, sent
first, because MySQL's SET TRANSACTION applies only to the next
transaction on that session:
readOnly: true spells the access mode out as START TRANSACTION READ ONLY
(and readOnly: false as START TRANSACTION READ WRITE). With neither, the
driver's own beginTransaction() sends a plain START TRANSACTION.
SQLite has one connection and no isolation levels to choose between; what you
choose is when the write lock is taken:
typeStatement
'DEFERRED' (default)BEGIN TRANSACTION
'IMMEDIATE'BEGIN IMMEDIATE TRANSACTION
'EXCLUSIVE'BEGIN EXCLUSIVE TRANSACTION
A nested transaction() sends SAVEPOINT <name> instead. Use IMMEDIATE
for a read-then-write transaction: it takes the write lock up front, so the
first write cannot fail with SQLITE_BUSY half way through.
readOnly has nowhere to go and is refused:
sqlite cannot start a read-only transaction here; drop `readOnly` or use a read-only connection.
The transaction-control statements (BEGIN, SAVEPOINT, COMMIT) are sent
by the dialect on the transaction's connection and do not pass through the
logging callback; only the statements you run inside it do. Capturing a
transfer between two accounts on SQLite gives exactly these four lines, the
last one from a nested transaction that was then rolled back:
SELECT * FROM "accounts" WHERE "id" = ? LIMIT 1
UPDATE "accounts" SET "balance" = 400 WHERE "id" = 1
UPDATE "accounts" SET "balance" = "balance" + 100 WHERE "id" = 2
INSERT INTO "transfers" ("fromId", "toId", "amount") VALUES (?, ?, ?)

Locking rows inside a transaction#

Reading a row and then writing a value computed from it is a race unless the
read locks the row. Pass lock to the read, inside the transaction, and a
second transaction that wants the same row waits until the first commits.
import { Op } from 'ts-prorm-orm';

await prorm.transaction(async (t) => {
  const products = await Product.findAll({
    where: { id: { [Op.in]: [1, 2] } },
    lock: true,
    transaction: t,
  });
  // Nobody else can change these rows until this callback returns.
});
lock also takes { level, nowait, skipLocked, of }. The same three calls
render like this:
The whole database is the unit of locking. Start the transaction with
type: 'IMMEDIATE' to take the write lock before the first read.
[!WARNING]
lock outside a transaction locks nothing useful: the statement commits on
its own and the lock is released before your next line runs. Always pair it
with transaction: t.
skipLocked is what makes a table usable as a work queue. Each worker claims
a batch that no other worker holds, without waiting on them:
async function claimJobs(workerId: string) {
  return prorm.transaction(async (t) => {
    const jobs = await Job.findAll({
      where: { status: 'queued' },
      order: [['id', 'ASC']],
      limit: 10,
      lock: { level: 'UPDATE', skipLocked: true },
      transaction: t,
    });
    for (const job of jobs) {
      await job.update({ status: 'running', workerId }, { transaction: t });
    }
    return jobs;
  });
}
Without skipLocked, worker 2 would block on job 1 until worker 1 commits,
then find it already running; with nowait it would fail at once instead.

Retrying serialization failures and deadlocks#

Under SERIALIZABLE a serialization failure is a normal outcome, and a
deadlock can happen at any level. retry: { max } re-runs the whole callback
when the transaction fails with one, with exponential backoff and full jitter:
await prorm.transaction(
  async (t) => {
    const account = await Account.findOne({ where: { id: 1 }, transaction: t, lock: true });
    await account.increment('balance', { by: 100, transaction: t });
  },
  { isolationLevel: 'SERIALIZABLE', retry: { max: 3 } },
);
The sequence shows that each attempt is a complete transaction of its own, and
that only a retryable error followed by a remaining attempt leads back to
BEGIN.
max: 3 runs the callback at most four times. max must be a non-negative
integer.
What counts as retryable by default: SQLSTATE 40001 (serialization failure)
and 40P01 (deadlock detected); MySQL/MariaDB 1213 (ER_LOCK_DEADLOCK) and
1205 (ER_LOCK_WAIT_TIMEOUT); SQL Server 1205; Oracle ORA-08177 and
ORA-00060. A dialect's own isRetryableError() (CockroachDB has one) is
consulted too. Codes are read from the error and from its parent,
original and cause chain.
on: [...] replaces that list with your own codes or message fragments.
backoffBase (default 25 ms) doubles per attempt, capped at backoffMax
(default 1000 ms), and each wait is a random value up to that ceiling.
Only the callback form can retry: a manual transaction cannot be re-run, so
prorm.transaction({ retry }) throws. Only the outermost transaction can
retry; a nested one is a savepoint and its failure is the outer callback's
to handle.
[!WARNING]
Because the whole callback re-runs, keep side effects that are not part of
the transaction (sending an email, charging a card, enqueueing a job) out of
it, or make them idempotent. A retried callback that sends an email sends it
once per attempt, and a rolled-back one sends it for an order that does not
exist.

A worked example: placing an order#

The pieces above combine into the usual shape of a write path: lock what you
read, write everything in one transaction, isolate the optional part in a
savepoint, retry on contention, and run side effects only after the commit.
import { Op, TransactionError } from 'ts-prorm-orm';

type CartLine = { productId: number; quantity: number };

async function placeOrder(userId: number, cart: CartLine[]) {
  const order = await prorm.transaction(
    async (t) => {
      // 1. Lock the rows whose values the writes depend on.
      const products = await Product.findAll({
        where: { id: { [Op.in]: cart.map((l) => l.productId) } },
        lock: true,
        transaction: t,
      });

      // 2. Check, then write. A throw here rolls everything back.
      let total = 0;
      for (const line of cart) {
        const product = products.find((p) => p.id === line.productId);
        if (!product || product.stock < line.quantity) {
          throw new Error(`Out of stock: product ${line.productId}`);
        }
        await product.decrement('stock', { by: line.quantity, transaction: t });
        total += product.price * line.quantity;
      }

      const created = await Order.create({ userId, total }, { transaction: t });
      await OrderItem.bulkCreate(
        cart.map((l) => ({ orderId: created.id, ...l })),
        { transaction: t },
      );

      // 3. Optional work in a savepoint: losing it must not lose the order.
      try {
        await prorm.transaction(
          async (sp) => {
            await LoyaltyPoints.create(
              { userId, points: Math.floor(total / 100) },
              { transaction: sp },
            );
          },
          { transaction: t },
        );
      } catch (err) {
        if (err instanceof TransactionError) throw err; // misuse, not a business failure
        // Points can be re-credited later; the order stands.
      }

      return created;
    },
    // 4. Two buyers racing for the last item is normal; retry the loser.
    { isolationLevel: 'SERIALIZABLE', retry: { max: 3 } },
  );

  // 5. Side effects after COMMIT, exactly once.
  await mailer.send({ to: userId, template: 'order-confirmed', orderId: order.id });
  return order;
}
The email is the one step that cannot be rolled back, so it runs only once
nothing else can fail.

Manual transactions#

Call prorm.transaction() without a callback to get a transaction object you drive yourself. You are then responsible for calling commit() or rollback(). Options may be passed as the first argument in this mode.
const t = await prorm.transaction({ isolationLevel: 'READ COMMITTED' });

try {
  await Account.update({ balance: 500 }, { where: { id: 1 }, transaction: t });
  await Account.update({ balance: 500 }, { where: { id: 2 }, transaction: t });
  await t.commit();
} catch (err) {
  await t.rollback();
  throw err;
}
Manual mode is useful when the transaction lifetime does not map cleanly onto a single function, but the callback mode should be preferred whenever possible because it guarantees the transaction is always finalized.

Savepoints (nested transactions)#

Savepoints let you roll back part of a transaction without discarding the whole thing. Create one from an active transaction with createSavepoint(). The returned savepoint (a SavepointTransaction) has its own commit() (which issues RELEASE SAVEPOINT) and rollback() (which issues ROLLBACK TO SAVEPOINT, then releases the name so it does not pile up). It is not a new connection: a statement passed the savepoint runs on the outermost transaction's connection, inside the savepoint.
Names are generated (prorm_sp_<n>) unless you pass one. A name ends up in SQL
text, where there is no bind parameter for an identifier, so anything outside
[A-Za-z_][A-Za-z0-9_]* (up to 128 characters) is refused rather than escaped:
Invalid savepoint name "x; DROP TABLE t": a savepoint name must match /^[A-Za-z_][A-Za-z0-9_]*$/ (letters, digits and underscores, not starting with a digit).
The statements are spelled per engine (captured from the dialect builders):
EngineTakeReleaseRoll back to
PostgreSQL, SQLiteSAVEPOINT "sp1"RELEASE SAVEPOINT "sp1"ROLLBACK TO SAVEPOINT "sp1"
MySQLSAVEPOINT `sp1` RELEASE SAVEPOINT `sp1` ROLLBACK TO SAVEPOINT `sp1`
SQL ServerSAVE TRANSACTION [sp1]none (no RELEASE)ROLLBACK TRANSACTION [sp1]
OracleSAVEPOINT "sp1"none (no RELEASE)ROLLBACK TO SAVEPOINT "sp1"
Db2SAVEPOINT "sp1" ON ROLLBACK RETAIN CURSORSRELEASE SAVEPOINT "sp1"ROLLBACK TO SAVEPOINT "sp1"
Where there is no RELEASE, sp.commit() sends nothing and the savepoint
lives until the transaction ends, which is harmless.
Engines with no savepoints — the 27 in NO_SAVEPOINT_ENGINES in
src/transaction-support.ts: Snowflake, DuckDB, MotherDuck, D1, rqlite,
BigQuery, the Redshift Data API, Druid, ClickHouse, Spanner (both dialects),
Athena, Trino, Presto, Kusto, Teradata, Exasol, Materialize, RisingWave,
QuestDB and CrateDB, plus Redshift, SingleStore, Azure Synapse, Microsoft
Fabric, Apache Doris and StarRocks, which have transactions but no
SAVEPOINT — refuse to nest instead of pretending, and
capabilitiesOf(dialect).savepoints is false for each of them:
Nested transactions need savepoints, and snowflake has none. Run the work in a single transaction, or restructure it so nothing nests.
[!NOTE]
Before 4.9.2 the capabilities disagreed with what nesting did. Redshift,
SingleStore, Synapse, Fabric, Doris and StarRocks claimed savepoints, but a
nested transaction() threw; Materialize, RisingWave, Trino, CrateDB,
QuestDB, Exasol, Teradata, Spanner PG, Athena and Presto claimed none, but
createSavepoint() still sent an inherited SAVEPOINT, which the server
rejected. The savepoint builders now refuse wherever the capabilities say
there are none. Code that branched on capabilitiesOf().savepoints gets
the right answer; code that caught the server's error now gets a
TransactionError before anything is sent.
await prorm.transaction(async (t) => {
  await User.create({ name: 'Ada' }, { transaction: t });

  const sp = await t.createSavepoint();
  try {
    await AuditLog.create({ action: 'risky' }, { transaction: t });
    await sp.commit(); // RELEASE SAVEPOINT — keep the audit row
  } catch (err) {
    await sp.rollback(); // ROLLBACK TO SAVEPOINT — undo just the audit row
    // The User.create above is still intact and will commit with t.
  }
});
You can also roll a transaction back to a savepoint directly by passing the savepoint to the transaction's rollback():
await prorm.transaction(async (t) => {
  const sp = await t.createSavepoint();
  await Item.create({ sku: 'A-1' }, { transaction: t });

  // Undo everything since `sp` was created, but keep the transaction open.
  await t.rollback(sp);

  await Item.create({ sku: 'B-2' }, { transaction: t }); // still works
});

Error handling#

The two modes have different error-handling contracts:
Callback mode finalizes for you. A thrown error triggers a rollback and is re-thrown, so a single try/catch around prorm.transaction() is enough. Never call commit()/rollback() yourself inside the callback.
Manual mode does not finalize automatically. Always wrap the work in try/catch and call rollback() on failure, otherwise the transaction stays open and holds its connection.
[!CAUTION]
A manual transaction that is never committed or rolled back keeps its
connection checked out and its row locks held. Under load that is how a
pool runs dry: every request that touches the locked rows waits, then times
out. If a code path can return early, put rollback() in a finally that
checks whether commit() ran.
// Callback mode: catch around the whole call.
try {
  await prorm.transaction(async (t) => {
    await transferFunds(t);
  });
} catch (err) {
  logger.error('Transfer failed and was rolled back', err);
}
A rolled-back transaction leaves the database exactly as it was before the transaction began, so it is safe to retry the operation (for example on a serialization failure under SERIALIZABLE isolation) — retry: { max } does exactly that for you.
If the rollback itself fails, the callback's error is still the one thrown; the
rollback's error travels with it as error.rollbackError.
Two more cases throw TransactionError up front rather than running a
statement in the wrong place:
passing a transaction that has already been committed or rolled back to a
query (This transaction has already been committed or rolled back; …);
nesting in a finished transaction (Cannot nest in a transaction that has already finished.).
On SQLite (better-sqlite3), which has one shared connection, unrelated root
transactions started concurrently are queued so each runs BEGIN … COMMIT on
its own rather than interleaving. Druid and rqlite reuse SQLite's builders over
HTTP and skip that queue.

Asking the engine what it can do#

Every dialect answers transactionCapabilities(), either declared by the
dialect or derived from its name by transactionCapabilitiesFor() in
src/transaction-support.ts. This is what the option validation above reads:
const dialect = prorm.getDialectInstance();
const caps = dialect?.transactionCapabilities?.();
if (caps && !caps.savepoints) {
  // nest nothing on this engine
}
FieldMeans
savepointsSAVEPOINT (or an equivalent) exists, so a transaction can nest.
releaseSavepointA savepoint can be released explicitly (Oracle and SQL Server cannot).
maxIsolationThe strongest ANSI level the engine guarantees; null means no transactions to isolate.
isolationLevelsThe ANSI levels accepted when not every level up to maxIsolation is (Oracle).
nativeIsolationLevelsEngine-native levels accepted as-is (SNAPSHOT, UR/CS/RS/RR, READ ONLY).
readOnly, deferrable, constraintDeferralWhich transaction modes startTransaction() applies.
lockingTypeSQLite's type: 'DEFERRED' | 'IMMEDIATE' | 'EXCLUSIVE'.
atomicStatements between BEGIN and commit are all-or-nothing; false for the HTTP engines.
For PostgreSQL this comes back as savepoints: true, releaseSavepoint: true, maxIsolation: 'SERIALIZABLE', atomic: true; for D1 as savepoints: false, atomic: false. The per-engine values are in the dialect pages.

Summary#

prorm.transaction(async (t) => { ... }) runs work atomically, committing on success and rolling back on error.
Thread the transaction into every query via the transaction option, or set transactionContext: true and let the callback's context carry it.
Set concurrency behavior with isolationLevel (ANSI string, or the enum); without it the engine's default applies. A level the engine cannot provide throws.
Use createSavepoint() for partial rollbacks, and t.rollback(savepoint) to unwind to a point without ending the transaction. Engines without savepoints refuse to nest.
retry: { max } re-runs the callback on serialization failures and deadlocks; callback mode only.
Prefer callback mode for automatic cleanup; reach for manual mode only when the transaction cannot be scoped to one function.

Next: Migrations — evolving a schema you cannot simply drop and recreate.

Related reading#

Core concepts — the reading path these belong to
Going further — the specialised material
Modified at 2026-10-04 00:40:16
Previous
Terraform
Next
Type mapping: legacy and modern
Built with