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

Raw Queries & Query Building

Drop down to hand-written SQL with prorm.query(), bind values safely with replacements, and inject trusted SQL fragments with prorm.literal() — without giving up prorm's escaping and result shaping.
Most of the time you'll reach for the model API (findAll, create, update) or the typed query builder. But when you need a database-specific statement, a hairy analytical query, or a PRAGMA/EXPLAIN, prorm gives you a first-class escape hatch. prorm.query() runs arbitrary SQL, applies your replacements, infers the statement type, and returns results already shaped for that type.
[!IMPORTANT] Replacements are inlined, not bound
prorm.query() escapes each replacement for the active dialect and writes
it into the SQL text before the statement is sent; the driver receives no
separate parameter list. The escaping is what keeps it safe, so always pass
values through replacements and never concatenate them yourself. The
WHERE guard does not see raw SQL, and a
query firewall, if you run one, does.

Running a raw query#

prorm.query(sql, options?) executes a SQL string against the connected dialect and returns the results. The shape of the return value depends on the query type (see Result shaping).
import { Prorm } from 'ts-prorm-orm';

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

// SELECT returns an array of row objects
const rows = await prorm.query('SELECT id, email FROM users');
console.log(rows); // [{ id: 1, email: 'a@example.com' }, ...]
You never build SQL by concatenating user input. Instead you leave placeholders in the string and pass values through the replacements option — prorm escapes them for the active dialect before the query runs.

Bind parameters & replacements#

The replacements option accepts either an object (for named :param placeholders) or an array (for positional placeholders). Values are escaped by the dialect: strings are quoted with embedded quotes doubled, null/undefined become NULL, Date objects are formatted, and plain objects are serialised to JSON strings. Booleans and Buffers depend on the dialect:
ValuePostgreSQLMySQLSQLiteSQL Server
"O'Brien"'O''Brien''O''Brien''O''Brien''O''Brien'
truetrueTRUE11
nullNULLNULLNULLNULL
{ color: 'red' }'{"color":"red"}''{"color":"red"}''{"color":"red"}''{"color":"red"}'
Buffer.from('hi')'{"type":"Buffer","data":[104,105]}'X'6869'X'6869'0x6869
[!WARNING]
On PostgreSQL a Buffer replacement is written as its JSON form, not as
bytea. Insert binary data through the model API, or encode it yourself
(decode(:hex, 'hex') with a hex string).

Named replacements (:param)#

const active = await prorm.query(
  'SELECT * FROM users WHERE status = :status AND age >= :minAge',
  {
    replacements: { status: 'active', minAge: 18 },
  },
);
A named parameter must match a key exactly. One that is missing from the object (a typo, or different case) is left in the SQL as written, so the statement reaches the database with :orderId still in it and the driver rejects it — on SQLite with Missing named parameters. Placeholders inside quoted string literals are never replaced, so WHERE note <> 'is it? :maybe' is safe.
On SQL Server a named parameter can also be written @name:
const top = await prorm.query('SELECT TOP (10) * FROM orders WHERE customer_id = @customerId', {
  replacements: { customerId: 42 },
});
// SELECT TOP (10) * FROM orders WHERE customer_id = 42

Positional replacements#

Positional placeholders are filled from the array in order, and their spelling is the dialect's own:
const found = await prorm.query('SELECT * FROM users WHERE last_name = $1 AND is_active = $2', {
  replacements: ["O'Brien", true],
});
const found = await prorm.query('SELECT * FROM users WHERE last_name = ? AND is_active = ?', {
  replacements: ["O'Brien", true],
});
const found = await prorm.query('SELECT * FROM users WHERE last_name = ? AND is_active = ?', {
  replacements: ["O'Brien", true],
});
const found = await prorm.query('SELECT * FROM users WHERE last_name = @p1 AND is_active = @p2', {
  replacements: ["O'Brien", true],
});
[!CAUTION]
A ? on PostgreSQL or SQL Server is not a placeholder: with an array of
replacements it is left in the SQL untouched, and the database reports a
syntax error. Named :param placeholders work the same way on every
dialect, which makes them the portable choice.

Arrays and IN#

An array value is where the dialects differ most. The same named query, run through each dialect's replaceReplacements():
const orders = await prorm.query(
  'SELECT id, total FROM orders WHERE customer_id = :customerId AND status IN (:statuses)',
  { replacements: { customerId: 42, statuses: ['paid', 'shipped'] } },
);
The array becomes an array literal, which IN cannot use:
Write = ANY(:statuses) instead:
The array is serialised to one JSON string, so IN compares with that string
and matches nothing:
The array expands into a list:
As on MySQL, the array becomes one JSON string:
[!WARNING] IN (:list) is only portable through the model API
For a list filter that works everywhere, use
Order.findAll({ where: { status: { [Op.in]: statuses } } }), which binds
each element (see Query safety).
In raw SQL on MySQL or SQL Server, give each element its own placeholder,
as below.
const statuses = ['paid', 'shipped'];
const names = statuses.map((_, i) => `:s${i}`).join(', '); // ':s0, :s1'
const orders = await prorm.query(`SELECT id, total FROM orders WHERE status IN (${names})`, {
  replacements: Object.fromEntries(statuses.map((s, i) => [`s${i}`, s])),
});
// SELECT id, total FROM orders WHERE status IN ('paid', 'shipped')

