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

Data types

DataTypes is the vocabulary you use to declare a column. Each type is a small
class that knows how to render itself as SQL, and each dialect gets the final
say — getDataTypeSql() on the dialect turns a DataTypes.BOOLEAN() into
BOOLEAN on PostgreSQL, TINYINT(1) on MySQL, BIT on SQL Server and
INTEGER on SQLite. Writing DataTypes.BOOLEAN() once therefore gives you a
column that behaves the same everywhere without you tracking the differences.
import { Prorm, DataTypes } from 'ts-prorm-orm';

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

const Product = prorm.define('Product', {
  id:        { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  sku:       { type: DataTypes.STRING(64), allowNull: false, unique: true },
  price:     { type: DataTypes.DECIMAL(10, 2), allowNull: false },
  inStock:   { type: DataTypes.BOOLEAN(), defaultValue: true },
  tags:      { type: DataTypes.ARRAY(DataTypes.STRING(50)) },
  attributes:{ type: DataTypes.JSONB() },
  releasedAt:{ type: DataTypes.DATE() },
});
The same model on four engines. Note what each one does with the array and the
JSON column:
[!WARNING]
On MySQL the tags array became a VARCHAR(255). An ARRAY of fifty tags
will not fit, and nothing in the database knows it is a list. If the model
must run on more than PostgreSQL, declare lists as JSON() instead.
A type travels two ways: out through the dialect when the table is created, and
back in through the coercion step when a row is read.
Every factory is also exported at the package root, so DataTypes.STRING(100)
and STRING(100) are the same thing:
import { STRING, INTEGER, JSONB } from 'ts-prorm-orm';

Cross-dialect SQL mapping#

The exact SQL each type produces, taken from the dialects' own
getDataTypeSql(). Split by family rather than given as one wide grid, because
what you usually want is one row, not a comparison of all twenty-one.
In 4.x the default typeMapping: 'legacy' keeps 4.8's DDL for existing
databases; see Type mapping for how it differs from
'modern' and which columns need a manual migration.

Text#

DataTypeSQLitePostgreSQLMySQLSQL ServerOracle
STRING(100)VARCHAR(100)VARCHAR(100)VARCHAR(100)NVARCHAR(100)VARCHAR2(100)
STRING()VARCHAR(255)VARCHAR(255)VARCHAR(255)NVARCHAR(255)VARCHAR2(255)
CHAR(2)CHAR(2)CHAR(2)CHAR(2)CHAR(2)CHAR(2)
TEXT()TEXTTEXTTEXTNVARCHAR(MAX)CLOB

Numbers#

DataTypeSQLitePostgreSQLMySQLSQL ServerOracle
INTEGER()INTEGERINTEGERINTINTNUMBER(10)
BIGINT()BIGINTBIGINTBIGINTBIGINTNUMBER(19)
FLOAT()FLOAT(10,2)REALFLOATFLOATFLOAT
DOUBLE()DOUBLE(10,2)DOUBLE PRECISIONDOUBLEFLOATFLOAT
DECIMAL(10,2)DECIMAL(10,2)DECIMAL(10,2)DECIMAL(10,2)DECIMAL(10,2)NUMBER(10,2)
Only DECIMAL is exact. FLOAT and DOUBLE are binary floating point on
every engine here — never use them for money.

Dates, times and booleans#

DataTypeSQLitePostgreSQLMySQLSQL ServerOracle
BOOLEAN()INTEGERBOOLEANTINYINT(1)BITNUMBER(1)
DATE()DATETIMETIMESTAMPDATETIMEDATETIME2DATE
DATEONLY()DATEDATEDATEDATEDATE
TIME()TIMETIMETIMETIMEVARCHAR2(8)
Oracle's DATE carries a time component, so DATEONLY() and DATE() are the
same column type there; the difference is in how prorm reads the value back.

Structured and binary#

DataTypeSQLitePostgreSQLMySQLSQL ServerOracle
JSON()TEXTJSONJSONNVARCHAR(MAX)CLOB
JSONB()TEXTJSONBJSONNVARCHAR(MAX)BLOB
BLOB()BLOBBYTEABLOBVARBINARY(MAX)BLOB
UUID()TEXTUUIDCHAR(36)UNIQUEIDENTIFIERRAW(16)
ARRAY(INTEGER())TEXTINTEGER[]VARCHAR(255)NVARCHAR(255)VARCHAR2(255)
Where JSON is stored as TEXT, values still round-trip as parsed JavaScript
values — the encoding happens in prorm rather than the engine.

Special#

DataTypeSQLitePostgreSQLMySQLSQL ServerOracle
ENUM('a','b')TEXT CHECK(col IN ('a','b'))VARCHAR(255) CHECK (col IN ('a', 'b')) †ENUM('a','b')NVARCHAR(255)VARCHAR2(255)
GEOMETRY()BLOBgeometryGEOMETRYGEOMETRYSDO_GEOMETRY
VIRTUAL()(no column)(no column)(no column)(no column)VARCHAR2(255)
† PostgreSQL has no inline ENUM(...) column syntax, so under the default
'legacy' mapping ENUM() is a string column with a CHECK on the value set
(CockroachDB too). Before 4.9.2 it was a bare VARCHAR(255) that accepted any
value. For a real enum type, create it first and reference it by name — see
Enums below.
Two more mappings worth knowing because they change the column, not just its
type name:
INTEGER()/BIGINT() with autoIncrement: true become SERIAL/BIGSERIAL
on PostgreSQL, and INTEGER PRIMARY KEY AUTOINCREMENT on SQLite.
ARRAY only exists natively on PostgreSQL. On every other dialect the column
degrades to a string; store JSON instead if you need portability.

The type catalogue#

Strings#

TypeNotes
STRING(length?, binary?)VARCHAR(length). With no length it renders TEXT. binary: true adds a BINARY collation.
VARCHAR(length = 255, binary?)Always VARCHAR, never degrades to TEXT.
CHAR(length = 1)Fixed width.
TEXT('tiny' | 'medium' | 'long')Unbounded text; the size hint maps to TINYTEXT/MEDIUMTEXT/LONGTEXT on MySQL.
TINYTEXT(), MEDIUMTEXT(), LONGTEXT()Explicit MySQL text sizes; portable fallbacks elsewhere.

Numbers#

TypeNotes
INTEGER(), TINYINT(), SMALLINT(), MEDIUMINT(), BIGINT()Integer family. All support .UNSIGNED() and .ZEROFILL() chaining on MySQL/MariaDB.
FLOAT(length?, decimals?), DOUBLE(...), REAL(...)Approximate numerics.
DECIMAL(precision, scale)Exact numerics — use this for money.
{ views: { type: DataTypes.INTEGER().UNSIGNED() } }  // INT UNSIGNED on MySQL
BIGINT values are handed back as JavaScript BigInt when the driver returns
one; Prorm deliberately does not coerce them to Number, which would lose
precision past 2^53.
[!CAUTION]
Whether the driver returns a BigInt is the driver's choice. With the default
SQLite driver settings, writing 9007199254740993n and reading it back gives
the number 9007199254740992 — off by one, silently. Keep identifiers that can
exceed 2^53 (snowflake IDs, external account numbers) in a STRING column, or
enable your driver's big-number mode.

Booleans#

BOOLEAN() — read back as a real true/false regardless of whether the
database stored 1, '1' or true.

Dates and times#

TypeNotes
DATE(precision?, timezone?)Date and time. timezone: true gives a zoned type under typeMapping: 'modern' (see below).
DATEONLY()Calendar date, no time.
TIME(precision?, timezone?)Time of day.
DATETIME(), TIMESTAMP()Dialect-specific spellings when you want them explicitly.
NOWNot a column type — a default value meaning "the database's current timestamp".
Values come back as Date instances even on SQLite, which stores them as ISO
strings.
The time zone flag is one of the places where the type mapping
mode changes the column. DataTypes.DATE(3, true) renders:
typeMappingSQLitePostgreSQLMySQLSQL ServerOracle
'legacy' (default)DATETIMETIMESTAMPTZ(3)DATETIME(3)DATETIME2(3)DATE
'modern'DATETIMETIMESTAMPTZ(3)TIMESTAMP(3)DATETIMEOFFSET(3)TIMESTAMP(3) WITH TIME ZONE
[!IMPORTANT]
Under the default 'legacy' mapping, PostgreSQL (and the rest of the
PostgreSQL family) keeps the zone: DATE(3, true) is TIMESTAMPTZ(3).
Before 4.9.2 the legacy mapping dropped it and created TIMESTAMP(3), so a
column created by an older release has no zone until you migrate it. MySQL, SQL Server
and Oracle still drop the zone under 'legacy'; opt in with
new Prorm({ …, typeMapping: 'modern' }) for new databases.
const attributes = { createdAt: { type: DataTypes.DATE(), defaultValue: DataTypes.NOW } };
DataTypes.NOW, DataTypes.NOW() and fn('NOW') all become the engine's
current-timestamp default: DEFAULT CURRENT_TIMESTAMP on most engines,
now() on ClickHouse and CURRENT_TIMESTAMP() on BigQuery.
[!NOTE]
Older releases wrote the uncalled DataTypes.NOW as the text
DEFAULT '() => new NOW()' on the PostgreSQL and MySQL families, HANA, Db2,
BigQuery, Snowflake, ClickHouse and DuckDB, and createTable() failed on
Firebird, Teradata, Vertica and several others. A table created that way
still has the text default; replace it with changeColumn or a migration.

Identifiers#

TypeNotes
UUID()Native UUID/UNIQUEIDENTIFIER where available, CHAR(36)/TEXT elsewhere.
UUIDV1, UUIDV4Default-value generators, not column types. Use them as a defaultValue (see below).
A generator default — DataTypes.UUIDV4, DataTypes.UUIDV1 or any
function such as () => randomUUID() — is evaluated in JavaScript by
create() and written in the INSERT. It is not a database default, so the
CREATE TABLE carries no DEFAULT for it:
const Order = prorm.define(
  'Order',
  {
    publicId: { type: DataTypes.UUID(), allowNull: false, unique: true, defaultValue: DataTypes.UUIDV4 },
    total: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
  },
  { tableName: 'orders', timestamps: false },
);

await Order.create({ total: 12.5 });
Rows inserted outside Prorm (raw SQL, another service) get no value, so keep
allowNull: false on such a column. DataTypes.NOW is different: it stays a
SQL default (CURRENT_TIMESTAMP).
[!NOTE]
Before 4.9.2, define() models did not send a generator default in the
INSERT, and CREATE TABLE carried the generator's source text as the
column default (DEFAULT '() => new UUIDV4()'), which is what those rows
stored. Tables created by an older release may still have that default;
drop it with changeColumn or a migration.

JSON#

TypeNotes
JSON()Objects and arrays are serialised on write and parsed back on read.
JSONB()PostgreSQL binary JSON — indexable, supports containment operators. Falls back to JSON/TEXT elsewhere.
HSTORE()PostgreSQL key/value column.
Assigning a plain object is enough — it is serialised on write:
await Product.create({ attributes: { colour: 'red', sizes: [1, 2, 3] } });
You get a JavaScript value back on read, on every dialect:
const p = await Product.findByPk(1);
p.attributes.colour;   // 'red' — already parsed
Where the driver returns a real object (PostgreSQL JSON/JSONB, MySQL JSON)
it is passed through untouched. Where the column is stored as text — SQLite, and
any dialect whose mapping in the table above is TEXT/NVARCHAR(MAX)/CLOB —
the string is parsed. Text that is not valid JSON is returned verbatim rather
than throwing.
Behaviour change. Models built with prorm.define() used to hand back the
raw JSON string on text-backed dialects. If you have code doing its own
JSON.parse() on SQLite, drop it — it would now be parsing an object.
PostgreSQL and MySQL are unaffected.
Filter inside a document with Op.json(path) nested under the column (not a
dotted attribute name — a dotted key is treated as a column name and the
database will reject it):
import { Op } from 'ts-prorm-orm';

await Product.findAll({ where: { attributes: { [Op.json('$.colour')]: 'red' } } });
Which engines can render that path predicate today:
Not rendered: the call throws UnsupportedWhereError ("the operator
'.colour' is not implemented by its WHERE builder. The statement was not
sent…"
). Use the PostgreSQL JSON operators from
Query operators instead.
Not rendered: the call throws UnsupportedWhereError before anything is sent,
rather than running the query without the condition.
Not rendered: the call throws UnsupportedWhereError before anything is sent.
The full set of JSON predicates — Op.contains, Op.keyExists,
Op.jsonHasKey, Op.jsonPathExists and the PostgreSQL @> / -> / #>
family — is in Query operators.

Binary#

BLOB('tiny' | 'medium' | 'long'), TINYBLOB(), MEDIUMBLOB(),
LONGBLOB(), BINARY(length), VARBINARY(length).

Enums#

ENUM(...values) renders a real ENUM on MySQL/MariaDB, a
TEXT CHECK(col IN (...)) on SQLite and a VARCHAR(255) CHECK (col IN (...))
on PostgreSQL — all three enforce the value set in the database.
On PostgreSQL, create the type once and reference it by name:
const pg = prorm.getDialectInstance();
await pg.createEnumType('user_role', ['admin', 'user'], { ifNotExists: true });

prorm.define('User', {
  role: { type: 'user_role' as any, defaultValue: 'user' },
});
dropType(name, { ifExists, cascade }) removes it again. A plain string is
always accepted as a type and passed through verbatim, which is the escape
hatch for any type Prorm has no factory for.

Collections and structures#

TypeAvailable on
ARRAY(subtype)PostgreSQL (INTEGER[]), degrades elsewhere
LIST(subtype), STRUCT(fields), MAP(key, value), UNION(...)DuckDB / ClickHouse / Databricks-style nested types
SET(...values)MySQL/MariaDB
RANGE(subtype)PostgreSQL range types (int4range, tstzrange, …)

Network types#

INET(), INET6(), CIDR(), MACADDR() — PostgreSQL native, text elsewhere.

Spatial#

GEOMETRY(type?, srid?), GEOGRAPHY(type?, srid?), plus the concrete shapes
POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING,
MULTIPOLYGON, GEOMETRYCOLLECTION.
{ location: { type: DataTypes.GEOGRAPHY('POINT', 4326) } }
On PostgreSQL this needs PostGIS — await prorm.createExtension('postgis').

Virtual columns#

VIRTUAL() and VIRTUALSTRING() declare an attribute that has no database
column at all
: getDataTypeSql() returns an empty string and the column is
omitted from CREATE TABLE and from every INSERT/UPDATE. The value is
computed in JavaScript by the attribute's get. See
Virtual fields.
const attributes = {
  firstName: { type: DataTypes.STRING(50) },
  lastName:  { type: DataTypes.STRING(50) },
  fullName:  {
    type: DataTypes.VIRTUAL(),
    get(this: { firstName: string; lastName: string }) {
      return `${this.firstName} ${this.lastName}`;
    },
  },
};

Type coercion on read#

Rows arriving from the driver are cast back to the JavaScript type the
attribute declares, because wire formats differ per dialect. A round trip on
SQLite, where every one of these is stored as text or an integer:
const Line = prorm.define('Line', {
  sku: DataTypes.STRING(64),
  price: DataTypes.DECIMAL(10, 2),
  inStock: { type: DataTypes.BOOLEAN(), defaultValue: true },
  attributes: DataTypes.JSON(),
  at: DataTypes.DATE(),
});
await prorm.sync();

await Line.create({ sku: 'A', price: '19.99', attributes: { colour: 'red' }, at: new Date('2026-03-01T09:30:00Z') });
const row = await Line.findOne({ where: { sku: 'A' } });

typeof row.price;          // 'number'  (19.99; sent as '19.99')
row.inStock;               // true      (stored as 1)
row.attributes.colour;     // 'red'     (stored as '{"colour":"red"}')
row.at instanceof Date;    // true      (stored as an ISO string)
Declared typeCoerced to
INTEGER, SMALLINT, MEDIUMINT, TINYINTnumber
BIGINTnumber, or left as BigInt when the driver returns one
FLOAT, DOUBLE, DECIMAL, REALnumber — so a DECIMAL(20,4) beyond 15–16 significant digits loses precision in JavaScript
BOOLEANtrue / false (from 1/0/'1'/'0')
DATE, DATEONLYDate
JSON, JSONBparsed object / array; unparseable text is returned verbatim
Unparseable values are left untouched rather than turned into NaN or an
Invalid Date.

TypeScript#

Attribute types are declared separately from the runtime data types; the
InferAttributes helpers keep the two in step:
import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'ts-prorm-orm';

class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  declare id: CreationOptional<number>;   // optional on create, present on read
  declare email: string;
  declare bio: string | null;
}
See TypeScript types for the full set.

Next: Querying — the finders, and how one FindOptions becomes SQL.

Related reading#

Defining models
Virtual fields
Query operators — JSON and array operators
Dialects — per-engine type notes and caveats
Type mapping — typeMapping: 'legacy' vs 'modern'
Modified at 2026-10-04 00:40:16
Previous
Couchbase: structured N1QL queries
Next
Decorators
Built with