1. dialects
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. dialects

Teradata Dialect

Reference for the teradata SQL dialect (Teradata Vantage).

Source: teradata
Tests: teradata

Overview

Teradata Vantage is not a PostgreSQL or MySQL fork — its own proprietary
engine, wire protocol and SQL dialect. But the shape of that SQL where the
ORM spends most of its time (double-quoted identifiers, '...' strings with
doubled apostrophes, WHERE/GROUP BY/HAVING/JOIN as PostgreSQL's
builders already emit them, and a MERGE statement for upserts) is ANSI and
matches PostgreSQL closely enough that TeradataDialect extends
PostgresDialect
and reuses its where/order/join/CTE builders — every value
still leaves those builders as a $n placeholder with its value beside it.
Nothing about the wire is PostgreSQL's, though, so the whole connection
layer, escaping, data types, pagination, table DDL and every non-relational
PostgreSQL feature is replaced or refused.

PropertyValue
Dialect nameteradata
ExtendsPostgresDialect
Driverteradatasql (official Teradata SQL Driver for Node.js)
Default port1025 (dbs_port)
Registered with PrormYes — SqlDialect.Teradata = 'teradata', lazily loaded from ./teradata as TeradataDialect (src/dialects/loaders.ts)
Cloud SDKnone
Local runtimenone — hosted service only

Quick start

Install

$ npm install ts-prorm-orm teradatasql
$ pnpm add ts-prorm-orm teradatasql
$ yarn add ts-prorm-orm teradatasql
$ bun add ts-prorm-orm teradatasql

Connect

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

export const db = new Prorm({
  dialect: 'teradata',
  host: 'td.example.com',
  database: 'sales',
  username: 'dbc',
  password: process.env.TD_PASSWORD,
});
import { Prorm } from 'ts-prorm-orm';

export const db = new Prorm({
  dialect: 'teradata',
  url: 'teradata://dbc:secret@td.example.com:1025/sales',
});

A URL is folded into host, port, database, username and password before the dialect is built; any of those passed alongside it wins.

Define a model

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

const User = db.define('User', {
  id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  email: { type: DataTypes.STRING(255), allowNull: false, unique: true },
  name: { type: DataTypes.STRING(100) },
});

await db.sync(); // CREATE TABLE — see Generated SQL below

[!WARNING] db.sync() cannot create this table
Teradata does not support CREATE TABLE IF NOT EXISTS. Check DBC.TablesV (or catch error 3803, "table already exists") before creating.

Query

import { Op } from 'ts-prorm-orm';

await User.create({ email: 'ada@example.com', name: 'Ada' });

const page = await User.findAll({
  where: { name: { [Op.like]: 'A%' } },
  order: [['id', 'ASC']],
  limit: 20,
  offset: 40,
});

Generated SQL

Each block is the statement the model call above it hands the dialect's query(), captured with the driver stubbed out. The model layer inlines the values.

Insert, update and delete

await User.create({ email: 'ada@example.com', name: 'Ada' });
await User.update({ name: 'Grace' }, { where: { email: 'ada@example.com' } });
await User.destroy({ where: { id: 1 } });
-- insert
INSERT INTO "users" ("email", "name") VALUES ('ada@example.com', 'Ada');

-- update
UPDATE "users" SET "name" = 'Grace', "updatedAt" = TIMESTAMP '2026-09-27 05:01:42.230000' WHERE "email" = 'ada@example.com';

-- delete
DELETE FROM "users" WHERE "id" = 1;

Upsert

await User.upsert({ id: 1, email: 'ada@example.com', name: 'Ada Lovelace' });
MERGE statement
MERGE INTO "users" AS tgt USING (SELECT 1 AS "id", 'ada@example.com' AS "email", 'Ada Lovelace' AS "name") AS src ON tgt."id" = src."id" WHEN MATCHED THEN UPDATE SET "email" = src."email", "name" = src."name" WHEN NOT MATCHED THEN INSERT ("id", "email", "name") VALUES (src."id", src."email", src."name");