What the database receives#

Pass a logging function to see the SQL after replacement. Run against SQLite:
const statements: string[] = [];
const rows = await prorm.query(
  'SELECT id, status, total FROM orders WHERE customer_id = :customerId AND status IN (:statuses) ORDER BY id',
  {
    replacements: { customerId: 42, statuses: ['paid', 'shipped'] },
    logging: (sql: string) => statements.push(sql),
  },
);
// rows:       [{ id: 1, status: 'paid', total: 120 }, { id: 2, status: 'shipped', total: 80 }]
// statements: ["SELECT id, status, total FROM orders WHERE customer_id = 42 AND status IN ('paid', 'shipped') ORDER BY id"]

Choosing the query type#

prorm inspects the leading keyword of your SQL to decide how to process the result. A statement starting with SELECT is treated as a SELECT, INSERT as INSERT (or UPSERT when it contains ON CONFLICT, ON DUPLICATE KEY, or INSERT OR REPLACE), UPDATE as UPDATE, DELETE as DELETE, and PRAGMA/EXPLAIN/anything else as RAW.
When the inference is wrong — for example a CTE that begins with WITH but ultimately selects — set type explicitly using the QueryTypes enum (or its string equivalent). A RAW result is the rows too, but only a SELECT-type query can be hydrated with mapToModel:
import { QueryTypes } from 'ts-prorm-orm';

const report = await prorm.query(
  `WITH recent AS (SELECT * FROM orders WHERE created_at > :since)
   SELECT customer_id, COUNT(*) AS n, SUM(total) AS revenue
   FROM recent GROUP BY customer_id ORDER BY customer_id`,
  {
    type: QueryTypes.SELECT,
    replacements: { since: '2026-01-01' },
  },
);
// [{ customer_id: 7, n: 1, revenue: 15 }, { customer_id: 42, n: 2, revenue: 200 }]
QueryTypes includes SELECT, INSERT, UPDATE, DELETE, BULKDELETE, BULKINSERT, UPSERT, VERSION, SHOWTABLES, DESCRIBE, and RAW.

Result shaping#

The return type of prorm.query() follows the (inferred or explicit) query type:
Query typeReturn value
SELECT, SHOWTABLES, DESCRIBE, VERSIONunknown[] — an array of row objects
INSERT[rows, created] — inserted rows plus a boolean
UPDATE, DELETE, BULKDELETE, UPSERTnumber — affected row count
BULKINSERTnumber — inserted row count
RAW (default)unknown[] — raw rows
// UPDATE returns the affected count
const affected = await prorm.query(
  'UPDATE users SET status = :status WHERE last_seen < :cutoff',
  { type: QueryTypes.UPDATE, replacements: { status: 'dormant', cutoff: '2025-01-01' } },
);
console.log(`${affected} rows updated`);

// INSERT returns [rows, created]
const [inserted, created] = await prorm.query(
  'INSERT INTO tags (name) VALUES (:name)',
  { type: QueryTypes.INSERT, replacements: { name: 'urgent' } },
);
created is true when the driver reports an insert id (rowid or insertId) for the statement; treat it as a hint, and select the row back when you need it.

Mapping rows to model instances#

For SELECT-style queries you can hydrate the plain rows into full model instances by passing a model and mapToModel: true. The returned objects are real ModelInstances (with instance methods, not isNewRecord), rather than plain objects.
const User = prorm.define('User', { /* ... */ });

const users = await prorm.query('SELECT * FROM users WHERE status = :status', {
  replacements: { status: 'active' },
  model: User,
  mapToModel: true,
});
// users are User instances, not plain row objects
Use raw: true when you explicitly want untouched driver output with no model instantiation.

Other query options#

prorm.query() accepts several execution controls alongside type and replacements:
await prorm.query('SELECT * FROM big_table', {
  logging: (sql, timing) => console.log(`[${timing}ms] ${sql}`), // or `true` / `false`
  benchmark: true, // always log execution time
  retry: { max: 3, match: ['ECONNREFUSED', 'Timeout'] }, // retry on matching errors
  transaction: tx, // run inside an existing transaction
});
logging — true logs to the console, false silences it, or pass a (sql, timing) => void callback.
benchmark — force timing output even when logging is otherwise off.
retry — retry up to max times when the error message matches one of the match patterns.
transaction — bind the query to a Transaction you already opened.
Every executed query also emits a query event (and a slowQuery event when it exceeds the configured slowQueryThreshold), so you can hook centralized instrumentation.

prorm.literal() — trusted raw SQL fragments#

prorm.literal(sql) wraps a string so prorm splices it into generated SQL verbatim, instead of quoting it as a value. It returns a Literal object usable inside model options — default values, attributes, where, and update payloads. Because the SQL is injected as-is, only pass literals you construct yourself, never user input.
// As a column default: evaluate NOW() in the database
const Event = prorm.define('Event', {
  createdAt: { type: DATE, defaultValue: prorm.literal('NOW()') },
});

