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

SQL function builders

A typed library of SQL expression builders is exported from the package root. It
covers aggregates, window functions, date and time, JSON, strings, maths, CASE
and full-text search. Each builder takes the dialect as its first argument
and returns a literal expression carrying the SQL that engine actually uses. One
call site then works on every engine, with no switch over dialect names.
import { countDistinct, dateTrunc, rowNumber, col } from 'ts-prorm-orm';

const dialect = prorm.getDialect(); // 'postgres' | 'mysql' | 'sqlite' | 'mssql' | …

countDistinct(dialect, 'id'); // COUNT(DISTINCT "id") on PostgreSQL
dateTrunc(dialect, 'month', col('createdAt')); // DATE_TRUNC('month', "createdAt")
rowNumber().forDialect(dialect).partitionBy('userId').orderBy('total', 'DESC').toSQL();
// ROW_NUMBER() OVER (PARTITION BY "userId" ORDER BY "total" DESC)
Every SQL string on this page is the builder's real output. The examples use an
orders table (id, userId, status, total, createdAt, shippedAt) with
users and products alongside it.

How a builder renders#

Managed services resolve to the engine they run, and derived dialects resolve to
the grammar they inherit. Values are inlined with the engine's own escaping
rather than bound as parameters, because not every consumer of a literal
expression expands bindings. Names such as function names, operators and cast
types are validated, and anything unsafe throws UnsafeSqlArgumentError rather
than reaching the SQL.

A report in one query#

Here is monthly revenue with a paid-only total, built from builders only:
import { col, count, dateTrunc, sqlSum } from 'ts-prorm-orm';

const d = prorm.getDialect();
const month = dateTrunc(d, 'month', col('createdAt'));

const rows = await Order.findAll({
  attributes: [
    [month, 'month'],
    [count(d), 'orders'],
    [sqlSum(d, col('total'), { filter: { status: 'paid' } }), 'paidRevenue'],
  ],
  group: [month],
  order: [['month', 'ASC']],
});
filter is a native FILTER (WHERE …) where the engine has one (PostgreSQL,
SQLite) and a CASE inside the aggregate elsewhere. The two give the same
answer.

Where a builder's result can go#

PositionPostgreSQLMySQLSQLiteSQL Server
attributes: [[expr, 'alias']]yesyesyesyes
order: [['alias', 'ASC']] (by the attribute's alias)yesyesyesyes
group: [expr]yesyesyesyes
order: [[expr, 'ASC']] (the expression itself)yesyesyesyes
where: expr (a predicate as the whole condition)yesrefusedyesrefused
Ordering by the expression itself repeats it in the ORDER BY:
await Order.findAll({ attributes: [[month, 'month']], group: [month], order: [[month, 'ASC']] });
Before 4.9.2 an expression in order rendered [object Object] on PostgreSQL
and SQL Server, and group: [expr] rendered [[object Object]]] on SQL
Server. Where the WHERE builder cannot render a predicate, it throws
UnsupportedWhereError and sends nothing. It never drops the condition.

Strings are values; col() is a column#

This trips people up, so it is worth stating plainly. In the string, math,
date and JSON
builders a plain string argument is rendered as a quoted SQL
string literal
; to name a column, wrap it in col():
import { concat, col } from 'ts-prorm-orm';

concat(dialect, 'first', ' ', 'last');
// 'first' || ' ' || 'last'          — three literals

concat(dialect, col('firstName'), ' ', col('lastName'));
// "firstName" || ' ' || "lastName"  — two columns and a literal
The aggregate builders are the exception: they treat a bare string as an
identifier.
import { countDistinct, sqlSum, col } from 'ts-prorm-orm';

countDistinct(dialect, 'id'); // COUNT(DISTINCT "id")
sqlSum(dialect, col('total')); // SUM("total")   — col() also works
Use col() everywhere and the distinction stops mattering. fullTextMatch and
fullTextRank are the exception in the other direction: they take column
names as strings, and a col() there throws UnsafeSqlArgumentError.

Aggregates#