upsert() also reads the row by primary key before and after the write, to return the instance.

Pagination

await User.findAll({
  where: { name: { [Op.like]: 'A%' } },
  order: [['id', 'ASC']],
  limit: 20,
  offset: 40,
});
SELECT * FROM "users" WHERE "name" LIKE 'A%' QUALIFY ROW_NUMBER() OVER (ORDER BY "id" ASC) BETWEEN 41 AND 60 ORDER BY "id" ASC;

JSON

[!NOTE] No JSON operator in the WHERE builder
DataTypes.JSON() maps to JSON, but this dialect's WHERE builder refuses Op.contains on it: Teradata does not support the @> / <@ containment operators. The condition used a PostgreSQL-only operator. On Teradata, LIKE on a NOT CASESPECIFIC column is already case-insensitive; JSON values are read with JSONExtractValue.

Transaction

await db.transaction(async (t) => {
  await User.create({ email: 'grace@example.com', name: 'Grace' }, { transaction: t });
  await User.update({ name: 'Grace Hopper' }, { where: { email: 'grace@example.com' }, transaction: t });
});
INSERT INTO "users" ("email", "name") VALUES ('grace@example.com', 'Grace');
UPDATE "users" SET "name" = 'Grace Hopper', "updatedAt" = TIMESTAMP '2026-09-27 05:01:42.230000' WHERE "email" = 'grace@example.com';
-- driver: commit() (teradatasql)

[!WARNING] No savepoints
Nested transactions need savepoints, and teradata has none. Run the work in a single transaction, or restructure it so nothing nests.

Table sampling

sample on the select builder reads a random fraction of the table, for estimates over large tables:

const sample = db.getDialectInstance()!.buildSelectQuery({
  tableName: 'users',
  sample: { method: 'BERNOULLI', percent: 10 },
});
await db.query(sample.sql);
SELECT * FROM "users" SAMPLE 0.1;

Type mapping for the portable descriptors: STRING → VARCHAR(255), auto-increment INTEGER → INTEGER, BOOLEAN → BYTEINT, DATE → TIMESTAMP(6), UUID → CHAR(36), JSON → JSON. The type comparison lines the major engines up side by side.

Connection

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

const orm = new Prorm({
  dialect: SqlDialect.Teradata, // or the string 'teradata'
  host: 'td.example',
  // port defaults to 1025
  username: 'dbc',
  password: process.env.TD_PASSWORD,
  database: 'sales',
  dialectOptions: { tmode: 'ANSI', logmech: 'LDAP' },
});

Or construct the dialect directly:


const d = new Prorm({
  dialect: 'teradata',
  host: 'td.example',
  username: 'dbc',
});
await d.connect();
OptionDefaultEffect
host'localhost'driver host
port1025driver dbs_port
username—driver user
password—driver password
database—driver database
tmode— (database default)session mode: 'TERA', 'ANSI', or 'DEFAULT'
logmech—logon mechanism ('TD2', 'LDAP', 'JWT', 'BROWSER', ...)
encryptdata—encrypt data in transit (stringified)
connectParams—any further teradatasql connection parameters, passed through verbatim (every value stringified)

The teradatasql module is loaded lazily with require() on the first
connect(); if it is not installed, connect() throws with an install
hint (npm install teradatasql, 64-bit Node.js 18.20+).

The driver follows the DB-API shape: connect(params) → connection,
con.cursor() → cursor, cur.execute(sql, params) with ? markers,
cur.fetchall() → row arrays, cur.description → column names. query()
rewrites the builders' $n (or :name) placeholders outside string literals
to ? markers and hands the values to the driver as real bind parameters —
nothing is inlined on the wire:

const { sql, values } = d.buildSelectQuery({ tableName: 'users', where: { name: "O'Brien", active: true } });
await d.query(sql, { replacements: values });
// executed: 'SELECT * FROM "users" WHERE "name" = ? AND "active" = ?', params: ["O'Brien", 1]

getDatabaseVersion() reads DBC.DBCInfoV (InfoKey = 'VERSION').