// In-place update expressions (increment without a read-modify-write)
await View.update(
  { count: prorm.literal('count + 1') },
  { where: { postId: 42 } },
);

// Computed attributes in a SELECT
const rows = await User.findAll({
  attributes: [[prorm.literal("first_name || ' ' || last_name"), 'fullName']],
});

// Raw condition in a where clause
const power = await User.findAll({
  where: prorm.literal('LENGTH(bio) > 500'),
});
The raw condition is wrapped in parentheses and joined to the rest of the statement; Order.findAll({ where: literal('total > 6') }) on SQLite sends:
prorm.literal() and the free function literal() exported from the package
both work as update and create values, and skip attribute validators like other
SQL expressions. On SQLite:
await Product.update({ stock: literal('stock - 1') }, { where: { id: 1 } });
[!NOTE]
Before 4.9.2 the free literal() returned a plain { $literal } object that
create() and update() did not recognise, so this stored the text
{"$literal":"stock - 1"} in the column. A JSON value that carries a
$literal key beside other keys is still data.

Expression helpers: fn, col, cast, where#

For structured expressions that stay dialect-aware, prefer the typed helpers over hand-written literals. They exist both as methods on the prorm instance and as standalone functions importable from prorm.
// COUNT(id) grouped by role, as a named attribute
const byRole = await User.findAll({
  attributes: ['role', [prorm.fn('COUNT', prorm.col('id')), 'count']],
  group: ['role'],
});

// col() produces quoted identifiers: col('User', 'name') -> "User"."name"
const upper = prorm.fn('UPPER', prorm.col('User.name'));

// cast() emits a type conversion
const asText = prorm.cast(prorm.col('price'), 'VARCHAR');

// where() pairs an expression with a value or operator object
const in2026 = await User.findAll({
  where: prorm.where(prorm.fn('YEAR', prorm.col('createdAt')), 2026),
});
The same helpers are available as free functions, which compose more naturally in shared code:
import { fn, col, cast, literal } from 'ts-prorm-orm';

Order.findAll({
  attributes: [
    'status',
    [fn('SUM', col('total')), 'revenue'],
    [cast(col('created_at'), 'DATE'), 'day'],
  ],
});
A revenue-per-status rollup shows the helpers quoted for each engine:
import { fn, col } from 'ts-prorm-orm';

const revenue = await Order.findAll({
  attributes: ['status', [fn('SUM', col('total')), 'revenue']],
  where: { status: 'paid' },
  group: ['status'],
});

Lower-level query-builder helpers#

Under the model layer sits a standalone SQL compiler you can drive directly when you want a SQL string without executing it — for building statements to feed into prorm.query(), tests, or migrations. createQuickQuery() returns thin wrappers around the compiler for the common clauses. These live in the internal query-builders module (imported by relative path, not from the package root).
import { createQuickQuery } from '../query-builders';

const q = createQuickQuery();

q.select('users', { status: 'active' });          // { sql, values } for a SELECT
q.insert('users', { email: 'a@example.com' });     // compiled INSERT
q.update('users', { status: 'dormant' }, { id: 7 }); // compiled UPDATE
q.delete('users', { id: 7 });                       // compiled DELETE
q.where({ age: { $gte: 18 } });                     // just the WHERE clause string
q.order([['createdAt', 'DESC']]);                   // just the ORDER BY clause
q.limitOffset(20, 40);                              // LIMIT / OFFSET clause
Each of select/insert/update/delete returns a { sql, values } pair produced by the underlying SqlCompiler; where, order, and limitOffset return the corresponding clause fragment. For full control, createQueryBuilder({ parameterized, paramChar }) hands back the raw sqlCompiler instance whose compileSelect, compileInsert, compileUpdate, compileDelete, compileWhere, compileOrder, and compileLimitOffset methods accept richer option objects (joins, CTEs, grouping, having, pivots).

Guidelines#

Never interpolate user input into SQL. Use replacements for values and reserve prorm.literal() for SQL you author yourself.
Prefer named :param placeholders. They are spelled the same on every dialect; positional ones are not.
Don't rely on IN (:list) outside SQLite. Use = ANY(:list) on PostgreSQL, one placeholder per element elsewhere, or the model API's Op.in.
Let prorm infer the type, override when it's wrong. Set type for CTEs or statements whose leading keyword doesn't match their behavior.
Prefer typed helpers (fn, col, cast, and the query builder) over raw string SQL where a dialect-aware equivalent exists — you keep portability and escaping.
Reach for prorm.query() for genuinely database-specific features (PRAGMA, vendor extensions, complex analytics) that the model API doesn't cover.

Related reading#

Core concepts — the reading path these belong to
Going further — the specialised material
Query safety — the guard model calls get and raw SQL does not
Query firewall — pattern rules in front of prorm.query()
Modified at 2026-10-04 00:40:16
Previous
Querying
Next
Read replicas
Built with