FunctionPostgreSQLMySQLSQLiteSQL ServerOracle
count(d)COUNT(*)COUNT(*)COUNT(*)COUNT(*)COUNT(*)
countDistinct(d, 'id')COUNT(DISTINCT "id")COUNT(DISTINCT `id`)COUNT(DISTINCT "id")COUNT(DISTINCT [id])COUNT(DISTINCT "id")
sqlSum(d, col('total')), avg, min, maxSUM("total")SUM(`total`)SUM("total")SUM([total])SUM("total")
stringAgg(d, col('name'), ', ')STRING_AGG("name", ', ')GROUP_CONCAT(`name` SEPARATOR ', ')GROUP_CONCAT("name", ', ')STRING_AGG([name], ', ')LISTAGG("name", ', ')
arrayAgg(d, col('tag'))ARRAY_AGG("tag")JSON_ARRAYAGG(`tag`)json_group_array("tag")throwsJSON_ARRAYAGG("tag")
percentileCont(d, 0.5, { orderBy: 'total' })PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY "total")throwsthrowsPERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY [total]) OVER ()PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY "total")
sqlMode(d, col('status'))MODE() WITHIN GROUP (ORDER BY "status")throwsthrowsthrowsSTATS_MODE("status")
arrayAgg on SQL Server throws with the reason: FOR JSON PATH shapes a whole
query, not a single aggregate expression, so there is nothing correct to emit.
That is the pattern across this library. Where an engine genuinely cannot do
something, you get an explanatory error instead of SQL that fails at the server:
Error: percentileCont() is not supported on dialect "mysql": mysql has no PERCENTILE_CONT
function; compute the percentile in a subquery with ORDER BY and LIMIT/OFFSET instead
sum is exported as sqlSum at the package root, because sum is already
taken by a utility helper. The same applies to sqlRandom, sqlTruncate,
sqlSubstring, sqlTrim, sqlLtrim, sqlRtrim, sqlJsonContains,
sqlJsonHasKey, sqlFormatDate, sqlNow, sqlRepeat, sqlReverse,
sqlCoalesce, sqlFormat, sqlLike, sqlParseDate and sqlMode.

Options: filter, distinct, orderBy#

Aggregates take a filter (a where-style condition). stringAgg also takes
distinct and orderBy:
import { stringAgg, col } from 'ts-prorm-orm';

stringAgg(dialect, col('name'), ', ', { orderBy: 'name', distinct: true });
Error: stringAgg() is not supported on dialect "sqlite": SQLite's GROUP_CONCAT does not
support an ORDER BY clause; pre-sort via a subquery instead
Error: stringAgg() is not supported on dialect "mssql": MSSQL STRING_AGG does not support DISTINCT
Counting distinct combinations passes an array. Only some engines can do this:
import { countDistinct, col } from 'ts-prorm-orm';

countDistinct(dialect, [col('userId'), col('productId')]);
EngineOutput
PostgreSQLCOUNT(DISTINCT CASE WHEN "userId" IS NOT NULL AND "productId" IS NOT NULL THEN ("userId", "productId") END)
MySQLCOUNT(DISTINCT `userId`, `productId`)
SQLite, SQL Server, Oraclethrows, and the message suggests a DISTINCT subquery
The PostgreSQL form spells out the NULL test because the row value
(NULL, 1) is not itself NULL and would otherwise be counted.

Window functions#

WindowFunctionBuilder is chainable. Set the dialect with forDialect(), then
render with toSQL(), toLiteral() or as(alias):
import { rowNumber, lag, ntile } from 'ts-prorm-orm';

rowNumber().forDialect('postgres').partitionBy('userId').orderBy('total', 'DESC').toSQL();
// ROW_NUMBER() OVER (PARTITION BY "userId" ORDER BY "total" DESC)

lag('total', 1).forDialect('mysql').partitionBy('userId').orderBy('createdAt').toSQL();
// LAG(`total`, 1) OVER (PARTITION BY `userId` ORDER BY `createdAt`)

ntile(4).forDialect('postgres').orderBy('total', 'DESC').toSQL();
// NTILE(4) OVER (ORDER BY "total" DESC)
[!CAUTION]
Without forDialect(), identifiers are double-quoted (the ANSI form). On
MySQL, a double-quoted word is a string, so PARTITION BY "userId"
partitions by a constant and the query still runs. Always call
forDialect(prorm.getDialect()).
as(alias) returns the [expression, alias] pair that attributes expects.
Here each order is ranked among its customer's orders:
import { rowNumber } from 'ts-prorm-orm';

const d = prorm.getDialect();
await Order.findAll({
  attributes: [
    'id',
    'userId',
    'total',
    rowNumber().forDialect(d).partitionBy('userId').orderBy('total', 'DESC').as('rankInUser'),
  ],
});
Available: rowNumber, rank, denseRank, percentRank, cumeDist, ntile,
lag, lead, firstValue, lastValue, nthValue, and the aggregate-over
forms sumOver, avgOver, countOver, minOver, maxOver. windowFn(name, …args) builds one the list does not cover.

Frames#

import { sumOver, avgOver } from 'ts-prorm-orm';

sumOver('total').forDialect('postgres').orderBy('id')
  .rows({ start: 'unboundedPreceding', end: 'currentRow' })
  .toSQL();