What differs from Postgres

TeradataDialect extends PostgresDialect (postgres) and
overrides 109 of its methods (Object.getOwnPropertyNames(TeradataDialect.prototype),
computed by the scratch test); everything else is inherited unchanged.

AreaOverridden
Connection and executioncommitTransaction, connect, disconnect, getConnection, isConnected, listen, notify, query, queryStream, rollbackTransaction, startTransaction, unlisten
DML buildersbuildDeleteQuery, buildInsertQuery, buildLimitOffset, buildMergeSql, buildSampleClause, buildSelectQuery, buildUpdateQuery, buildUpsertQuery, buildWhereClause, bulkInsert, escape, quoteTable, replaceReplacements
TypesbuildColumnSql, canonicalTypeSql, createEnumType, ensureEnumTypes, getDataTypeSql, mapNativeType, unsupportedType
DDL and schemaaddColumn, addIndex, attachPartition, buildCreateDatabaseSql, buildCreateIndexSql, buildCreateTableSql, changeColumn, changeOwner, createDatabaseSQL, createDomain, createExtension, createForeignDataWrapper, createForeignServer, createForeignTable, createFulltextIndex, createGINIndex, createGISTIndex, createIndex, createMaterializedView, createPartition, createPartitionedTable, createPolicy, createProcedure, createSavepointSQL, createSchema, createSequence, createSpatialIndex, createStoredProcedure, createTable, createTrigger, createVectorIndex, createView, detachPartition, dropDatabaseSQL, dropExtension, dropIndex, dropSchema, dropSequence, dropTable, enableRLS, refreshMaterializedView, removeColumn, removeIndex, renameColumn, renameTable
IntrospectionassertIndexOptions, assertNoReturning, describeTable, getDatabaseVersion, getExtensions, hasExtension, hasPolicy, hasSequence, listSchemas, listSequences, showAllSchemas, showTables, showViews
OtherbuildConnectParams, buildRangePartitionSql, columnNames, connectionFor, copyFrom, copyTo, currSequenceValue, formatDefault, mainSelectInsertIndex, nextSequenceValue, openConnection, pgAdvisoryLock, pgTryAdvisoryLock, rangeBound, refuse, releaseSavepointSQL, rollbackToSavepointSQL, toDriverValue, toWire

Escaping

Values compiled to text (not bound) are escaped with Teradata literal rules —
booleans are 1/0 (no BOOLEAN type), dates are typed TIMESTAMP '...'
literals in UTC, and bytes are a '...'XB hex literal:

d.escape("it's");                              // 'it''s'
d.escape(true);                                 // 1
d.escape(new Date(Date.UTC(2024, 4, 6, 7, 8, 9, 10)));
// TIMESTAMP '2024-05-06 07:08:09.010000'
d.escape(Buffer.from([0xde, 0xad]));            // 'DEAD'XB
d.escape([1, 2]);                               // throws: array literals

Type mapping

ORMTeradataNote
STRING(n)VARCHAR(n)
TEXT / CITEXTCLOBnot comparable/indexable; use STRING for searchable text
CHAR(n)CHAR(n)
TINYINTBYTEINT
SMALLINT / MEDIUMINT / INTEGERSMALLINT / INTEGER / INTEGER
BIGINTBIGINT
FLOAT / DOUBLE / REALFLOATTeradata's FLOAT is an 8-byte double
DECIMAL / NUMERICDECIMAL(p,s)p ≤ 38, else throws
BOOLEANBYTEINTno BOOLEAN type; 0/1
DATETIMESTAMP(n)precision defaults to 6
DATEONLYDATE
TIMETIME(n)precision defaults to 6
UUIDCHAR(36)
JSON / JSONBJSONnative JSON type (16.x+)
BLOBBLOB
ENUMVARCHAR(longest value)no enum types
GEOMETRYST_Geometry
'DATETIME' / 'BOOLEAN' (string types)TIMESTAMP / BYTEINTpseudo-type strings are rewritten

