Overview#
YugabyteDB is a distributed SQL database whose YSQL API
is forked from the PostgreSQL source. As a result it speaks the PostgreSQL wire
protocol and is largely SQL-compatible with PostgreSQL. This ORM implements the
dialect by extending the Postgres dialect rather than reimplementing it:| Property | Value |
|---|
| Dialect name | yugabytedb |
| Extends | PostgresDialect (postgres) |
| Driver | pg |
| Cloud SDK | none |
| Default port | 5433 |
| Local runtime | prorm db up --dialect yugabytedb (yugabytedb/yugabyte:2.20.1.0-b97) |
YugabyteDBDialect extends PostgresDialect — connection handling, parameter
binding, transactions, and most query building are inherited unchanged.
It reuses the same pg driver (library === 'pg', inherited from
PostgresDialect).
The dialect identifies itself as name === 'yugabytedb'.
The default port is 5433 (YugabyteDB's YSQL server port), not Postgres's
5432. An explicit port in your config still wins.
On top of the inherited Postgres behavior, this dialect layers YugabyteDB's
distributed-table DDL: tablet splitting, colocation, hash/range primary keys,
and tablegroups.Source: src/dialects/yugabytedb/index.ts. Base: src/dialects/postgres/index.ts.Quick start#
Install#
$ npm install ts-prorm-orm pg
$ pnpm add ts-prorm-orm pg
$ yarn add ts-prorm-orm pg
$ bun add ts-prorm-orm pg
pg is the same driver the postgres dialect uses. pg-copy-streams is optional: only the features that need it load it.Connect#
import { Prorm } from 'ts-prorm-orm';
export const db = new Prorm({
dialect: 'yugabytedb',
host: 'localhost',
database: 'yugabyte',
username: 'yugabyte',
password: process.env.DB_PASSWORD,
});
import { Prorm } from 'ts-prorm-orm';
export const db = new Prorm({
dialect: 'yugabytedb',
url: 'yugabytedb://yugabyte:yugabyte@localhost:5433/yugabyte',
});
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) },
meta: { type: DataTypes.JSONB() },
});
await db.sync(); // CREATE TABLE — see Generated SQL below
meta is JSONB, which the containment query below needs.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.Create table#
db.sync() for the model in the Quick start:CREATE TABLE
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 } });
Upsert#
await User.upsert({ id: 1, email: 'ada@example.com', name: 'Ada Lovelace' });
upsert() also reads the row by primary key before and after the write, to return the instance.await User.findAll({
where: { name: { [Op.like]: 'A%' } },
order: [['id', 'ASC']],
limit: 20,
offset: 40,
});
JSON#
Containment on the meta column:import { Op } from 'ts-prorm-orm';
await User.findAll({ where: { meta: { [Op.contains]: { plan: 'pro' } } } });
Transaction with a savepoint#
await db.transaction(async (t) => {
await User.create({ email: 'grace@example.com', name: 'Grace' }, { transaction: t });
// A nested transaction is a SAVEPOINT; its failure undoes only its own work.
await db
.transaction(async (sp) => {
await User.destroy({ where: { id: 1 }, transaction: sp });
throw new Error('keep the row');
}, { transaction: t })
.catch(() => {});
});
Skip locked rows (SKIP LOCKED)#
A worker that claims rows from a queue table should pass over rows another transaction holds rather than wait for them. lock with skipLocked inside a transaction:await db.transaction(async (t) => {
await User.findAll({ where: { name: 'Ada' }, lock: { level: 'UPDATE', skipLocked: true }, transaction: t });
});
Type mapping for the portable descriptors: STRING → VARCHAR(255), auto-increment INTEGER → SERIAL, BOOLEAN → BOOLEAN, DATE → TIMESTAMP, UUID → UUID, JSON → JSON. The type comparison lines the major engines up side by side.Connection#
import { Prorm } from 'ts-prorm-orm';
const orm = new Prorm({
dialect: 'yugabytedb',
host: 'localhost',
// port defaults to 5433; override only if your YSQL server uses another port
database: 'mydb',
username: 'yugabyte',
password: 'yugabyte',
});
await orm.connect();
Connection options are identical to the Postgres dialect
(YugabyteDBDialectOptions extends PostgresDialectOptions); the only difference
is the 5433 port default applied in the constructor.You can also construct the dialect directly:import { YugabyteDBDialect, createYugabyteDBDialect } from 'prorm/dialects/yugabytedb';
const dialect = new YugabyteDBDialect({ database: 'mydb', username: 'yugabyte' });
// or
const dialect2 = createYugabyteDBDialect({ database: 'mydb', username: 'yugabyte' });
What differs from Postgres#
YugabyteDBDialect extends PostgresDialect (postgres) and
overrides 18 of its methods (Object.getOwnPropertyNames(YugabyteDBDialect.prototype),
computed by the scratch test); everything else is inherited unchanged.| Area | Overridden |
|---|
| Connection and execution | query |
| DML builders | formatDefaultValue |
| Types | buildColumnDefinitionSql |
| DDL and schema | addIndex, buildColumnReferencesSql, buildCreateTableGroupSQL, buildCreateTableSQL, createTable, createTableGroup, dropTableGroup |
| Introspection | isRetryableError |
| Other | applyPostCreateTableSteps, backoffDelay, buildPrimaryKeyClause, buildYbConstraintSql, buildYugabyteTableClauses, quoteSplitValue, runTransaction |
YugabyteDB-specific features#
These are surfaced through an extended options type,
YugabyteTableOptions extends TableOptions, accepted by
buildCreateTableSQL() (synchronous, connection-free) and createTable().
createTable() only takes the custom DDL path when at least one YugabyteDB
option is present (splitIntoTablets, splitAtValues, colocated,
colocation, tablegroup, or a table-level primaryKey); otherwise it falls
back to the inherited Postgres createTable().Identifiers are double-quoted (inherited Postgres escapeId). All SQL below is
the exact output of buildCreateTableSQL() / buildCreateTableGroupSQL().SPLIT INTO n TABLETS#
Presplit a hash-sharded table into n tablets with splitIntoTablets:dialect.buildCreateTableSQL(
'users',
{ id: { type: 'INTEGER', primaryKey: true } },
{ splitIntoTablets: 8 },
);
SPLIT AT VALUES#
Presplit a range-sharded table at explicit boundaries with splitAtValues.
Each inner array is one split point's column value(s); numbers pass through,
strings are single-quoted and escaped:dialect.buildCreateTableSQL(
'metrics',
{ ts: { type: 'TIMESTAMP' }, v: { type: 'INTEGER' } },
{
primaryKey: [{ name: 'ts', order: 'ASC' }],
splitAtValues: [[1000], [2000]],
},
);
Colocated / colocation tables#
Small tables can be co-located onto the database's colocation tablet to avoid
the overhead of a tablet-per-table. Use colocated (older keyword) or
colocation (newer keyword). If both are supplied, colocation wins.dialect.buildCreateTableSQL('sessions', { id: { type: 'INTEGER' } }, { colocated: true });
dialect.buildCreateTableSQL('config', { id: { type: 'INTEGER' } }, { colocation: true });
Both accept false as well, emitting WITH (colocated = false) /
WITH (colocation = false).HASH-sharded / range-sharded primary keys#
Unlike Postgres, a YugabyteDB primary-key column carries a sharding/sort
directive: HASH (hash-sharded — meaningful on leading PK columns), or ASC /
DESC (range-sharded). Supply a table-level primaryKey as an array of
{ name, order? } columns:dialect.buildCreateTableSQL(
'events',
{ id: { type: 'INTEGER' }, created_at: { type: 'TIMESTAMP' } },
{ primaryKey: [{ name: 'id', order: 'HASH' }, { name: 'created_at', order: 'DESC' }] },
);
The order is optional; a column with no order is emitted with no
directive.
When a table-level primaryKey directive is present, any column-level
primaryKey: true flags are stripped so the statement never emits two
PRIMARY KEY clauses. A PRIMARY KEY constraint passed via
options.constraints is likewise skipped when a PK clause was already
produced.
If no table-level primaryKey is given, columns flagged with column-level
primaryKey: true are collected into a table-level PRIMARY KEY (...) clause
with no sharding directive (as seen in the SPLIT INTO example above).
Tablegroups#
CREATE TABLEGROUP groups tables that should share tablets.
buildCreateTableGroupSQL() builds the statement synchronously;
createTableGroup() runs it. A table joins a tablegroup via the tablegroup
option.dialect.buildCreateTableGroupSQL('tg1');
// CREATE TABLEGROUP "tg1"
dialect.buildCreateTableGroupSQL('tg1', { ifNotExists: true, owner: 'app' });
// CREATE TABLEGROUP IF NOT EXISTS "tg1" OWNER "app"
dialect.buildCreateTableSQL('lookup', { id: { type: 'INTEGER', primaryKey: true } }, { tablegroup: 'tg1' });
// CREATE TABLE "lookup" ("id" INTEGER, PRIMARY KEY ("id")) TABLEGROUP "tg1"
await dialect.createTableGroup('tg1', { ifNotExists: true, owner: 'app' });
await dialect.dropTableGroup('tg1', { ifExists: true }); // DROP TABLEGROUP IF EXISTS "tg1"
Clause ordering#
When several YugabyteDB clauses apply to one CREATE TABLE, they are emitted in
this fixed order after the column list: colocation WITH (...), then
TABLEGROUP, then SPLIT INTO ... TABLETS, then SPLIT AT VALUES (...).Inherited Postgres behavior#
Everything not listed above comes straight from PostgresDialect, unchanged:CRUD — INSERT / SELECT / UPDATE / DELETE query building, parameter
binding ($1, $2, …), and result handling.
Upsert — buildUpsertQuery() emits
INSERT INTO ... VALUES (...) ON CONFLICT (...) DO UPDATE SET col = excluded.col.
conflictFields is required (PostgreSQL cannot infer the conflict target),
and an optional RETURNING clause is supported. For example, with
conflictFields: ['id'] the generated SQL is
... ON CONFLICT ("id") DO UPDATE SET ....
DDL — the non-YugabyteDB createTable() path, dropTable(), index
creation, comments, unique keys, and sequence start values are inherited.
When a YugabyteDB-specific option forces the custom DDL path, the follow-up
statements (unique keys, table comment, initialAutoIncrement sequence start,
and secondary indexes) are re-emitted to match the base dialect's behavior.
Identifier quoting — double quotes ("col"), inherited from the Postgres
escapeId ("foo" with embedded " doubled to "").
Auto-increment — an autoIncrement INTEGER column is emitted as SERIAL,
matching the Postgres/CockroachDB convention.
Type mapping#
Column types are resolved by the inherited Postgres getDataTypeSql(). The main
ORM type → SQL mappings:| ORM type | SQL type |
|---|
STRING | VARCHAR(length) (default VARCHAR(255)) |
CHAR | CHAR(length) (default CHAR(1)) |
TEXT | TEXT (or VARCHAR(length) for a sized value) |
INTEGER | INTEGER (SERIAL when autoIncrement) |
BIGINT | BIGINT (BIGSERIAL when autoIncrement) |
FLOAT | REAL |
DOUBLE | DOUBLE PRECISION |
DECIMAL | DECIMAL(precision, scale) (default 10,0) |
BOOLEAN | BOOLEAN |
DATE | TIMESTAMP (or TIMESTAMP(precision)) |
DATEONLY | DATE |
TIME | TIME (or TIME(precision)) |
BLOB | BYTEA |
ENUM | ENUM('a','b',...) |
JSON | JSON |
JSONB | JSONB |
UUID | UUID |
HSTORE | HSTORE |
VECTOR | VECTOR(dimensions) (requires pgvector) |
INET | INET |
CIDR | CIDR |
MACADDR | MACADDR |
ARRAY | <baseType>[] |
Additional notes from the base dialect:The cross-dialect pseudo-type DATETIME (used by the model-sync layer for
createdAt / updatedAt / deletedAt) is normalized to TIMESTAMP.
A raw string type is passed through as-is.
An unknown/object type with no matching key falls back to VARCHAR(255).
Caveats#
CREATE INDEX ... CONCURRENTLY#
addIndex() is overridden to handle YugabyteDB's CONCURRENTLY divergence.
In YugabyteDB, index backfill is already online by default, and CONCURRENTLY
carries different semantics/restrictions — notably it cannot run inside a
transaction block. Mirroring the CockroachDB dialect's approach, a requested
concurrently flag is ignored (with a console.warn) rather than emitted,
so the generated SQL stays safe to run in the common transactional case. All
other index-building behavior is inherited from the Postgres dialect unchanged.System catalogs#
YugabyteDB emulates the PostgreSQL pg_catalog for compatibility, but a handful
of columns/values reflect its distributed storage rather than a single-node
heap. Any inherited Postgres feature that introspects pg_catalog internals may
therefore behave slightly differently against a live YugabyteDB cluster.Verification status#
SQL generation is verified. The CREATE TABLE / CREATE TABLEGROUP
grammar (tablet splitting, colocation, hash/range primary keys, tablegroups)
is covered by connection-free unit tests in
tests/dialects/yugabytedb.test.ts, and every SQL snippet in this document is
the exact output of the corresponding builder method.
Runtime behavior is not verified here. There is no CRUD/integration test
against a live YugabyteDB cluster (no yugabytedb-crud.test.ts exists).
Executing these statements against a real cluster — and the inherited Postgres
runtime behavior over the YSQL wire — has not been exercised in this
repository's test suite. Validate against a live YugabyteDB deployment before
relying on runtime semantics.
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.| Capability | yugabytedb |
|---|
| Transactions atomic | yes |
| Savepoints | yes |
| Isolation | up to SERIALIZABLE |
| Transaction modes | read-only yes; deferrable yes; constraint deferral yes |
| RETURNING | RETURNING on INSERT |
| Upsert | INSERT … ON CONFLICT (…) DO UPDATE |
| JSON column | JSON (JSONB → JSONB) |
| Vector column | VECTOR(3) |
| Array column | INTEGER[] |
| WHERE builder | 62 operator keys; $and/$or/$not; $exists: yes; $in subquery: yes; expression operands: yes |
| SQL objects | family unknown: triggers no; procedures no; functions no; materialized views no; sequences no; enums check; RLS no |
| Streaming | queryStream() present; LISTEN present; createExtension() present |
Querying — how a FindOptions becomes SQL Modified at 2026-10-04 00:40:16