// SUM("total") OVER (ORDER BY "id" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

avgOver('total').forDialect('mysql').partitionBy('userId')
  .rows({ start: { preceding: 2 }, end: { following: 2 } })
  .toSQL();
// AVG(`total`) OVER (PARTITION BY `userId` ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
Boundaries are 'unboundedPreceding', 'unboundedFollowing', 'currentRow',
{ preceding: n } or { following: n }. range(frame) is the RANGE
equivalent of rows(frame).
exclude() adds a frame exclusion, which only some engines have. A moving
average of each row's neighbours looks like this:
import { avgOver } from 'ts-prorm-orm';

avgOver('total').forDialect(dialect).orderBy('id')
  .rows({ start: { preceding: 2 }, end: { following: 2 } })
  .exclude('currentRow')
  .toSQL();
Error: Window frame exclusion (EXCLUDE CURRENT ROW) is not supported on dialect "mysql";
no other frame specification expresses it
Error: Window frame exclusion (EXCLUDE CURRENT ROW) is not supported on dialect "mssql";
no other frame specification expresses it

Named windows#

When several window functions share one definition, define it once with
namedWindow() and reference it with over():
import { namedWindow, sumOver } from 'ts-prorm-orm';

const w = namedWindow('w').forDialect('postgres').partitionBy('userId').orderBy('createdAt');

w.toSQL(); // "w" AS (PARTITION BY "userId" ORDER BY "createdAt")  — for the WINDOW clause
sumOver('total').forDialect('postgres').over(w).toSQL(); // SUM("total") OVER "w"
Oracle has no named windows, so a reference there throws and tells you to write
the definition inline. A reference may extend the window with orderBy() or a
frame, but adding partitionBy() on top of a named window throws, as SQL
requires.

Date and time#

CallPostgreSQLMySQLSQLiteSQL ServerOracle
dateTrunc(d, 'month', col('createdAt'))DATE_TRUNC('month', "createdAt")DATE_FORMAT(`createdAt`, '%Y-%m-01 00:00:00')strftime('%Y-%m-01 00:00:00', "createdAt")DATETRUNC(month, [createdAt])TRUNC("createdAt", 'MM')
dateDiff(d, 'day', col('createdAt'), col('shippedAt'))(CAST("shippedAt" AS DATE) - CAST("createdAt" AS DATE))TIMESTAMPDIFF(DAY, `createdAt`, `shippedAt`)((CAST(strftime('%s', "shippedAt") AS INTEGER) - CAST(strftime('%s', "createdAt") AS INTEGER)) / 86400)DATEDIFF(day, [createdAt], [shippedAt])(TRUNC("shippedAt") - TRUNC("createdAt"))
dateAdd(d, col('createdAt'), 7, 'day')"createdAt" + INTERVAL '7 day'DATE_ADD(`createdAt`, INTERVAL 7 DAY)datetime("createdAt", '+7 days')DATEADD(day, 7, [createdAt])("createdAt" + 7)
sqlFormatDate(d, col('createdAt'), 'YYYY-MM-DD')TO_CHAR("createdAt", 'YYYY-MM-DD')DATE_FORMAT(`createdAt`, '%Y-%m-%d')strftime('%Y-%m-%d', "createdAt")FORMAT([createdAt], 'yyyy-MM-dd')
Five genuinely different expressions from one call is the whole point:
DATE_TRUNC does not exist on MySQL, and the DATE_FORMAT string that
approximates it is not something to retype per query. sqlFormatDate also
translates the format string itself, from YYYY-MM-DD to %Y-%m-%d or
yyyy-MM-dd.

The current time#

currentTimestamp() is the portable SQL-standard form. sqlNow() and
currentDate() use each engine's own spelling:
[!NOTE]
SQLite's datetime('now') and CURRENT_TIMESTAMP are UTC text
(YYYY-MM-DD HH:MM:SS). SQL Server's GETDATE() is the server's local time.
Store UTC and convert at the edge if the engines must agree.

JSON#

import { jsonExtract, jsonObject, col } from 'ts-prorm-orm';

jsonExtract(dialect, col('shipping'), '$.address.city');
jsonObject(dialect, { id: col('id'), total: col('total') });
Each dialect's extraction returns text, not JSON. The builders add the
unquote or cast, so a comparison against a string works without you knowing that
JSON_EXTRACT alone would return "value" with the quotes. On Oracle,
jsonExtract renders JSON_VALUE("shipping", '$.address.city').
Also jsonValue, jsonQuery, jsonExists, isJson, jsonArray, jsonSet,
jsonAgg, jsonObjectAgg, jsonKeys, jsonTypeOf, sqlJsonContains and
sqlJsonHasKey.