Types with no Teradata counterpart (ARRAY, HSTORE, ...) throw naming the
type rather than emit something Teradata rejects.

CREATE TABLE

buildCreateTableSql is pure and synchronous, and covers Teradata's table
kinds, distribution and partitioning:

d.buildCreateTableSql('sales', {
  id: { type: { key: 'BIGINT' }, allowNull: false },
  d: { type: { key: 'DATEONLY' }, allowNull: false },
}, {
  tableKind: 'SET',
  fallback: false,
  primaryIndex: ['id'],
  uniquePrimaryIndex: true,
  partitionByRange: {
    column: 'd', start: '2024-01-01', end: new Date(Date.UTC(2024, 11, 31)),
    each: { value: 1, unit: 'MONTH' }, noRange: true, unknown: true,
  },
});
CREATE SET TABLE "sales", NO FALLBACK ("id" BIGINT NOT NULL, "d" DATE NOT NULL)
  UNIQUE PRIMARY INDEX ("id")
  PARTITION BY RANGE_N("d" BETWEEN DATE '2024-01-01' AND DATE '2024-12-31'
    EACH INTERVAL '1' MONTH, NO RANGE, UNKNOWN)
  • SET vs MULTISET — defaults to MULTISET: a SET table silently
    discards duplicate rows, which is not what an ORM insert means.
  • PRIMARY INDEX (...) / UNIQUE PRIMARY INDEX / NO PRIMARY INDEX — the
    hash-distribution key across AMPs. NO PRIMARY INDEX requires MULTISET
    and cannot combine with a primary index.
  • PARTITION BY RANGE_N(...) — partitionByRange only; a raw
    partitionBy string is refused in favor of it.
  • VOLATILE / GLOBAL TEMPORARY — mutually exclusive; both default their
    ON COMMIT to PRESERVE ROWS (Teradata's own default, DELETE ROWS, would
    empty the table at the end of every auto-committed statement).
  • [NO] FALLBACK.
  • A PRIMARY KEY / UNIQUE column must be NOT NULL — UNIQUE on a
    nullable column throws rather than silently changing meaning.
  • Identity columns use GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1 NO CYCLE) instead of SERIAL.

createTable also runs each options.indexes entry through
buildCreateIndexSql and, if given, a COMMENT ON TABLE.

dropTable, showTables, describeTable

No DROP TABLE IF EXISTS — dropTable({ ifExists: true }) first checks
DBC.TablesV:

await d.dropTable('gone', { ifExists: true });
// SELECT 1 AS present FROM DBC.TablesV WHERE DatabaseName = DATABASE AND TableName = ?

showTables() / showViews() query DBC.TablesV by TableKind;
describeTable() reads DBC.ColumnsV and DBC.IndicesV.

Secondary indexes

Teradata puts the columns before ON:

d.buildCreateIndexSql('t', { name: 'ix', fields: ['a', 'b'], unique: true });
// CREATE UNIQUE INDEX "ix" ("a", "b") ON "t"

addIndex/createIndex refuse using (access methods), a non-empty where
(partial indexes), include columns, and concurrently — Teradata secondary
indexes have one kind and take their own locks.

Databases (Teradata's schemas)

Teradata has no schemas — a database/user is carved out of a parent's PERM
space:

d.buildCreateDatabaseSql({ name: 'app', from: 'dbc', permBytes: 1e9, spoolBytes: 5e8, fallback: false });
// CREATE DATABASE "app" FROM "dbc" AS PERMANENT = 1000000000, SPOOL = 500000000, NO FALLBACK

createSchema() throws and points at buildCreateDatabaseSql; dropSchema()
maps to DROP DATABASE (refusing cascade — run DELETE DATABASE first);
showAllSchemas()/listSchemas() read DBC.DatabasesV.

SELECT: TOP, QUALIFY, SAMPLE, LOCKING

Teradata has no LIMIT/OFFSET. A limit alone becomes SELECT TOP n; an
offset is expressed with QUALIFY ROW_NUMBER() OVER (ORDER BY ...), which
needs an order to be deterministic:

d.buildSelectQuery({ tableName: 't', limit: 10, order: [['id', 'ASC']] }).sql;
// SELECT TOP 10 * FROM "t" ORDER BY "id" ASC

d.buildSelectQuery({ tableName: 't', where: { a: 1 }, limit: 10, offset: 20, order: [['id', 'DESC']] }).sql;
// SELECT * FROM "t" WHERE "a" = $1 QUALIFY ROW_NUMBER() OVER (ORDER BY "id" DESC)
//   BETWEEN 21 AND 30 ORDER BY "id" DESC

d.buildSelectQuery({ tableName: 't', offset: 5, order: [['id', 'ASC']] }).sql;
// ... QUALIFY ROW_NUMBER() OVER (ORDER BY "id" ASC) > 5

An offset without an order, or a limit together with DISTINCT, throws by
name instead of reaching the parser (TOP cannot combine with DISTINCT, and
QUALIFY numbers rows before DISTINCT removes duplicates).

SAMPLE — Teradata's own row sampling, via teradataSample:

d.buildSelectQuery({ tableName: 't', teradataSample: { rows: 100 } }).sql;
// SELECT * FROM "t" SAMPLE 100

d.buildSelectQuery({
  tableName: 't',
  teradataSample: { fraction: 0.25, withReplacement: true, randomizedAllocation: true },
  order: [['id', 'ASC']],
}).sql;
// SELECT * FROM "t" SAMPLE WITH REPLACEMENT RANDOMIZED ALLOCATION 0.25 ORDER BY "id" ASC

The shared sample option (PostgreSQL TABLESAMPLE BERNOULLI) is translated
to a SAMPLE fraction:

d.buildSelectQuery({ tableName: 't', sample: { method: 'BERNOULLI', percent: 10 } }).sql;
// SELECT * FROM "t" SAMPLE 0.1

TABLESAMPLE SYSTEM (block sampling) and a REPEATABLE seed have no
Teradata equivalent and throw. SAMPLE and pagination (TOP/QUALIFY)
cannot be combined — sample in a derived table first, then page it — and
neither can combine with a UNION built by this dialect.

LOCKING ... FOR <level> — the request modifier for dirty reads, via
locking:

d.buildSelectQuery({ tableName: 't', locking: 'ACCESS', limit: 1 }).sql;
// LOCKING TABLE "t" FOR ACCESS SELECT TOP 1 * FROM "t"

locking must be one of ACCESS/READ/WRITE/EXCLUSIVE.
buildSelectQuery({ lock: true }) (PostgreSQL's FOR UPDATE/FOR SHARE)
throws — Teradata has no row-level lock clause.

Where-clause operators

The inherited PostgreSQL where-builder can emit operators Teradata does not
have (ILIKE, ->/->>/#>, @>/<@, &&, :: casts, ~/~*
regexes). buildWhereClause checks the built SQL (outside string literals and
quoted identifiers) and throws naming the operator:

d.buildWhereClause({ name: { [Op.iLike]: '%a%' } });
// throws: Teradata does not support ILIKE (case-insensitive LIKE)

In the default TERA session mode, plain LIKE on a NOT CASESPECIFIC
column is already case-insensitive, which is why ILIKE is unneeded rather
than reimplemented.

Writes

Insert — refuses RETURNING:

d.buildInsertQuery('t', { a: 1, b: new Literal('CURRENT_TIMESTAMP') });
// { sql: 'INSERT INTO "t" ("a", "b") VALUES ($1, CURRENT_TIMESTAMP)', values: [1] }

Upsert → MERGE — Teradata has no ON CONFLICT; buildUpsertQuery
(and buildInsertQuery({ upsert: true })) build a MERGE. conflictFields
is required (the ON condition must fix the target's primary index with
equality) and its columns are never updated:

d.buildUpsertQuery('t', { id: 1, name: 'x' }, { conflictFields: ['id'] });
MERGE INTO "t" AS tgt USING (SELECT $1 AS "id", $2 AS "name") AS src ON tgt."id" = src."id"
WHEN MATCHED THEN UPDATE SET "name" = src."name"
WHEN NOT MATCHED THEN INSERT ("id", "name") VALUES (src."id", src."name")

Update / delete — refuse UPDATE ... LIMIT and DELETE ... LIMIT
(narrow the WHERE clause instead); truncate maps to Teradata's fast-path
DELETE FROM t ALL:

d.buildDeleteQuery('t', {}, { truncate: true }).sql; // DELETE FROM "t" ALL

Bulk insert — one parameterized INSERT executed with a batch of row
arrays bound to ? markers in one round trip (Teradata has no multi-row
VALUES list); a Literal value in any row throws, since every row shares
one set of markers:

await d.bulkInsert('t', [{ a: 1, b: true }, { a: 2, b: false }]);
// executed: 'INSERT INTO "t" ("a", "b") VALUES (?, ?)', params: [[1, 1], [2, 0]]

Transactions

A dedicated connection with con.autocommit = false, finished with
con.commit()/con.rollback(). Only READ UNCOMMITTED and SERIALIZABLE
isolation levels are offered; anything else throws.

const tx = await d.startTransaction({ isolationLevel: 'READ UNCOMMITTED' });
// SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

Teradata has no savepoints — createSavepointSQL/releaseSavepointSQL/
rollbackToSavepointSQL all throw.

ALTER TABLE

addColumn, removeColumn, renameColumn (ALTER TABLE ... RENAME x TO y), and renameTable (RENAME TABLE old TO new) work as expected.
changeColumn throws: Teradata cannot retype a column in general — ALTER TABLE ... ADD on an existing column can only widen a VARCHAR, change a
title/format, or toggle a few attributes, not change the type — so the
suggested path is add a new column, copy the data, drop the old one, rename.

Refused, by name

CallWhy
createSchemaTeradata namespaces are databases carved from a parent's PERM space; use buildCreateDatabaseSql.
dropSchema({ cascade: true })No CASCADE; run DELETE DATABASE first.
createTable({ ifNotExists: true })No CREATE TABLE IF NOT EXISTS; check DBC.TablesV (or catch error 3803) first.
dropTable({ cascade: true })No CASCADE; drop dependent views and join indexes first.
changeColumnTeradata cannot retype a column via ALTER TABLE.
buildSelectQuery({ lock: true })No FOR UPDATE/FOR SHARE; use locking: 'WRITE' (or 'ACCESS').
buildSelectQuery with offset and no orderQUALIFY ROW_NUMBER() pagination needs a deterministic order.
buildSelectQuery with limit + distinctTOP cannot combine with DISTINCT.
buildSelectQuery with TOP/QUALIFY + SAMPLESample in a derived table first, then page it.
buildInsertQuery/buildUpdateQuery/buildDeleteQuery({ returning: true })No RETURNING; read affected rows back with a SELECT.
buildUpdateQuery/buildDeleteQuery({ limit })No UPDATE/DELETE ... LIMIT; narrow the WHERE clause.
bulkInsert with a Literal valueEvery row in the batch shares one set of ? markers.
createSavepointSQL/releaseSavepointSQL/rollbackToSavepointSQLNo savepoints; a transaction commits or rolls back as a whole.
startTransaction with an isolation level other than READ UNCOMMITTED/SERIALIZABLETeradata offers only those two.
createDatabaseSQLUse buildCreateDatabaseSql({ name, from, permBytes }).
createSequence/dropSequence/nextSequenceValue/currSequenceValueNo sequences; use an identity column (autoIncrement: true).
createTriggerTeradata triggers carry their body inline; not generated here.
createStoredProcedure/createProcedureTeradata SPL is not generated here.
createMaterializedView/refreshMaterializedViewTeradata's analogue is a join index (CREATE JOIN INDEX), maintained automatically.
createExtension/dropExtensionNo CREATE/DROP EXTENSION.
createEnumTypeAn ENUM column is stored as VARCHAR; add a CHECK constraint instead.
createDomainDeclare the type and constraint on each column.
createPolicy/enableRLSNo row-level security; restrict rows with views and GRANTs.
listen/unlisten/notifyNo LISTEN/NOTIFY; poll a table or use QueryGrid / an external bus.
pgAdvisoryLock/pgTryAdvisoryLockNo advisory locks; use a LOCKING request modifier.
copyFrom/copyToNo COPY; use bulkInsert, or Teradata FastLoad/FastExport/TPT.
createPartitionedTable/createPartition/attachPartition/detachPartitionA partitioned Teradata table is one table; partitions come from PARTITION BY RANGE_N, passed via partitionByRange.
createGINIndex/createGISTIndex/createVectorIndex/createFulltextIndexTeradata has hash-based secondary and join indexes only; no GIN/GiST/vector/full-text machinery.
createSpatialIndexST_Geometry columns are indexed by Teradata itself.
createForeignDataWrapper/createForeignServer/createForeignTableFederated access is Teradata QueryGrid, configured outside SQL DDL.
changeOwnerOwnership follows the database hierarchy; move space with GIVE.
array bind values / array literals (escape, driver binding)Teradata ARRAY columns are user-defined types; bind or escape the elements individually.
non-finite numbers (escape)Store NULL or a sentinel instead.
unmapped DataTypes (ARRAY, HSTORE, ...)No built-in Teradata equivalent; declare the column with an explicit type string.
DECIMAL/NUMERIC with precision > 38The maximum DECIMAL precision is 38.

Caveats / not-yet-verified

  • All SQL above is asserted as strings in tests/dialects/teradata.test.ts
    against a mocked teradatasql module (jest.mock('teradatasql', ..., { virtual: true })); nothing here has been run against a live Vantage
    instance in this suite.
  • queryStream has no server-side cursor to lean on — teradatasql exposes
    only fetchall/fetchone on an executed request — so it fetches the full
    result and then emits rows one by one; memory use is the whole result set.
  • Triggers and stored procedures exist on Teradata but use their own syntax
    (inline trigger bodies, Teradata SPL); the inherited PostgreSQL/PL-pgSQL
    builders would emit SQL Teradata cannot parse, so both throw rather than
    guess.
  • hasSequence() and getExtensions() answer false/[] without a server
    round trip, since Teradata has neither.

Capabilities

Computed from the code — capabilitiesOf() (src/transaction-support.ts),
whereSupportOf() (src/query-builders/expression-render.ts),
sqlObjectCapabilitiesOf() (src/sql-objects/capabilities.ts) and the
builders — by the scratch test described in the
capability matrix.

Capabilityteradata
Transactions atomicyes
Savepointsno — a nested transaction() throws
Isolationup to SERIALIZABLE
Transaction modesread-only yes; deferrable yes; constraint deferral yes
RETURNINGrefused — Teradata does not support RETURNING. Read the affected rows back with a SELECT (inside the same transaction if it matters).
UpsertMERGE INTO … WHEN MATCHED / WHEN NOT MATCHED
JSON columnJSON (JSONB → JSON)
Vector columnrefused — Teradata does not support the column type 'VECTOR'. Store the vector as JSON or a VARBYTE.
Array columnrefused — Teradata does not support the column type 'ARRAY'. Store the value as JSON, or create an ARRAY or structured UDT and use its name as a raw type.
WHERE builder35 operator keys; $and/$or/$not; $exists: no; $in subquery: no; expression operands: no
SQL objectsfamily unknown: triggers no; procedures no; functions no; materialized views no; sequences no; enums check; RLS no
StreamingqueryStream() present; LISTEN present; createExtension() present

Related reading

  • All dialects
  • PostgreSQL dialect — everything inherited
  • Teradata Node.js driver
  • Teradata SQL documentation — SQL Data Definition Language / SQL Data Manipulation Language
Modified at 2026-10-04 00:40:16
Previous
Azure Synapse Analytics (dedicated SQL pool)
Next
TiDB Dialect
Built with