Full-text search#

Column names are passed as strings; several columns are searched together:
import { fullTextMatch, fullTextRank } from 'ts-prorm-orm';

fullTextMatch(dialect, ['title', 'body'], 'database index');
fullTextRank(dialect, ['title', 'body'], 'database index');
DialectfullTextMatchfullTextRank
PostgreSQLto_tsvector('english', "title" || ' ' || "body") @@ plainto_tsquery('english', 'database index')ts_rank(to_tsvector('english', "title" || ' ' || "body"), plainto_tsquery('english', 'database index'))
MySQLMATCH(`title`, `body`) AGAINST('database index' IN NATURAL LANGUAGE MODE)MATCH(`title`, `body`) AGAINST('database index')
SQLite("title" MATCH 'database index' OR "body" MATCH 'database index')throws: select bm25() from the FTS5 table in a raw query
SQL ServerFREETEXT(([title], [body]), 'database index')throws: use CONTAINSTABLE()/FREETEXTTABLE() in a raw query
Both need the corresponding index to exist; see
Indexes & constraints. The
match is a predicate, so it can be a whole where on PostgreSQL and SQLite:
import { fullTextMatch } from 'ts-prorm-orm';

await Product.findAll({ where: fullTextMatch(prorm.getDialect(), ['name'], 'wireless mouse') });
// PostgreSQL: SELECT * FROM "products" WHERE to_tsvector('english', "name") @@ plainto_tsquery('english', 'wireless mouse')
// SQLite:     SELECT * FROM "products" WHERE ("name" MATCH 'wireless mouse')
On MySQL and SQL Server that findAll throws UnsupportedWhereError before
sending anything, because the WHERE builder does not render a literal predicate
there yet. Use a raw query on those engines.

Strings and maths#

Strings: concat, upper, lower, length, replace, lpad, rpad,
split, splitPart, position, overlay, regexpReplace, sqlSubstring,
sqlTrim, sqlLtrim, sqlRtrim, sqlRepeat, sqlReverse, sqlFormat,
sqlLike.
Maths: round, ceil, floor, power, sqrt, abs, sign, mod,
log, ln, exp, greatest, least, sqlRandom, sqlTruncate, and the
bitwise bitAnd, bitOr, bitXor, bitNot, bitShiftLeft, bitShiftRight.
General: sqlCoalesce, nullif, tryCast, collate.
import { sqlCoalesce, nullif, round, col } from 'ts-prorm-orm';

sqlCoalesce(dialect, col('nickname'), col('name'), 'anonymous'); // COALESCE("nickname", "name", 'anonymous')
nullif(dialect, col('discount'), 0); // NULLIF("discount", 0)
round(dialect, col('total'), 2); // ROUND("total", 2)
greatest / least are worth singling out. The same call produces three
different shapes:
import { greatest, col } from 'ts-prorm-orm';

greatest(dialect, col('a'), col('b'));
SQL Server has no GREATEST before 2022, so the builder expands it into the
equivalent CASE. The expansion compares each candidate with every argument,
itself included, so it generalises to any number of arguments.

CASE expressions#

import { caseWhen, caseOf } from 'ts-prorm-orm';

caseWhen()
  .when({ status: 'active' }, 1)
  .else(0)
  .toSQL('postgres');
// CASE WHEN "status" = 'active' THEN 1 ELSE 0 END

caseOf('status').when('a', 1).else(0).toSQL('mysql');
// CASE `status` WHEN 'a' THEN 1 ELSE 0 END — the simple (switch) form
caseWhen() takes a full where-style condition per
branch; caseOf(column) is the simple form that compares one expression against
each value. Both accept the dialect in the constructor (caseWhen(dialect)),
in forDialect(dialect) or in toSQL(dialect), and support as(alias) and
toLiteral().
A common use is conditional aggregation, counting subsets in one pass:
import { caseWhen, count, sqlSum } from 'ts-prorm-orm';

const d = prorm.getDialect();
await Order.findAll({
  attributes: [
    [count(d), 'total'],
    [sqlSum(d, caseWhen(d).when({ status: 'paid' }, 1).else(0).toLiteral()), 'paid'],
  ],
});
[!TIP]
count(d, undefined, { filter: { status: 'paid' } }) expresses the same count
directly, and uses the native FILTER (WHERE …) clause where the engine has
one.

Related reading#

query-builders — how these fit the compiler
Querying — attributes, group, having
Query operators — the where vocabulary
Raw queries — when a builder is not enough
Modified at 2026-10-04 00:40:16
Previous
SQL features
Next
SQLite advanced features
Built with