# JSON-native TypeScript ORM for Bun and Node > A TypeScript ORM whose queries are plain JSON values, typed down to every field, with no codegen and one API across every SQL database, MongoDB and runtime. Source: https://uql-orm.dev/ ## Every key is type-checked A query is a plain object: no builder to chain, no operators to import. The compiler checks every key at any depth, and the operators (`$in`, `$gte`, `$or`, …) are MongoDB’s. The red lines in the editor above are real `tsc` errors against the published types: a misspelled field, the same typo inside a populated relation, and an operator the column’s type does not allow. Entities are plain classes with [standard decorators](https://uql-orm.dev/entities/basic.md), or plain data with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) when you want no decorators. Both are typed the same, they mix in one project, and neither needs codegen. Checking reaches into [JSON](https://uql-orm.dev/querying/json.md) dot-paths too. ## The same query, from browser to backend A query is data, so the browser can send it over HTTP, typed the same as on the server: Browser: ```ts import { createClientQuerier, httpTransport } from 'uql-orm/browser'; const client = createClientQuerier(httpTransport('/api/v1')); const users = await client.findMany(User, { $select: { id: true, email: true }, $where: { email: { $endsWith: '@uql-orm.dev' } }, }); ``` entities.ts: ```ts import { v7 as uuidv7 } from 'uuid'; import { f, Entity, Field } from 'uql-orm'; @Entity() export class User { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.string().unique()) email!: string; } ``` defineEntity.ts: ```ts import { v7 as uuidv7 } from 'uuid'; import { f, defineEntity } from 'uql-orm'; export const User = defineEntity({ name: 'User', fields: { id: f.uuid().id().onInsert(uuidv7), email: f.string().unique(), }, }); export interface User extends InstanceType {} ``` uql.config.ts: ```ts import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, }); ``` Server: ```ts import { createApi, toFetchHandler } from 'uql-orm/http'; export const handler = toFetchHandler(createApi({ pool, include: [User] })); ``` The API runs each write in a transaction, takes what each definition’s `wire` lets a client read and write, and mounts on Hono, Elysia, Next.js, Express, Bun or Workers, or inside a tRPC procedure. See the [API](https://uql-orm.dev/http.md) and the [client](https://uql-orm.dev/browser.md). ## The rest, briefly - Runs on PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, SQL Server, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun SQL and MongoDB, on Node 22.18+, Bun, [Workers](https://uql-orm.dev/cloudflare-d1.md), [Lambda and Vercel](https://uql-orm.dev/serverless.md) and [the browser](https://uql-orm.dev/browser.md). ESM only. - Zero runtime dependencies; `uql-orm/postgres` is about 49 kB gzipped. - [Migrations](https://uql-orm.dev/migrations.md) with drift checks, [vector search](https://uql-orm.dev/ai-semantic-search.md), [raw SQL](https://uql-orm.dev/querying/raw-sql.md), [multi-tenancy](https://uql-orm.dev/multi-tenancy.md), [soft delete](https://uql-orm.dev/entities/soft-delete.md), [triggers](https://uql-orm.dev/entities/triggers.md) and [streaming](https://uql-orm.dev/querying/streaming.md) in the same package. - The fastest any ORM we measured on a PostgreSQL round trip, on Bun and Node (open-source [benchmark](https://uql-orm.dev/benchmark.md)). Compare it [feature by feature](https://uql-orm.dev/comparison.md) and [on type safety](https://uql-orm.dev/type-safety.md). # Quick Start > Install UQL, define an entity, and run your first query. Source: https://uql-orm.dev/getting-started [UQL](https://uql-orm.dev/index.md) is a TypeScript ORM whose queries are plain, typed JSON objects. Entities are plain classes with [decorators](https://uql-orm.dev/entities/basic.md), or declared as data with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md), with no code generation. This page takes you from install to a first query. > **Using a coding agent?** > > [Paste the setup prompt](https://uql-orm.dev/ai-agents.md) and it runs these steps in your project, for your runtime and database. ## 1. Install npm: ```sh npm install uql-orm pg # or mysql2, better-sqlite3, mongodb, etc. npm install -D tsx # Node only: the CLI loads uql.config.ts through it ``` bun: ```sh bun add uql-orm # bun:sql and bun:sqlite need no driver ``` pnpm: ```sh pnpm add uql-orm pg # or mysql2, better-sqlite3, mongodb, etc. pnpm add -D tsx # Node only: the CLI loads uql.config.ts through it ``` ### Requirements UQL runs on Node 22.18+, Bun and edge runtimes such as Cloudflare Workers, with TypeScript 5.7+. It is ESM only. Below are the three `tsconfig.json` settings that matter for UQL: ```json title="tsconfig.json" { "compilerOptions": { "module": "nodenext", // or "preserve": the resolver must read `exports` "target": "es2024", // any dated target from es2022 (`esnext` leaves decorators untransformed) "lib": ["es2024", "esnext.disposable"] // or just ["esnext"] } } ``` Behind a bundler, use `"module": "preserve"` or `"moduleResolution": "bundler"`. Vite’s TypeScript template pins `lib` to `ES2023`, so add `esnext`. Next.js compiles only legacy decorators, so add [a Babel config](https://uql-orm.dev/nextjs.md#decorators) or declare your entities with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md), which needs no decorators. If Node runs your compiled output, set `"type": "module"` in `package.json`. ## 2. Define an entity and a pool Decorators: ```ts title="entities.ts" import { f, Entity, Field } from 'uql-orm'; @Entity() export class User { @Field( f .uuid() .id() .onInsert(() => crypto.randomUUID()), ) id?: string; @Field(f.string().unique()) email!: string; @Field(f.string().nullable()) name?: string | null; } ``` defineEntity: ```ts title="entities.ts" import { f, defineEntity } from 'uql-orm'; export const User = defineEntity({ name: 'User', fields: { id: f .uuid() .id() .onInsert(() => crypto.randomUUID()), email: f.string().unique(), name: f.string().nullable(), }, }); export interface User extends InstanceType {} ``` Both export the same `User`, so the next files work with either. ```ts title="uql.config.ts" import type { Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; import { User } from './entities.js'; export const pool = new PgQuerierPool({ host: 'localhost', user: 'postgres', password: 'password', database: 'uql_app', }); export default { pool, entities: [User] } satisfies Config; ``` Create the pool once per process and import it everywhere. It connects on the first query. Other databases and pool sizing are in [Pool](https://uql-orm.dev/pool.md). ## 3. Create the table ```sh npx uql-migrate sync ``` `sync` compares the `entities` in `uql.config.ts` with the database and creates what is missing. Add `--dry-run` to print the DDL instead. Once the data matters, switch to [`generate:entities`](https://uql-orm.dev/migrations.md#from-entities-to-the-database), which writes the diff to a migration you review. For tables that already exist, [`generate:from-db`](https://uql-orm.dev/migrations.md#from-a-database-to-entities) writes the entities. ## 4. Query ```ts title="app.ts" import { pool } from './uql.config.js'; import { User } from './entities.js'; await pool.insertMany(User, [ { email: 'ada@uql-orm.dev', name: 'Ada' }, { email: 'grace@example.com', name: 'Grace' }, ]); const users = await pool.findMany(User, { $select: { id: true, name: true }, $where: { email: { $endsWith: '@uql-orm.dev' } }, }); // [{ id: '...', name: 'Ada' }] ``` Each pool call takes a connection and releases it. To share one connection across calls, use `pool.withQuerier`, or [`pool.transaction`](https://uql-orm.dev/querying/transactions.md) to commit them together. See [pool vs. querier](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx). ## Next steps - [Entities](https://uql-orm.dev/entities/basic.md) and [relations](https://uql-orm.dev/entities/relations.md) - [Querying](https://uql-orm.dev/querying/querier.md) and [transactions](https://uql-orm.dev/querying/transactions.md) - [Migrations](https://uql-orm.dev/migrations.md) and drift detection - [Examples](https://github.com/rogerpadilla/uql/tree/main/examples): runnable apps on Node, Bun, Next.js and Cloudflare D1 # Switching to UQL > Scaffold entities from the database you already run, translate the queries you already write, and move a production system over in phases. Source: https://uql-orm.dev/switching-to-uql UQL runs in the same process as Drizzle, MikroORM, Mongoose, Prisma or TypeORM, so you can move one endpoint at a time: [scaffold entities](#step-1-scaffold-entities-from-the-database-you-have), [run both ORMs](#step-2-run-it-beside-your-current-orm), [translate your queries](#translating-what-you-already-write), then [move traffic in phases](#migrating-in-phases). ## Step 1: Scaffold entities from the database you have The CLI writes `@Entity` classes from your tables, with relations from the foreign keys: ```bash npx uql-migrate generate:from-db --output ./src/entities ``` It reads the pool from `uql.config.ts`. For `snake_case` columns and `camelCase` code, set a [naming strategy](https://uql-orm.dev/naming-strategy.md) there; it applies to queries and DDL alike: ```ts title="uql.config.ts" import { SnakeCaseNamingStrategy, type Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool( { connectionString: process.env.DATABASE_URL }, { namingStrategy: new SnakeCaseNamingStrategy() }, ); export default { pool, migrationsPath: './migrations' } satisfies Config; ``` Then run `npx uql-migrate drift:check`, and keep it in CI. A junction table without foreign keys arrives as a plain entity. From here on, edit the classes and let [`generate:entities`](https://uql-orm.dev/migrations.md#from-entities-to-the-database) write each migration. See [scaffolding](https://uql-orm.dev/migrations.md#from-a-database-to-entities) and [drift detection](https://uql-orm.dev/migrations.md#drift-detection). ## Step 2: Run it beside your current ORM The two ORMs share nothing but the database. Lower each pool’s max so both fit its connection limit. A transaction cannot span both, so move a whole unit of work at once. Each [pool call](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx) takes its own connection, as in Prisma and TypeORM. `pool.withQuerier` and `pool.transaction` share one across statements. > **Caution** > > UQL is ESM only: use `import`, and set `"type": "module"` in `package.json` if Node runs your compiled output. See [Requirements](https://uql-orm.dev/getting-started.md#requirements). ## The shift in mental model Each ORM has one habit that does not carry over. The rest is renaming. From **Prisma**, there is no schema file and no `prisma generate`. The entity is the schema: an `@Entity` class with [decorators](https://uql-orm.dev/entities/basic.md), or a [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) call. Either is type-checked against its properties. From **Drizzle**, conditions are keys in an object instead of imported functions (`eq()`, `and()`), so a query is data that can travel over the network. From **MikroORM or TypeORM**, nothing is tracked and nothing flushes. A write happens only where you call one: ```ts await pool.updateOneById(User, id, { name: 'New Name' }); // instead of user.name = ...; em.flush() ``` From **Mongoose**, the [operators](https://uql-orm.dev/querying/comparison-operators.md) are the same (`$gte`, `$in`, `$regex`, `$elemMatch`, `$or`), and so are the [update operators](https://uql-orm.dev/querying/json.md#updating) on a JSON column (`$set` with dotted paths, `$unset`, `$push`, `$pull`, `$addToSet`). A document becomes an `@Entity` class. The same query runs on MongoDB and every SQL engine, so you can [move off Mongo](https://uql-orm.dev/mongodb.md#moving-to-sql) one collection at a time, comparing both stores’ answers before you switch, as [this walkthrough](https://uql-orm.dev/blog/mongodb-to-postgresql.md) does. ## Translating what you already write ### Method and operator equivalents Every method below exists on the pool and on a [querier](https://uql-orm.dev/querying/querier.md), with the same arguments. Prisma: | Prisma | UQL | | - | - | | `findMany({ where, select, orderBy, take, skip })` | `findMany(User, { $where, $select, $sort, $limit, $skip })` | | `findFirst({ where })` | `findOne(User, { $where })` | | `findUnique({ where: { id } })` | `findOneById(User, id)` | | `count({ where })` | `count(User, { $where })` | | `groupBy` / `aggregate` | [`aggregate(User, { $group, $select, $having })`](https://uql-orm.dev/querying/aggregate.md) | | `create({ data })` | `insertOne(User, data)` returns the id; pass `{ returning }` for the row | | `createMany({ data })` | `insertMany(User, data)` returns an id per row | | `update({ where: { id }, data })` | `updateOneById(User, id, data)` | | `updateMany({ where, data })` | `updateMany(User, { $where }, data)` | | `upsert({ where, create, update })` | `upsertOne(User, { $conflict, $update? }, data)` | | `delete` / `deleteMany` | `deleteOneById` / `deleteMany` | | `include` / nested `select` | [`$populate`](https://uql-orm.dev/querying/relations.md) | | `$transaction(fn)` | [`pool.transaction(fn)`](https://uql-orm.dev/querying/transactions.md) | | `$queryRaw` / `$executeRaw` | [``all(sql`...`)``](https://uql-orm.dev/querying/raw-sql.md) / ``run(sql`...`)`` | | `{ contains: 'x' }` | `{ $includes: 'x' }`, or `$iincludes` for `mode: 'insensitive'` | | `{ startsWith: 'x' }` | `{ $startsWith: 'x' }` / `{ $istartsWith: 'x' }` | | `{ notIn: [...] }` | `{ $nin: [...] }` | | `{ field: null }` | the same, or `{ $isNull: true }` | | `AND` / `OR` / `NOT` | [`$and` / `$or` / `$not`](https://uql-orm.dev/querying/logical-operators.md) | Drizzle: | Drizzle | UQL | | - | - | | `db.select().from(users).where(...)` | `findMany(User, { $where })` | | `db.select({ id: users.id })` | `$select: { id: true }` | | `db.query.users.findMany({ with: { posts: true } })` | `$populate: { posts: true }` | | `.orderBy(desc(users.createdAt))` | `$sort: { createdAt: 'desc' }` | | `.limit(n)` / `.offset(n)` | `$limit: n` / `$skip: n` | | `db.$count(users, ...)` | `count(User, { $where })` | | `.groupBy().having()` | [`aggregate(User, { $group, $select, $having })`](https://uql-orm.dev/querying/aggregate.md) | | `db.insert(users).values(v).returning()` | `insertOne(User, v, { returning: true })` | | `db.update(users).set(v).where(...)` | `updateMany(User, { $where }, v)` | | `db.delete(users).where(...)` | `deleteMany(User, { $where })` | | `.onConflictDoUpdate({ target, set, setWhere })` | `upsertOne(User, { $conflict, $where, $update? }, data)` | | `db.transaction(fn)` | [`pool.transaction(fn)`](https://uql-orm.dev/querying/transactions.md) | | ``db.execute(sql`...`)`` | [``all(sql`...`)``](https://uql-orm.dev/querying/raw-sql.md) / ``run(sql`...`)`` | | `and(...)` / `or(...)` / `not(...)` | [`$and` / `$or` / `$not`](https://uql-orm.dev/querying/logical-operators.md); `$and` is implicit between keys | | `like` / `ilike` | `{ $like }` / `{ $ilike }`, or `$includes` / `$iincludes` to skip the wildcards | | `inArray` / `notInArray` | `{ $in }` / `{ $nin }` | | `isNull` / `isNotNull` | `{ $isNull: true }` / `{ $isNotNull: true }` | TypeORM: | TypeORM | UQL | | - | - | | `find(User, { where, select, order, take, skip })` | `findMany(User, { $where, $select, $sort, $limit, $skip })` | | `findOneBy(where)` / `findOneBy({ id })` | `findOne(User, { $where })` / `findOneById(User, id)` | | `count` / `countBy` | `count(User, { $where })` | | `relations: ['posts']`, `leftJoinAndSelect` | [`$populate`](https://uql-orm.dev/querying/relations.md), with `$required: true` for an inner join | | `createQueryBuilder().groupBy().having()` | [`aggregate(User, { $group, $select, $having })`](https://uql-orm.dev/querying/aggregate.md) | | `insert(User, data)` | `insertOne(User, data)` / `insertMany(User, data)` | | `save(entity)` | `saveOne(User, data)`, upserts when the key is set | | `update(User, id, data)` | `updateOneById(User, id, data)` | | `delete(User, id)` | `deleteOneById(User, id, { hardDelete: true })` | | `softDelete` / `restore` | `deleteOneById` / [`restoreOneById`](https://uql-orm.dev/entities/soft-delete.md) | | `manager.transaction(fn)` | [`pool.transaction(fn)`](https://uql-orm.dev/querying/transactions.md) | | `manager.query(sql)` | [``all(sql`...`)``](https://uql-orm.dev/querying/raw-sql.md) / ``run(sql`...`)`` | | `Between(a, b)` | `{ $between: [a, b] }` | | `Like('%x%')` / `ILike('%x%')` | `{ $includes: 'x' }` / `{ $iincludes: 'x' }` | | `In([...])` / `Not(In([...]))` | `{ $in: [...] }` / `{ $nin: [...] }` | | `IsNull()` | `{ $isNull: true }` | MikroORM: | MikroORM | UQL | | - | - | | `em.find(User, where, { fields, orderBy, limit, offset })` | `findMany(User, { $where, $select, $sort, $limit, $skip })` | | `em.findOne(User, where)` | `findOne(User, { $where })` / `findOneById(User, id)` | | `em.count(User, where)` | `count(User, { $where })` | | `populate` + `populateFilter` | [`$populate`](https://uql-orm.dev/querying/relations.md) with a `$where` per relation | | `qb.groupBy().having()` | [`aggregate(User, { $group, $select, $having })`](https://uql-orm.dev/querying/aggregate.md) | | `em.create(...)` + `em.flush()` | `insertOne(User, data)`; there is no flush | | `em.nativeUpdate(User, where, data)` | `updateMany(User, { $where }, data)` / `updateOneById` | | `em.nativeDelete(User, where)` | `deleteMany(User, { $where })` / `deleteOneById` | | `em.upsert` / `em.upsertMany` | `upsertOne` / `upsertMany` | | `em.transactional(fn)` | [`pool.transaction(fn)`](https://uql-orm.dev/querying/transactions.md) | | `em.getConnection().execute(sql)` | [``all(sql`...`)``](https://uql-orm.dev/querying/raw-sql.md) / ``run(sql`...`)`` | | `$gte`, `$nin`, `$like`, `$or`, `$elemMatch` | same names, typed per field | | `$ilike` (PostgreSQL only) | `$ilike`, `$istartsWith`, `$iincludes` on every dialect | | `filters: { softDelete: ... }` | [`.softDelete()`](https://uql-orm.dev/entities/soft-delete.md), plus general [query filters](https://uql-orm.dev/querying/filters.md) | Mongoose: | Mongoose | UQL | | - | - | | `User.find(filter).sort().limit().skip()` | `findMany(User, { $where, $sort, $limit, $skip })` | | `User.findOne(filter)` | `findOne(User, { $where })` | | `User.findById(id)` | `findOneById(User, id)` | | `User.countDocuments(filter)` | `count(User, { $where })` | | `.select('id name')` | `$select: { id: true, name: true }` | | `.populate('posts')` | [`$populate: { posts: true }`](https://uql-orm.dev/querying/relations.md), as a join | | `User.aggregate([...])` | [`aggregate(User, { $group, $select, $having })`](https://uql-orm.dev/querying/aggregate.md) | | `User.create(doc)` / `insertMany` | `insertOne(User, doc)` / `insertMany(User, docs)` | | `findByIdAndUpdate(id, doc)` | `updateOneById(User, id, doc)` | | `updateMany(filter, { $set: doc })` | `updateMany(User, { $where }, doc)` | | `deleteOne` / `deleteMany` | `deleteOneById` / `deleteMany` | | `session.withTransaction(fn)` | [`pool.transaction(fn)`](https://uql-orm.dev/querying/transactions.md) | | `{ $regex: 'x', $options: 'i' }` | `{ $iincludes: 'x' }` for a plain substring, `{ $regex: '(?i)x' }` for a pattern | | `{ field: { $exists: true } }` | `{ field: { $ne: null } }`: a column always exists, so absent is `NULL` | | `$set: { 'settings.theme': 'dark' }` | `settings: { $set: { theme: 'dark' } }`, the JSON column first; deeper paths stay dotted | | `$push`, `$pull`, `$addToSet`, `$unset` on a subdocument | the same operators on a [JSON column](https://uql-orm.dev/querying/json.md#updating) | | `$push: { tags: 'x' }` / `$addToSet` / `$pull` on an array field | `tags: { $push: ['x'] }` on a [JSON array column](https://uql-orm.dev/querying/json.md#updating), each operator taking a list | | `$inc`, `$mul` | `{ stock: { $inc: -1 } }` | | `$setOnInsert` with `upsert: true` | [`upsertOne(User, { $conflict: { email: true }, $update }, row)`](https://uql-orm.dev/querying/methods.md#updating-a-conflicting-row-its-own-way): `row` is inserted, `$update` applies on a conflict | | `$currentDate` | the value `currentTimestamp` | | `findOneAndUpdate(filter, update, { new: true })` | [`updateOneById(User, id, update, { returning: true })`](https://uql-orm.dev/querying/methods.md#returning) | | `.populate({ path, match, select, perDocumentLimit })` | `$populate: { posts: { $where, $select, $limit } }`, whose `$limit` is per parent; Mongoose’s `options.limit` caps the total | | `Model.distinct('city', filter)` | `aggregate(User, { $where, $group: { city: true } })` | | `.lean()` | nothing: rows are plain objects | | virtuals | [`@Computed`](https://uql-orm.dev/entities/computed-fields.md) | | `schema.pre('save', fn)` | [hooks](https://uql-orm.dev/entities/lifecycle-hooks.md) such as `@BeforeInsert`, or a database [trigger](https://uql-orm.dev/entities/triggers.md) | | `timestamps: true` | a [`Timestamped` base class](https://uql-orm.dev/entities/computed-fields.md#timestamps) | | `ObjectId` | the key’s type: keep the 24-hex text (`f.string().id()`), or move to `f.uuid()` | | Subdocuments and arrays of objects | a [JSON column](https://uql-orm.dev/querying/json.md), or a relation if you filter or join on it | In [aggregate queries](https://uql-orm.dev/querying/aggregate.md), grouped columns go in `$group` and computed ones are named in `$select`, and `$having` and `$sort` are checked against those names. [Semantic search](https://uql-orm.dev/ai-semantic-search.md) is a `$sort` with `$vector`. ### Patterns worth seeing side by side The [comparison page](https://uql-orm.dev/comparison.md) covers every common operation; these two need more than renaming keys. #### Filtering, sorting, paging Prisma: ```ts prisma.user.findMany({ where: { age: { gte: 18 }, status: 'active', email: { contains: '@uql-orm.dev' } }, orderBy: { createdAt: 'desc' }, take: 10 }); ``` Drizzle: ```ts import { and, gte, eq, like, desc } from 'drizzle-orm'; db.select() .from(users) .where(and( gte(users.age, 18), eq(users.status, 'active'), like(users.email, '%@uql-orm.dev%') )) .orderBy(desc(users.createdAt)) .limit(10); ``` TypeORM: ```ts import { MoreThanOrEqual, Like } from 'typeorm'; manager.find(User, { where: { age: MoreThanOrEqual(18), status: 'active', email: Like('%@uql-orm.dev%') }, order: { createdAt: 'DESC' }, take: 10 }); ``` MikroORM: ```ts em.find(User, { age: { $gte: 18 }, status: 'active', email: { $like: '%@uql-orm.dev%' } }, { orderBy: { createdAt: 'DESC' }, limit: 10 }); ``` Mongoose: ```ts User.find({ age: { $gte: 18 }, status: 'active', email: { $regex: '@uql-orm.dev' } }) .sort({ createdAt: -1 }) .limit(10); ``` UQL: ```ts pool.findMany(User, { $where: { age: { $gte: 18 }, status: 'active', email: { $includes: '@uql-orm.dev' } }, $sort: { createdAt: 'desc' }, $limit: 10 }); ``` #### Atomic JSON updates Update one key of a JSON column in place: Other ORMs (raw SQL): ```ts await db.execute( `UPDATE users SET settings = jsonb_set(settings, '{theme}', '"dark"') WHERE id = 1` ); ``` UQL: ```ts await pool.updateOneById(User, 1, { settings: { $set: { theme: 'dark' } } }); ``` Rewriting the whole object would lose concurrent writes to other keys. `$set`, `$unset`, `$push`, `$pull` and `$addToSet` work on every dialect ([JSON / JSONB](https://uql-orm.dev/querying/json.md)). ## Migrating in phases Keep each old path until the new one is proven in production. 1. Move one non-critical read. Run old and new side by side and log any difference. 2. Build new tables and features on UQL, with [`generate:entities`](https://uql-orm.dev/migrations.md#from-entities-to-the-database) creating the tables. 3. Move writes one entity at a time, so each table has one writer. Port the old ORM’s callbacks, cascades and validation to [lifecycle hooks](https://uql-orm.dev/entities/lifecycle-hooks.md) in the same change: nothing warns you if they go missing. 4. When nothing uses the old ORM, remove it with its `.prisma` file, Drizzle snapshots or data source config. Keep its migration history table if you may need to audit it. # Upgrade guide > What each release asks of you, newest first, with the version and date it landed. Source: https://uql-orm.dev/upgrade-guide Releases that may need a change on your side, newest first. Everything else, including what a custom dialect or driver sees, is in the [changelog](https://github.com/rogerpadilla/uql/blob/main/CHANGELOG.md). ## 0.114.2 - 2026-11-08 Outside Postgres, an array in [`sql`](https://uql-orm.dev/querying/raw-sql.md#what-sql-interpolates) is refused: write `IN (${ids})` as `IN (${sql.join(ids)})`. ## 0.114.0 - 2026-11-07 Run the [codemod](https://uql-orm.dev/codemod.md) first: it reports each removed name with what replaces it. The HTTP handler is an API that every transport calls. `createApi({ pool, include, contextOf, use })` takes what `createRequestHandler` took, `getContext` renamed `contextOf` (as on the NestJS module, which the codemod renames), and `toFetchHandler(api)`, `toExpress(api)` and `toRequestHandler(api)` replace `createFetchHandler`, `querierMiddleware` and `createRequestHandler`. A tRPC or oRPC procedure calls `api.call(input, context)`, which checks the call itself ([tRPC](https://uql-orm.dev/trpc.md), [oRPC](https://uql-orm.dev/orpc.md)). `use: [(call, context, next) => next(call)]` replaces the `pre`, `preSave`, `preFilter` and `post` hooks: reshape the call before `next`, or what `next` resolves to after it; `serve(Entity, { use })` runs one on that entity’s calls alone. `toExpress` answers every failure itself, so `errorHandler` is gone. A hook or middleware refusing a client throws `new UqlRequestError(message, status)`: a `status` on any other error is no longer answered, since a driver’s comes with a message naming tables. What a client may do is the definition’s `wire`, on every route and relation reaching an entity ([what a client may do](https://uql-orm.dev/http.md#what-a-client-may-do)). Hide a field with `.wire(false)` on its builder instead of stripping it in `post`, which left it filterable; `@Entity({ wire: ['read'] })` or `defineEntity({ wire })` limits an entity’s operations. To keep one API read-only, as on D1, refuse writes in its `use` ([D1](https://uql-orm.dev/cloudflare-d1.md#serving-reads-over-http)). A write to a computed field, or an update of an `updatable(false)` one, answers `403` instead of being ignored. `createClientQuerier(httpTransport(url, { headers, readMethod }))` replaces `new HttpQuerier(url, defaults)`, and answers what the pool answers: `const users = await client.findMany(...)`, not `const { data: users }`; `findManyAndCount` answers `[rows, count]`; `exists` a boolean. `entityPath` moves to `createClientQuerier(transport, { entityPath })`. `on()`, `silent` and the `get`, `post`, `put`, `patch`, `remove` and `query` helpers are gone: wrap the transport ([around each call](https://uql-orm.dev/browser.md#around-each-call)). The [HTTP protocol](https://uql-orm.dev/http.md#wire-protocol) is one route per op, `{base}//` (`/user/findManyAndCount`), carrying the rest of the call as one JSON object in `?q=` or a `POST` body; it replaces the REST routes, their `PUT`, `PATCH` and `DELETE` verbs, `basePath` and the per-clause query string. Mount it under `/api/v1`, and send a body as `application/json`. A success answers `{ data }` with no `count`, an error `{ error: { message, status, kind, path } }` with `status` in place of `code`; an error that is not a `UqlError` answers generically by its kind (`409` for a unique violation, `503` for a retryable one) or `500`, never its message. ## 0.112.1 - 2026-11-05 The browser client reads rows by the entity it is handed: a `Date` field is a `Date`, no longer its ISO text, and a `bigint` exact, so code that parsed one can stop. The entity has to be registered where the client runs, as importing its class does; a class used only to name the route throws. A cache that persists the client’s rows needs a serializer that keeps a `Date` and a `bigint`. The `./browser` entry grows from about 2 KB gzipped to about 11 KB, the entity metadata. `uql-orm/browser` ships no prebuilt `uql-browser.min.js`: import the package entry, which every bundler resolves. ## 0.112.0 - 2026-11-04 Run the [codemod](https://uql-orm.dev/codemod.md) first: it rewrites the relation decorators. A relation decorator takes its target first, then its options, as `defineEntity`’s `rel.*` do: `@ManyToOne(() => User, { references: (post) => post.authorId })`, and `@OneToMany(() => Post)` where nothing else needs saying. The `entity` option is gone; in plain JavaScript, a decorator still passing it throws on first read. ## 0.111.2 - 2026-11-04 PGlite needs 0.5.10 or later: upgrade `@electric-sql/pglite`, and `@electric-sql/pglite-pgvector` with it. A statement now binds up to 65535 values, as on a Postgres server. ## 0.111.1 - 2026-11-01 `insertOne`, `insertMany`, `saveOne` and `saveMany` resolve to a defined key, so a `!` or a check on the result can go. On SQL engines, an insert leaving out a key the entity does not declare a fill for now throws before writing. If only the table states the default, declare it: `f.uuid().id().default(sql`gen\_random\_uuid()`)`. ## 0.111.0 - 2026-11-01 `.id()` no longer implies a generated key: a generated key says so, as `f.number().autoIncrement()`, or `f.bigint().autoIncrement()`. `.autoIncrement()` makes the column the key, so it replaces `.id()` rather than following it, and on a column that is no key, where it never generated anything, it is gone. `f.number().id()` is now a key the caller supplies, an insert has to name it, and `.autoIncrement(false)` is gone. Run `npx uql-codemod`, which rewrites each sole numeric key. On MongoDB, where nothing generates a numeric key, undo that for yours. An insert has to name a key unless the entity says something fills it. `defineEntity` reads that off its columns. A decorated class says so itself: keep `id!: number` and list it in `[filledKey]?: 'id'`, as any other field a default fills, or declare it `id?`. `@Field` refuses `?` on a numeric or `.references()` key nothing fills. A text key stays allowed `?`, which MongoDB generates. Generated entities carry `?` on a key the database fills. On SQLite, a new key the caller supplies is `INT`, as `INTEGER PRIMARY KEY` numbers its own rows. An existing table stays as it is, which `sync` reads as no drift. ## 0.110.0 - 2026-10-31 `.narrow()` is gone: a column’s type argument says it, `f.uuid()`, and a schema-less JSON payload is `f.json()`. For a builder with no type argument, set the SQL type after: `f.number().columnType('int')`. A [brand](https://uql-orm.dev/entities/basic.md#branded-types) now holds across a foreign key: a column referencing a branded key has to carry the brand, in a relation and on a decorated property. A filter on a branded `Date` takes the brand, not a plain `Date` or string. The `DateColumnType`, `BlobColumnType` and `VectorColumnType` exports are gone; `ColumnType` covers them. ## 0.109.2 - 2026-10-30 The deprecated `raw` export is gone, so `raw` from `uql-orm` no longer compiles. Use `sql`, which [`uql-codemod`](https://uql-orm.dev/codemod.md) renames at the import and every use. ## 0.109.0 - 2026-10-29 Run the [codemod](https://uql-orm.dev/codemod.md) first: it rewrites the upsert calls. An upsert’s update is its query’s `$update`, beside `$conflict` and `$where`, and the options follow the rows as on every other write: `upsertOne(SearchQuery, { $conflict: { term: true }, $update: { uses: { $inc: 1 } } }, row, opts)`, likewise in `upsertMany` and a trigger’s `upsertInto`. ## 0.108.0 - 2026-10-29 Run the [codemod](https://uql-orm.dev/codemod.md) first: it rewrites the upsert calls. An upsert’s conflict keys are a query, as `updateMany`’s `$where` is: `upsertOne(User, { $conflict: { email: true } }, row)`, likewise in `upsertMany` and a trigger’s `upsertInto`. A `$where` beside it limits which found rows [take the update](https://uql-orm.dev/querying/methods.md#updating-only-some-conflicting-rows). `QueryConflictPaths` is `QueryConflictKeys`. A [JSON column](https://uql-orm.dev/querying/json.md)’s default is a document: `.default('draft')` stores the JSON string `"draft"`, and `.default('{}')` is refused in favour of `.default({})`. On SQL Server, a uuid reads back lowercase, as written: compare ids as read, not uppercased. On MongoDB, a write of several steps no longer opens a transaction of its own, so it runs on a standalone server: an upsert with an `update` or a `$where`, and an `updateMany` or `deleteMany` that reads its ids first, cascades, or runs hooks. Wrap it in a [transaction](https://uql-orm.dev/querying/transactions.md) where it must land whole or not at all. ## 0.107.0 - 2026-10-27 On [MongoDB](https://uql-orm.dev/mongodb.md#ids), a foreign key only a relation declares (in `defineEntity`’s `.relations()`, or a plain `@Field` a `@ManyToOne` joins by) is now stored as an `ObjectId`, as an `f.references()` one already was, so `$populate` and `$count` find its rows. Convert the documents written before, per collection and field: `db.posts.updateMany({ author: { $regex: '^[0-9a-fA-F]{24}$' } }, [{ $set: { author: { $toObjectId: '$author' } } }])`. ## 0.106.0 - 2026-10-26 A JSON column’s payload is a [Standard Schema](https://uql-orm.dev/querying/json.md#a-schema-for-the-payload), `f.json(schema)`: the `shape` option (`f.json({ lang: String })`) is gone. The codemod leaves a `shape` it cannot write as a builder, so write the schema by hand or with any Standard Schema library. It also converts a class registered with `defineEntity(Class, options)` into a `defineEntity({ name, fields })` call, and leaves a class it cannot convert as it is, with the reason. `defineEntity` has no `.references()` section. A foreign key is a [relation](https://uql-orm.dev/entities/relations.md) in `.relations()`, which checks its key type at compile time; the column never names its target. `f.references()` on a decorated field is unchanged. ## 0.105.0 - 2026-10-25 Run the [codemod](https://uql-orm.dev/codemod.md) first: it rewrites what follows where it can and reports the rest. A column is a [builder](https://uql-orm.dev/entities/basic.md): `@Field(f.string().nullable().length(80))` replaces `@Field({ type: String, nullable: true, length: 80 })`. It is NOT NULL unless `.nullable()`, a key is `.id()` (`@Id` is gone), and a computed field is ``@Computed((post) => f.string().as(sql`...`))``. A builder has no method for an option its type cannot take, so `f.number().length(10)` does not compile. The [migration builder](https://uql-orm.dev/migrations/builder.md) takes the same methods: `table.string('email').length(80).nullable()`, `.default()` for `.defaultValue()`, `.id()` for `.primaryKey()` and `.as()` for `.computed()`. `@Index`, `@Filter` and `@Trigger` are gone: list them in `@Entity({ indexes, filters, triggers })`. An index, check or trigger entry is written by the helper its callback hands over, `indexes: (post, index) => [index([post.title], 'by_title')]`. A base class carrying them without being a table is `@Entity({ abstract: true, ... })`. The codemod folds each decorator in, its comments with it. A JSON index entry reads its path off the column’s ref, as the `$where` key it serves: `index([user.settings.theme])` for text, `{ column: user.settings.rating, type: Number }` for any other value, and `type: [String]` for an array’s elements. `jsonPath` and `jsonArray` are gone. An unnamed JSON index is now named after its path too, so the next [migration](https://uql-orm.dev/migrations.md) rebuilds each one once. In the migration builder an expression entry is ``{ expression: sql`lower(email)` }``. An entry’s `length` is `prefixLength` on a column and `charLength` on a JSON path. An entity is a decorated class or [`defineEntity({ name, fields })`](https://uql-orm.dev/entities/define-entity.md) with its other options as chained sections. `defineEntity(Class, options)`, `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are gone, and so are `@Entity`’s `fields`, `relations`, `hooks` and `extends`. The codemod rewrites a class `defineEntity` registered as `export const Post = defineEntity({ name: 'Post', ... })`, a table it named kept as `table`, folding the same class’s definers in; it reports a class it cannot convert as it is, such as one with methods. A decorated class names its base by extending it. A foreign key column holding its own type must hold the type of the key it references, and `f.decimal(precision, scale)` carries its digits into its type: `tsc` names each mismatch. `$exclude` is gone: write `$select: { password: false }`, which the codemod rewrites it to. A server answers a request still sending it with a 400, as it does any `$` key a query does not take. A `$sort` that projects a distance or a score puts it on the row’s type, so drop the `as WithProjection<...>` cast: `WithProjection` is gone. An empty `$project` throws on every SQL engine. On MongoDB Atlas, a vector `$sort`’s `$project` holds the distance, lower nearer, as on the SQL engines, not Atlas’s score: flip a check like `score > 0.8` into a cut-off on the distance. ## 0.104.0 - 2026-10-22 A read captures its whole query, so `QueryFindResult` takes the field names or the query: `QueryFindResult` keeps working, and `QueryFindResult` replaces the forms that named `$select` values, `$exclude`, `$populate` and `$count` key by key. `QueryProjected`, `QueryOneProjected`, `QueryKeysetProjected` and `ProjectedQuery` are gone: a function forwarding a query types it `Captured, Q>`, as [the querier page](https://uql-orm.dev/querying/querier.md#naming-a-projected-row) shows. `ReturningResult` is `WriteResults`. `tsc` names every use to change. ## 0.103.0 - 2026-10-21 `NeonQuerierPool` takes Neon’s `ClientConfig`: drop pool options such as `max` and `idleTimeoutMillis`. It holds no connection, so build it once at module scope, Cloudflare Workers included, and drop the `pool.end()` a handler ran for it. ## 0.102.0 - 2026-10-11 On MongoDB, an `updateMany` or `deleteMany` that is paged, filtered through a relation, hooked, cascading or `returning` runs in a transaction, so it needs a [replica set](https://uql-orm.dev/mongodb.md#transactions-need-a-replica-set). A single-node one is enough for development. ## 0.101.4 - 2026-10-10 `uql-orm/migrate` and `uql-orm/nestjs` no longer export the schema introspector classes or `UqlContextInterceptor`; the migrator and the Nest module still use them. ## 0.101.2 - 2026-10-10 `raw` is renamed `sql`, which editors highlight as SQL: ``sql`...` ``, `sql.join`, `sql.text`. `raw` still works but is deprecated; [`uql-codemod`](https://uql-orm.dev/codemod.md) renames it. ## 0.101.1 - 2026-10-10 `uql-orm/migrate`, `uql-orm/http` and the driver entries export only what the docs use. `tsc` names any import that is gone. ## 0.100.0 - 2026-10-08 Run [`uql-codemod`](https://uql-orm.dev/codemod.md) first. It moves imports to the renamed entries (`uql-orm/mariadb`, `uql-orm/mongodb`, `uql-orm/bun-sql`) and off the removed ones (`uql-orm/type`, `uql-orm/dialect`, `uql-orm/entity`, `uql-orm/querier`, `uql-orm/namingStrategy`, now `uql-orm`), and renames `Sqlite3QuerierPool` to `SqliteQuerierPool` and `IMigrationBuilder`-style types to `MigrationBuilder`. Then: - Upgrade to TypeScript 5.7 or newer, and keep each driver on a supported major (`pg` 8, `mongodb` 6 or 7, …). - Import only what the docs show from `uql-orm`: the abstract dialect and querier classes, `SqlQueryContext` and helpers such as `fieldOf` are internal, and `uql-orm/util` is gone (the codemod moves `raw`, `refs` and the other names the root still exports). - `all` and `run` are [tags](https://uql-orm.dev/querying/raw-sql.md), ``pool.all`SELECT ... ${id}` ``, which bind each value. The codemod rewrites a literal statement into one, its `?` or `$1` values included, and wraps SQL built at run time in `sql.text(...)`. Wrap a SQL string you interpolate into a tag in `sql.text` too, or it is bound as a value ([building a statement](https://uql-orm.dev/querying/raw-sql.md#building-a-statement-from-parts)). An interpolated `undefined` throws, and a JSON document is bound as `${JSON.stringify(doc)}`. - A pool call inside a `pool.transaction()` callback joins the transaction, uncommitted writes included. To read what is committed instead, use a querier of its own, `await using querier = await pool.getQuerier()`, on an engine with more than one connection (not SQLite, PGlite or local Turso). - In `/http`, `HookContext` and `Hook` are `RequestHookContext` and `RequestHook`. - A `decimal` is a `string`. Declare `type: Number` to keep a number. - `Json` is a bare `Json`. - `upsertOne` resolves to the id and `upsertMany` to the ids: read `ids[0]` for `firstId`, and drop `created` and `changes`. - An `undefined` in `$where` or `$having` throws. Leave the key out, or write `null`. - A nested `transaction()` is a savepoint, and is refused on MongoDB. - A to-many update removes the children the payload leaves out. A to-one holding the key cascades `'persist'` only ([relations](https://uql-orm.dev/entities/relations.md)). - `migrator.down()` with no options reverts one migration; pass `{ step: Infinity }` for all. - Replace `pending()` and `executed()` with `status()`. Drop the `storage` option and the migration storages (`JsonMigrationStorage`, `MongoMigrationStorage`). - `generate:entities` renames a column in place only when the two names differ by case or underscores (`firstName`, `first_name`). Write any other rename into the migration yourself, as `renameColumn`, before it drops the column. - Catch `UqlUsageError` where you caught `UqlLockUsageError`. - On MongoDB, the next migration or `sync` gives each collection with [checks or enums](https://uql-orm.dev/mongodb.md) a validator, replacing a hand-written one. Stored documents are checked on their next update. ## 0.99.0 - 2026-10-07 - A migration file that fails to load, or lacks `up` and `down`, stops `up` and `down` before anything runs. Move helper modules out of the migrations directory. - `Migrator.pending()` returns names. Replace `getMigrations`, `getMigrationFiles`, `loadMigration` and `isMigration` with `status()`, `up()` and `down()`. ## 0.98.0 - 2026-10-07 - `$regex` is case-sensitive on MySQL and MariaDB too. Spell both cases where you relied on the collation: `'^[Jj]ohn'`. ## 0.97.0 - 2026-10-07 - [Checks and enums](https://uql-orm.dev/entities/enum-checks.md#how-a-change-is-detected) are diffed and installed as `_uql____`. The next migration or `sync` adds each under its new name; drop the old ones by hand (each is warned about), or a widened enum keeps rejecting its new values. - On SQLite, D1 and Turso, that change rebuilds each table with a check or an enum. On D1 or remote libSQL, a referenced table needs foreign keys off to rebuild. ## 0.96.0 - 2026-10-06 - A custom `MigrationStorage` does not need `ensureStorage`. - `Migrator.logger` is read-only: pass `logger` in the `Migrator` options. - `CreateSchemaOptions.foreignKeys` is gone; a schema always carries its foreign keys. - `drift:check` on MongoDB fails where it reported drift. Use `sync --dry-run` to see index changes. - Turso needs `@tursodatabase/database` 0.8.2+ and `@tursodatabase/serverless` 1.4.1+. - The next `sync` indexes a foreign key whose only covering index is partial, fulltext, vector or a MySQL prefix one. ## 0.95.0 - 2026-10-01 - An upsert takes its update as the fourth argument, `upsertOne(Entity, paths, row, { uses: { $inc: 1 } })`, not `{ update: ... }`. [`uql-codemod`](https://uql-orm.dev/codemod.md) rewrites it. - An empty update `{}` leaves a conflicting row as it is. The codemod cannot tell it from an old empty options object, so delete such a `{}` yourself. - `upsertOne`, `upsertMany`, and `saveOne`/`saveMany` naming a key write [cascaded](https://uql-orm.dev/entities/relations.md) relations, replacing a found row’s. ## 0.94.0 - 2026-10-01 - A statement on the querier inside its own `findManyStream` loop throws `UqlUsageError`. Run it on another connection, or after the loop on SQLite and PGlite ([streaming](https://uql-orm.dev/querying/streaming.md#one-statement-at-a-time-on-the-querier)). - `findManyStream` runs `@AfterLoad` per row, so a hook querying through its `querier` is refused there too. - A statement binding more values than its engine allows is refused: 100 on D1, 2098 on SQL Server, 32766 on SQLite, 32767 on PGlite, 65535 on MySQL and MariaDB. Split a long `$in`; lists UQL builds are split for you. ## 0.93.0 - 2026-10-01 - The migration builder’s `expr` is gone. [`uql-codemod`](https://uql-orm.dev/codemod.md) rewrites each default as an entity spells it (`expr.now()` is `currentTimestamp`). - `expr.onUpdateNow()` has no rewrite: use `m.raw(...)`, or a [stamp](https://uql-orm.dev/entities/computed-fields.md#stamps-stored-on-an-event). ## 0.92.0 - 2026-09-30 - A `Date` field without `precision` stores milliseconds on every engine (`TIMESTAMPTZ(3)`, `DATETIME2(3)`). [Generate a migration](https://uql-orm.dev/migrations.md) or `sync`, which rounds past the millisecond; `precision: 6` keeps a column. - On MongoDB, a `$select` without the key does not return `id`. Name it. - Over HTTP, an update or delete answers its changed row count in `data`, not ids. A `DELETE` naming no rows is a `400`. - `uql-orm/browser` drops `getQuerier`, `getQuerierPool`, `setQuerierPool` and `ClientQuerierPool`. Create `new HttpQuerier('/api')` where you use it; [`uql-codemod`](https://uql-orm.dev/codemod.md) points at each use. ## 0.91.0 - 2026-09-28 - An insert must include every field declared `!`, except a single-column id and the `version`. Declare it `?` if a `defaultValue` or `onInsert` fills it ([required fields](https://uql-orm.dev/entities/basic.md#required-fields)). - A `type: 'time'` field is a `string`, not a `Date`. ## 0.90.0 - 2026-09-26 - Import `MongoQuerier`, `isMongoQuerier` and `MongoSchemaIntrospector` from the MongoDB entry (`uql-orm/mongodb` since 0.100.0), including in each MongoDB migration. [`uql-codemod`](https://uql-orm.dev/codemod.md) moves them. ## 0.89.0 - 2026-09-26 - On SQL Server, a trigger with `of` or `where` refuses a body of your own SQL. Write it with `insertInto`, `updateTable` and `deleteFrom`, joined in one `sql` where there are several. - A `$where` mixing a relation’s `$size` with a condition on its rows, and a `$text` `$fields` naming a non-string field, do not compile. ## 0.88.0 - 2026-09-26 - `sync` and `generate:entities` refuse a newly required field with no `defaultValue` on a table with rows. Declare a default, or add it nullable, fill it, then require it. - On SQLite, `sync` rebuilds a table to add a relation’s foreign key: read a `planSync()` before the next one. - On SQL Server, a trigger with `of` gets a new name, which `sync` installs in place of the old one. ## 0.86.0 - 2026-09-26 - `uql-orm/betterAuth` is removed until it returns as its own package. ## 0.85.0 - 2026-09-25 - `createFetchHandler`, `createRequestHandler` and `querierMiddleware` require `include` and serve only those entities: `createFetchHandler({ pool, include: [User, Post] })`. - `exclude` is gone. Leave those entities out of `include`. ## 0.84.0 - 2026-09-25 A `security` filter guards writes as well as reads. A write outside it throws `UqlSecurityError` (`403` over HTTP). - An insert gets the filter’s fields from the context; naming another value throws. Delete any `onInsert` tenant fill. - An update changing those fields throws. Move rows between tenants under a trusted context resolving to `{}`. - A save or upsert naming another tenant’s row fails on its key. On a guarded entity it reads conflicting rows first, so it runs two or three statements. - A filter that is not plain field equalities (`$in`, `$or`) refuses writes. Write those rows under a `{}` context. - `UqlUsageError` is not a `TypeError`; all three UQL errors extend `UqlError`. Test `queryErrorKind(err) === 'usage'` instead of `instanceof TypeError`. ## 0.83.0 - 2026-09-24 Every SQL engine binds and reads a `Date` as UTC. Dates written from a non-UTC process read shifted until their columns are converted, so [generate a migration](https://uql-orm.dev/migrations.md): - Postgres, CockroachDB: `Date` columns become `TIMESTAMPTZ`. Run the migration with the session `TimeZone` set to the zone the app wrote in (usually `UTC`). `columnType: 'timestamp'` keeps a column zoneless. A `DATE` reads as UTC midnight. - MySQL, MariaDB: `DATETIME` becomes `DATETIME(3)`; `precision: 0` keeps whole seconds. Sessions run in UTC. A raw read on MariaDB returns a `DATETIME` as text. - SQLite, libSQL, Turso, D1: dates are stored as UTC text, not epoch milliseconds. Convert rows with `UPDATE t SET col = strftime('%Y-%m-%d %H:%M:%f', col / 1000.0, 'unixepoch') WHERE col NOT LIKE '%-%'`. ## 0.80.0 - 2026-09-23 - On SQL engines, `$ne` excludes rows where the column is NULL, like `$nin`, `$not` and `$nor`. MongoDB keeps them. To include them: `{ $or: [{ status: { $ne: 'draft' } }, { status: null }] }`. ## 0.79.0 - 2026-09-21 - `length`, `precision` and `scale` on `type: 'varchar'` or `'decimal'`, and `dimensions` on `columnType: 'vector'`, reach the column. Existing columns read as drift and are altered: check the values fit. ## 0.77.1 - 2026-09-20 - Rename `UqlLockUsageError` to `UqlUsageError`, thrown by every misuse. The old name still resolves to it. - Over HTTP, a call the API cannot carry out answers `400`, not `500`. ## 0.77.0 - 2026-09-19 - On an entity with a [version field](https://uql-orm.dev/entities/optimistic-locking.md), `updateMany` over many rows is refused. Update each row by id. ## 0.73.0 - 2026-09-18 - Rename `WithDistance` and `WithScore` to `WithProjection`. - On SQLite, libSQL and Turso, a vector column created before 0.71.0 is `TEXT` and reported by `drift:check`. Recreate its table in a migration with the column as `F32_BLOB`, which libSQL’s vector index needs. ## 0.70.0 - 2026-09-18 - Run the [codemod](https://uql-orm.dev/codemod.md) to append `| null` to each nullable column’s property. Give a column that never holds null `nullable: false` instead. - An `updateMany` or `deleteMany` naming no rows throws. Pass `{ unfiltered: true }` for the whole table. - A write payload naming a `readonly` field does not compile. - Replace `$sumDistinct` and `$avgDistinct` with a `$group` on the field. ## 0.68.1 - 2026-09-17 - An RPC contract takes [`WireQuery`](https://uql-orm.dev/trpc.md). - A `sql` fragment or `Uint8Array` in a browser-client query or payload does not compile, and a cast past the types throws. Keep both server-side. - Run the [codemod](https://uql-orm.dev/codemod.md) to rename `D1Database` to `D1Queryable`. - A query type takes its SQL type before its key set: `QueryWhere`. ## 0.68.0 - 2026-09-17 - On PostgreSQL and CockroachDB, [generate a migration](https://uql-orm.dev/migrations.md) for each numeric `jsonPath` index, whose expression changed. - `$elemMatch` with one `$eq` or `$in` compares by JSON type, so `'5'` does not match `5`. An object in `$all` matches an element holding its keys. ## 0.66.0 - 2026-09-16 - Run the [codemod](https://uql-orm.dev/codemod.md): every to-one names its foreign key in `references` and declares the column. For a composite key, declare a column per key and pair them. - `tsc` then reports what registration refused at startup: a skipping security filter, and a `mappedBy` or `references` column that cannot hold the key it joins. ## 0.65.0 - 2026-09-14 - Run the [codemod](https://uql-orm.dev/codemod.md), then give each junction column `references`. - Declare a relation for any `@Field({ references })` column you `$populate`. - Read `pool.dialect.dialectName` instead of `migrator.dialectName`. ## 0.63.0 - 2026-09-13 - Write an index expression as `sql` in the list, ``(user) => [sql`lower(${user.email})`]``. - Move SQLite off the Bun SQL entry to [`SqliteQuerierPool`](https://uql-orm.dev/sqlite.md). - Upgrade `@tursodatabase/serverless` to 1.3+, and pass a libSQL client you built to [`LibsqlQuerierPool`](https://uql-orm.dev/turso.md#libsql). - SQLite reads an integer past 2^53 as text. ## 0.62.0 - 2026-09-13 - Run the [codemod](https://uql-orm.dev/codemod.md) for the renamed options and `col()`, which is [`refs(Entity)`](https://uql-orm.dev/querying/raw-sql.md). - SQL an entity declares reads columns off a callback’s refs: ``(user) => sql`lower(${user.email})` ``. ## 0.60.0 - 2026-09-12 - A [builder migration](https://uql-orm.dev/migrations/builder.md) gets the builder first and the querier second: `up(m, querier)`. Move `querier.run` calls to `defineMigration`. ## 0.58.0 - 2026-09-11 Members are named by callbacks and keys, never strings, and the [codemod](https://uql-orm.dev/codemod.md) rewrites all of it: - Definitions: `@Index((post) => [post.title])`, `mappedBy: (post) => post.author`, `references`. - `aggregate()` takes computed columns in `$select`, not `$agg`, and `$text` takes `$fields: { title: true }`. ```ts await pool.aggregate(Order, { $group: { status: true }, $select: { total: { $sum: { amount: true } } }, }); ``` ## 0.57.0 - 2026-09-11 - A to-many `$populate` and `$count` read in the parent’s statement, which needs MySQL 8.0.14+ and SQLite 3.44+. - Each table reads under its own name, relation key or join path, so raw SQL naming a related table uses that alias. - Every foreign key gets an index unless one leads with it (`index: false` opts out). The next migration adds them. ## 0.55.0 - 2026-09-10 - A BIGINT past 2^53 reads as exact text. Declare `type: BigInt` for a typed exact integer. - The [codemod](https://uql-orm.dev/codemod.md) renames `CrdbQuerier`/`NeonQuerier` to `PgQuerier` and `LibsqlQuerier`/`TursoQuerier` to `HranaQuerier`. - Raw access on Bun SQL is `pool.sql`. ## 0.54.0 - 2026-09-10 - `virtual` and the `raw('...')` call are gone; the [codemod](https://uql-orm.dev/codemod.md) rewrites both. - An `after*` hook’s `this` is a copy of the row as written, so mutating it leaves your object alone. ## 0.53.0 - 2026-09-10 `$where` takes only a map. An id, a list of ids or a bare SQL fragment there does not compile, and answers 400 over HTTP. Name the key, and put SQL fragments in `$and`. The [codemod](https://uql-orm.dev/codemod.md) renames `QueryWhereMap` to `QueryWhere`. ```ts import { sql } from 'uql-orm'; await pool.findMany(User, { $where: { id: [1, 2] } }); await pool.findMany(User, { $where: { $and: [sql`"createdAt" > now()`] } }); ``` ## 0.52.0 - 2026-09-09 - `BunSqlPostgresDialect`, `BunSqlCockroachDialect` and `BunSqliteDialect` are gone; the pool builds the dialect. ## 0.48.0 to 0.51.0 - 2026-09-09 - `saveOne`/`saveMany` upsert on the key a row names. A stale id writes the row, and [composite keys work](https://uql-orm.dev/querying/methods.md#saveone--savemany). - A save naming its key fires `@BeforeUpsert`/`@AfterUpsert`: move logic from `@BeforeUpdate`. - Every write reports its id as the column value, or the [key map](https://uql-orm.dev/querying/methods.md#composite-keys) on a composite. - `upsertOne` and `upsertMany` return `id` and `ids` (payload order), not `firstId`. - A key not called `id`, `_id` or `uuid`, and every composite, needs the `idKey` brand, which the [codemod](https://uql-orm.dev/codemod.md) writes: ```ts import { Entity, Field, f, idKey } from 'uql-orm'; @Entity() export class Enrolment { [idKey]?: 'studentId' | 'courseId'; @Field(f.number().id()) studentId!: number; @Field(f.string().id()) courseId?: string; } ``` - On MongoDB, a key you supply is the document’s `_id`; older documents keep their minted id. Ids read as hex strings, and a database-generated key must be one [MongoDB can mint](https://uql-orm.dev/mongodb.md#generated-keys). ## 0.46.0 - 2026-09-08 - `virtual` is renamed to [`computed`](https://uql-orm.dev/entities/computed-fields.md); giving both throws. The [codemod](https://uql-orm.dev/codemod.md) rewrites it. ## 0.45.0 - 2026-09-08 - `sync` applies foreign keys (except on SQLite): read a `planSync()` before the first one. - On MySQL and MariaDB, generated keys are not `UNSIGNED`, and an `UNSIGNED` key refuses constraints pointing at it. On a database created earlier, run this (under `safe: false`) before adding foreign keys, as a migration rather than at boot, since it rebuilds the table under a metadata lock: ```sql title="MySQL" ALTER TABLE `Company` MODIFY COLUMN `id` BIGINT AUTO_INCREMENT; ``` - A key filled by `onInsert` is not auto-increment. - `serial`, `bigserial` and `smallserial` are gone as `columnType`. Use `@Id({ type: Number })` or `@Id({ type: Number, columnType: 'int' })`. ## 0.44.0 - 2026-09-07 - A naming strategy does not rewrite a table you named, so check what `@Entity({ name: 'UserProfile' })` maps to. - `migrator.autoSync`, `syncForce` and `syncEntity` are one `migrator.sync(options)`. ## 0.43.0 - 2026-09-07 An option a column cannot use is an error. Delete: - `length`, `precision`, `scale`, `autoIncrement`, `dimensions` and `distance` where the type has no use for them. - DDL or generator options on a `virtual` field, and `onUpdate` beside `updatable: false`. - `nullable: true` on a key. - A `defaultValue` that is not the stored value (a JSON column keeps its SQL literal, `defaultValue: '{}'`). ## 0.42.1 - 2026-09-05 - Keys and indexes are recognised by their columns, never by name, so nothing in your database is renamed. - Adding a key column to a table with rows fails until you fill it. ## 0.42.0 - 2026-09-04 - A second `@Id` composes a two-column [`PRIMARY KEY`](https://uql-orm.dev/entities/basic.md#composite-primary-keys) instead of replacing the first. Narrowing an inherited key is unaffected. - `EntityMeta.id` is `ids`, a list. ## 0.24.0 - 2026-08-02 - The pool runs every operation, so a writing function can take `UniversalQuerier`. - A hand-written `QuerierPool` must implement `insertMany`, `updateMany`, `upsertOne`, `upsertMany` and `saveMany`. ## 0.23.0 - 2026-08-01 Decorators are the standard TC39 ones. The [codemod](https://uql-orm.dev/codemod.md) drops `experimentalDecorators`, `emitDecoratorMetadata` and `reflect-metadata`, and reports what is left. Then: - Set `target` to anything but `esnext`, which leaves decorators untransformed. - Build with esbuild, SWC, Babel `version: '2023-11'`, Bun or `tsc`. Oxc does not transform them, so Vite 8 needs one of the others. - Run `uql.config.ts` with `bun` or `node --import tsx` if it imports entities. - On NestJS, use `defineEntity`: Nest’s DI needs parameter decorators ([NestJS](https://uql-orm.dev/nestjs.md)). - Use Node 22.18 or newer (24 before 0.101.0). # Codemod > One command that rewrites your code across the UQL breaking changes that can be made mechanically. Source: https://uql-orm.dev/codemod `uql-codemod` rewrites your code across UQL’s mechanical breaking changes and reports what it cannot decide. Run it first when you upgrade, then `tsc`, then the [upgrade guide](https://uql-orm.dev/upgrade-guide.md) for the rest. ```sh npx uql-codemod --dry-run ``` ```plaintext needs a decision: src/entity/audit.ts:9: has no 'type': declare its column as a builder, such as `f.string()` would change: src/entity/user.ts ... 23 file(s) would change 1 item(s) need a decision; see above ``` `needs a decision:` marks something it will not guess, and `worth a look:` a rewrite you may want to read. Drop `--dry-run` to write the files. Only the edited text changes; comments and formatting stay as you wrote them. `--project=` picks another `tsconfig.json` (it must cover your entities), and `--include=` limits the paths. It exits `0` when nothing is left, `1` when something is, and `2` when it could not start. Everything it inserts is type-checked against the property it describes, so a wrong guess shows up as a `tsc` error. ## What it rewrites Entities and relations: - A column’s options to its [builder](https://uql-orm.dev/entities/basic.md#field-options): `@Id()` and `@Field({ type: String, nullable: true, length: 80 })` to `@Field(f.number().autoIncrement())` and `@Field(f.string().nullable().length(80))`, a NOT NULL column losing its `nullable: false`, and a `computed` field to `@Computed((row) => f.string().as(...))`, or `@Computed((row) => row.books.count())` for an aggregate. - A sole numeric key to the generated one it was, `f.number().id()` to `f.number().autoIncrement()`, and `.autoIncrement(false)` dropped. A key a relation shares stays `.id()`, as does a class’s `id!`, which an insert then names until it is `id?` or listed in `[filledKey]`. On MongoDB, take `.autoIncrement()` off a numeric key. - Each index, check and trigger entry to the helper its callback is handed: `indexes: (post, index) => [index([post.title], 'by_title')]`. - `@Index`, `@Trigger` and `@Filter` into `@Entity`’s `indexes`, `triggers` and `filters`, each decorator’s comments kept above its entry; a class with no `@Entity` becomes `@Entity({ abstract: true, ... })`, a base that is never a table. - Members named by string to callbacks, in `mappedBy`, `include`, `references`, and the `indexes` and `hooks` of `@Entity`/`defineEntity`: `mappedBy: 'author'` to `(post) => post.author`. - `references: (post) => post.authorId` on each to-one, declaring the `authorId` column where it is missing. - A relation decorator’s target first, as `defineEntity`’s `rel.*` take it: `@ManyToOne({ entity: () => User, references })` to `@ManyToOne(() => User, { references })`, and `@OneToMany({ entity: () => Post })` to `@OneToMany(() => Post)`. - A JSON index entry to the path read off its column’s ref: `{ column: post.kind, jsonPath: { path: 'theme', type: Number } }` to `{ column: post.kind.theme, type: Number }`, and a `jsonArray`’s element type to `type: [String]`. Its `length` becomes `charLength`, and a column entry’s `prefixLength`. - `| null` on each [nullable column](https://uql-orm.dev/entities/basic.md#nullable-columns)’s property, except keys, relation aggregates and `nullable: false` fields. - The [`idKey` brand](https://uql-orm.dev/entities/basic.md#naming-the-key) on a key not called `id`, `_id` or `uuid`, and on every composite. - `virtual` to [`computed`](https://uql-orm.dev/entities/computed-fields.md), and a check’s `expression` and a filter’s `condition` to `where`. - A class registered with `defineEntity(Post, { ... })` to the [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) call it stands for, `export const Post = defineEntity({ name: 'Post', ... })`, the class removed: its other options as the sections chained after it, each relation as a `rel` thunk, a relation aggregate in `.relations()`’ second callback, a hook’s method as a function of the row, and the same class’s `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` folded in. A column’s foreign key becomes the relation joining on it, its `onDelete` moved into that relation, and a key no relation joins on gets a `manyToOne` written for it. A class with a method no hook runs, a base it extends, or a foreign key no relation can take is reported and left as written. SQL and queries: - `raw` to [`sql`](https://uql-orm.dev/querying/raw-sql.md), at the import and every use. `raw('SQL')` becomes the tagged template, `raw(fn, alias)` becomes `sql(fn).as(alias)`, and `col('cost')` becomes a ref: ``(product) => sql`${product.cost}` ``in a `computed`, `refs(Item).cost` in a statement. - A [migration builder](https://uql-orm.dev/migrations/builder.md) column’s options to the same methods: `table.string('email', { length: 80, nullable: true })` to `table.string('email').length(80).nullable()`, `.defaultValue()` to `.default()`, `.primaryKey()` to `.id()`, `.computed()` to `.as()`, and `.notNullable()` dropped. - A partial-index `where` string to `sql`, in entities and the migration builder, and the builder’s `expr` defaults: `expr.now()` to `currentTimestamp`, `expr.uuid()` to `uuid`, `expr.raw('...')` to ``sql`...` ``. - `$exclude` to a `$select` leaving its fields out, `$select: { password: false }`, at every depth of `$populate`. - An aggregate’s `$agg` to `$select`, and fields named in it or in `$text`’s `$fields` to keys: `{ $sum: { amount: true } }`. - An upsert’s conflict keys to a query, `upsertOne(User, { email: true }, row)` to `upsertOne(User, { $conflict: { email: true } }, row)`, and its update, a fourth argument or `{ update: X }` options, to the query’s `$update: X`, the options after it kept, in `upsertOne`, `upsertMany` and a trigger’s `upsertInto`; `QueryConflictPaths` to `QueryConflictKeys`, and `const { id } = await upsertOne(...)` to `const id`, since it resolves to the id. - `$lock: { wait: 'skip' }` to `{ $wait: 'skip' }`, or `true` for a lock that waits. - `run` and `all` to tags: `all('SELECT * FROM t WHERE id = ?', [id])` to ``all`SELECT * FROM t WHERE id = ${id}` ``. A string built at run time goes in `sql.text(...)`. Imports and setup: - Renamed exports, with their imports and uses: `QueryWhereMap`, `RelationKeyMap`, `FilterCondition`, `IndexColumnSchema` (to `IndexEntry`), `IndexColumnModifiers` (to `IndexEntryModifiers`), `QueryDialect`, `EngineFeatures`, `KnownMigratorDialect` (to `DialectName`), `D1Preparer` and `D1Database` (to `D1Queryable`), `SqlMigrationModuleOptions`, `buildSqlQuerierMigrationModule`, `Sqlite3QuerierPool` (to `SqliteQuerierPool`), the migration builder’s `IMigrationBuilder`, `ITableBuilder` and the like (to `MigrationBuilder`, `TableBuilder`), and each driver subclass (`PgDialect`, `NeonQuerier`, `LibsqlQuerier`, …) to its base class. - `MongoQuerier`, `isMongoQuerier` and `MongoSchemaIntrospector`, imported from `uql-orm/mongodb`. - `CrudOperation` to `ApiOp` and `RequestOptions` to `CallOptions`; each removed HTTP export (`createRequestHandler`, `querierMiddleware`, `HttpQuerier`, …) is reported with what replaces it. - An awaited browser client’s result to the value it answers now: `(await client.findMany(...)).data` and `const { data: users } = await ...` lose the envelope, and a `findManyAndCount`’s `{ data, count }` becomes `[rows, count]`. - `UqlModule.forRoot({ getContext })`, and its async form, to `{ contextOf }`. - Entries: `uql-orm/maria`, `uql-orm/mongo` and `uql-orm/bunSql` to `uql-orm/mariadb`, `uql-orm/mongodb` and `uql-orm/bun-sql`; `uql-orm/type`, `uql-orm/dialect`, `uql-orm/entity`, `uql-orm/querier` and `uql-orm/namingStrategy` to `uql-orm`. ## What it leaves to you - `@Transactional()`, `@InjectQuerier()`, `@Log()` and `@Serialized()`, which UQL does not have. Wrap a `@Transactional()` method’s body in `pool.transaction()` on the pool you choose. - Removed exports with no one-to-one replacement, such as `setQuerierPool` or `AbstractPgQuerier`; internals the root no longer exports (`AbstractSqlQuerier`, `fieldOf`, …); the migration storages; and any import from `uql-orm/util` the root does not export (`raw`, `refs` and the rest it does export move to `uql-orm`). - `Migrator`’s `pending()` and `executed()`, now read off `(await migrator.status())`, and a bare `down()` (`worth a look:`), which reverts only the last migration: `{ step: Infinity }` reverts them all. - A `col()` whose entity it cannot tell: a raw built apart from its query, one under a relation filter, or a column no field maps. Read it off [`refs(Entity)`](https://uql-orm.dev/querying/raw-sql.md). - Values it cannot read statically: `@Field(shared)`, a spread, a non-literal list. - A partial-index `where` template that interpolates, since `sql` would bind each interpolation as a value. - A JSON index entry whose `path` is not a string literal, or whose `jsonPath`/`jsonArray` takes an option besides `path`, `type` and `length`. - A `run`/`all` with values it cannot place safely, such as a non-literal list or SQL, or mixed `?` and `$n`. - SQL in a definition that names a column by hand (`worth a look:`). Only a ref follows a rename: ``(user) => sql`lower(${user.email})` ``. - An `$exclude` it cannot read, or one beside a `$select`: merge it in, each field as `field: false`. - A to-one onto a composite key (declare a column per key and pair each in `references`), and a to-one whose `Id` is not a declared column. - A property whose type maps to no column (`Json`, a vector, a mixed union), a key under a computed name, and a nullable column’s property with no written type. - A `@Field`/`@Id` with no `type`, and a relation with no target: declare the column as a builder (`f.string()`) and pass the target first (`@ManyToOne(() => Target)`). - `Relation`, which uql no longer exports: write the property’s type without it, and drop the import. - A definer on a decorated class (`defineIndex(Post, ...)`), and `@Entity`’s `fields`, `relations`, `hooks` and `extends`: each is a decorator, or the class’s own `extends`, now. - A column option it cannot write as a method: a `shape`, which a JSON payload no longer takes (write a Standard Schema), or a flag such as `unique: isUnique` that no literal states. - A file that already declares a name the codemod would import (`sql`, `refs`, `idKey`, `f`, a renamed export), which it leaves unchanged. - A branded string id’s column, `f.uuid()` or `f.string()`. `f.uuid()` is a native column type and may need a migration. - `tsconfig.json`, which it only reads: remove `experimentalDecorators` and `emitDecoratorMetadata`, and change a `target: esnext`, which leaves decorators untransformed, to any dated target. A config that `extends` another is reported so you check its base. `import 'reflect-metadata'` is harmless and stays. # AI & RAG > Build the retrieval step of a RAG feature with UQL, from storing embeddings to picking the context for a model. Source: https://uql-orm.dev/ai-semantic-search This guide builds the retrieval half of a RAG (retrieval-augmented generation) feature: store documents with their embeddings, pick the passages closest to a question, and hand them to a model. An embedding is a column and similarity is a sort, so it is all ordinary UQL queries, with no separate search service to keep in sync. For every operator, metric, index option and engine difference, see the [semantic search reference](https://uql-orm.dev/querying/semantic-search.md). ## 1. Store a vector per row A vector field is `@Field(f.vector(dimensions))`, its dimensions matching your embedding model. Add a vector index so search does not scan every row: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (article, index) => [ index([article.embedding], { type: 'hnsw', distance: 'cosine' }), ], }) export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) category?: string | null; @Field(f.string().nullable()) body?: string | null; @Field(f.vector(1536).nullable()) embedding?: number[] | null; } ``` Index types differ by engine: `hnsw` works on Postgres, PGlite, CockroachDB, libSQL and Turso Cloud, and MariaDB takes `vector`. MySQL and SQL Server have none, and plain SQLite and D1 fall back to exact search. Check [entity setup](https://uql-orm.dev/querying/semantic-search.md#entity-setup) and [vector indexes](https://uql-orm.dev/querying/semantic-search.md#vector-indexes) for yours before you migrate. ## 2. Ingest content Embed each document with any embedding model and insert it with its vector: ```ts import { pool } from './uql.config.js'; import { Article } from './entities.js'; const body = 'UQL is a TypeScript ORM ...'; await pool.insertOne(Article, { title: 'What is UQL?', category: 'docs', body, embedding: await embed(body), }); ``` Long documents retrieve better split into passages, one row and one embedding each. With a `Passage` entity related to its document, you can also [rank documents by their best passage](https://uql-orm.dev/querying/semantic-search.md#ranking-by-a-related-row). ## 3. Retrieve the context Filter by distance with `$near` so weak matches never reach the model, rank what is left with a `$vector` sort, and project the distance so you can log it: ```ts const question = 'Does UQL support vector search?'; const queryVec = await embed(question); const context = await pool.findMany(Article, { $select: { title: true, body: true }, $where: { category: 'docs', embedding: { $near: { $vector: queryVec, $distance: 'cosine', $lt: 0.35 }, }, }, $sort: { embedding: { $vector: queryVec, $distance: 'cosine', $project: 'distance' }, }, $limit: 8, $candidates: 100, }); ``` With cosine distance, lower is closer, so `$lt` is the cut-off; start around `0.35` and tune it against real questions. The `category` filter narrows the candidates before ranking ([combined with filtering](https://uql-orm.dev/querying/semantic-search.md#combined-with-filtering)). `$candidates` makes an approximate index look further so the threshold does not leave you short of rows, applied for this query alone ([tuning recall](https://uql-orm.dev/querying/semantic-search.md#tuning-recall)). > **On MongoDB Atlas, threshold in your app** > > Atlas cannot filter by distance, so `$near` throws there. Drop the `$near`, keep `$project`, and keep the rows under the same cut-off in your app: the projected field is the distance, as on the SQL engines. ## 4. Ask the model Pass the retrieved passages to the model along with the question: ```ts const prompt = [ 'Answer using only the context below.', ...context.map((article) => `## ${article.title}\n${article.body}`), `Question: ${question}`, ].join('\n\n'); const answer = await generate(prompt); // any chat model ``` When `context` is empty, nothing was close enough. Answer that you do not know instead of letting the model guess. # AI Coding Agents > One prompt sets UQL up in your project for any coding agent, with the UQL skill and the docs MCP server, so it writes UQL for the version you installed. Source: https://uql-orm.dev/ai-agents Paste this into any coding agent, or open it in Cursor or in Claude Code for VS Code, which open it in the project you have open and send nothing until you do. It works in a new project and in one that already uses UQL. ```text title="Setup prompt" Set up UQL (uql-orm) in this project. 1. If uql-orm (npm package) isn't installed, install it and the driver for this project's database. If you can't tell which database, ask me. 2. Add this line to AGENTS.md: To know how UQL ORM works, read `node_modules/uql-orm/skills/uql-orm/SKILL.md`: it matches the installed uql-orm. 3. Add https://uql-orm.dev/mcp as an MCP server named uql for this agent: HTTP transport, no key. 4. If there's no uql.config.ts yet, read the skill and follow it to: - create uql.config.ts, reading the database credentials from environment variables - add one entity that fits this project - write one typed query that uses it 5. Ask me before you change the database. 6. Run the type checker, then tell me what you changed. ``` It installs UQL if the project lacks it, and gives the agent two things: the UQL skill, which teaches it to write UQL, and the docs, which it looks up as it goes. It asks before it changes the database. ## Or set it up yourself ### The skill `uql-orm` ships an [agent skill](https://uql-orm.dev/.well-known/agent-skills/uql-orm/SKILL.md). It covers how a query is shaped, how entities are declared, the mistakes agents make most, and where each detail lives in these docs. The skill is inside the package, so each `uql-orm` upgrade brings the skill for that version. Add this line to your project’s `AGENTS.md`, which Claude Code, Codex, Cursor, GitHub Copilot and most other agents read on their own: ```md title="AGENTS.md" To know how UQL ORM works, read `node_modules/uql-orm/skills/uql-orm/SKILL.md`: it matches the installed uql-orm. ``` ### The docs over MCP The docs MCP server at `https://uql-orm.dev/mcp` adds search, so the agent finds the right page without knowing its URL. It needs no key, and its three tools are read-only: | Tool | What it answers | | - | - | | `search_docs` | The pages for a topic, most relevant first, with the passage that matched | | `get_doc` | One page as Markdown, by the path `search_docs` gives or by its URL | | `read_skill` | The skill above, for a client that cannot install one | Add it to your agent: Claude Code: ```sh claude mcp add --transport http uql https://uql-orm.dev/mcp ``` Cursor: [Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=uql\&config=eyJ1cmwiOiJodHRwczovL3VxbC1vcm0uZGV2L21jcCJ9) VS Code: [Install in VS Code](vscode:mcp/install?%7B%22name%22%3A%22uql%22%2C%22url%22%3A%22https%3A%2F%2Fuql-orm.dev%2Fmcp%22%7D) For VS Code's own chat. Claude Code in VS Code takes the Claude Code command. Codex: ```sh codex mcp add uql --url https://uql-orm.dev/mcp ``` Claude.ai: In **Customize**, then **Connectors**, add a custom connector named `uql` with the URL `https://uql-orm.dev/mcp`. Claude Desktop uses the same connectors. Other: Add `https://uql-orm.dev/mcp` as an MCP server named `uql`: HTTP transport, no key. ### The docs by URL, with nothing to set up Every page here answers with Markdown when an agent asks for it, as Claude Code and Cursor do. Each page is also Markdown at its URL plus `.md`, such as [`/querying/relations.md`](https://uql-orm.dev/querying/relations.md), and [`/llms.txt`](https://uql-orm.dev/llms.txt) indexes them all. An agent that can fetch URLs needs only that index: ```text To know how UQL ORM works, read https://uql-orm.dev/llms.txt and fetch the pages for the task. ``` To load the whole site at once, [`/llms-full.txt`](https://uql-orm.dev/llms-full.txt) is every page in one file. # FAQ > Short answers to common questions about UQL, from setup to troubleshooting. Source: https://uql-orm.dev/faq ## Getting started ### What is UQL, and why would I pick it? UQL is a TypeScript ORM whose queries are plain, typed JSON objects instead of method chains. Your entities, classes or [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) data, are the schema, with no codegen or build step. One query runs on PostgreSQL, CockroachDB, MySQL, MariaDB, SQL Server, the SQLite family (libSQL, Turso, D1) and MongoDB, and travels over HTTP to the browser unchanged. It ships [vector search](https://uql-orm.dev/ai-semantic-search.md), [multi-tenant filters](https://uql-orm.dev/multi-tenancy.md), [soft delete](https://uql-orm.dev/entities/soft-delete.md), [migrations](https://uql-orm.dev/migrations.md), an [HTTP API](https://uql-orm.dev/http.md) and a [browser client](https://uql-orm.dev/browser.md) in one package, and adds the least measured time and memory over the driver in our [PostgreSQL benchmark](https://uql-orm.dev/benchmark.md). The [comparison page](https://uql-orm.dev/comparison.md) sets it beside Drizzle, MikroORM, Prisma and TypeORM. ### Where does the name come from? Unified Query Language: one typed JSON syntax, modeled on MongoDB’s, for SQL databases and MongoDB alike. It is the [first of five things a perfect ORM should have](https://uql-orm.dev/blog/in-search-of-the-perfect-orm.md). ### Is it production-ready? Yes. It runs in production behind [Variability.ai](https://variability.ai), an AI meeting notetaker by UQL’s author. ### Who maintains it, and where is it going? UQL is maintained by its author, [Roger Padilla](https://github.com/rogerpadilla), in the open on [GitHub](https://github.com/rogerpadilla/uql). The [roadmap](https://github.com/rogerpadilla/uql/blob/main/architecture/roadmap.md) lists what is planned, in build order. ## Setup ### Which driver do I install? Your database’s own: `pg`, `mysql2`, `mariadb`, `better-sqlite3`, `mssql`, `mongodb`, and so on. [Which pool](https://uql-orm.dev/pool.md#which-pool) pairs each entry point with its driver. On Bun, `bun:sql` (PostgreSQL, CockroachDB, MySQL, MariaDB) and `bun:sqlite` need none, and D1 takes the Worker’s binding. ### Do I need special TypeScript settings? No decorator flags or polyfills: UQL uses [standard TC39 decorators](https://uql-orm.dev/entities/basic.md). `module`, `target` and `lib` matter, as [Requirements](https://uql-orm.dev/getting-started.md#requirements) explains. ### Can I use UQL from JavaScript? Yes, with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md), which declares an entity as data, its row type derived. The CLI reads a `uql.config.js` like a `.ts` one. Decorators in a `.js` file need Bun or a transpiler such as Babel, SWC or esbuild. ## Queries ### What does “JSON-native” mean? A query is a plain object, so you can `JSON.stringify()` it, send it over HTTP, cache it, or share it between backend and frontend: ```ts import type { Query } from 'uql-orm'; import { User } from './shared/models/index.js'; const query: Query = { $select: { id: true, name: true }, $where: { email: { $endsWith: '@uql-orm.dev' } }, $sort: { createdAt: 'desc' }, $limit: 10, }; ``` The [API](https://uql-orm.dev/http.md) serves your entities over HTTP, tRPC or oRPC, and the [client](https://uql-orm.dev/browser.md) sends these queries to it from the browser. ### What is the difference between `$select` and `$populate`? `$select` picks scalar fields. `$populate` loads relations, in the same statement: ```ts const query: Query = { $select: { id: true, name: true }, $populate: { posts: { $select: { title: true } } }, }; ``` ### How do I filter on a relation or a JSON property? A relation filters by its fields, and a JSON column by dot-paths. Both work on every SQL dialect: ```ts await pool.findMany(Post, { $where: { author: { name: 'Roger' } } }); await pool.findMany(Company, { $where: { 'settings.region': 'eu' } }); ``` `$size` filters by how many related rows exist, as a `COUNT(*)` subquery that never loads them: ```ts await pool.findMany(MeasureUnitCategory, { $where: { measureUnits: { $size: { $gte: 2 } } }, }); ``` ### What is the difference between `f.string()` and `.columnType()`? The builder (`f.string()`, `f.uuid()`, …) is the portable type the compiler checks the property against. A foreign key is `f.references(() => User)` and inherits the target key’s type, and a relation aggregate is typed by its aggregate. `.columnType()`, or `f.column('')`, overrides the SQL type it maps to. See [Column types](https://uql-orm.dev/entities/basic.md#column-types). ### Is UQL safe from SQL injection? Yes. Every value is bound as a parameter, and table and column names come from entity metadata, never the query. [`sql`](https://uql-orm.dev/querying/raw-sql.md) is the deliberate opt-out. As a tagged template it binds every interpolated value, and columns come from `refs`: ```ts import { sql, refs } from 'uql-orm'; const item = refs(Item); sql`${item.stock} - ${quantity}`; ``` Its callback form does not bind, so never build one from user input. Bind values there with `ctx.addValue()`. UQL does not use server-side prepared statements, so transaction-mode poolers such as [Supabase’s](https://uql-orm.dev/supabase.md) work without extra configuration. ## Schema and migrations ### Do I write migrations by hand? No. Edit the entity, run `npx uql-migrate generate:entities ` to write a migration from the diff, and `up` to apply it. For your own SQL, `generate ` creates an empty migration. See [Migrations](https://uql-orm.dev/migrations.md). ### Can UQL create the database from my entities? Yes, with `sync`: ```bash npx uql-migrate sync --dry-run # print the DDL npx uql-migrate sync # create missing tables, columns and indexes ``` By default `sync` only adds: it drops no column and changes no type unless you pass `--unsafe`. Use it on prototypes and test databases, and [generated migrations](https://uql-orm.dev/migrations.md#from-entities-to-the-database) once the data matters. `generate:from-db` goes the other way, from tables to entities. ### Should I use a lifecycle hook or a trigger? A [lifecycle hook](https://uql-orm.dev/entities/lifecycle-hooks.md) runs in your app on UQL’s own writes, and can call a queue or another service. A [trigger](https://uql-orm.dev/entities/triggers.md) runs in the database, so it also fires on raw SQL, data migrations and other services’ writes. Use a trigger for data every write must produce, such as audit rows, and a hook for application logic. Triggers are SQL-only: on MongoDB, a write to an entity that declares one is refused. ### How do soft delete and multi-tenancy work? Mark a field `.softDelete()`. Deletes then set it, reads hide those rows, `restoreOneById` and `restoreMany` bring them back, and `{ hardDelete: true }` removes them for good. Soft delete is one [query filter](https://uql-orm.dev/querying/filters.md), a named `$where` that applies by default. A `security` filter resolved from a per-request context gives you [multi-tenancy](https://uql-orm.dev/multi-tenancy.md): it covers every query, relations and cascades included, a client cannot bypass it, and it fails closed without a context. ### How does vector search work? Declare `@Field(f.vector(dimensions))` and sort with `$vector`. It runs on PostgreSQL and PGlite (pgvector), CockroachDB, MariaDB, SQLite (sqlite-vec), libSQL/Turso, SQL Server 2025 and MongoDB Atlas. Start with [AI & RAG](https://uql-orm.dev/ai-semantic-search.md); [Semantic Search](https://uql-orm.dev/querying/semantic-search.md) is the reference. ## Troubleshooting ### My decorators do not work - `target` must not be `esnext` ([Requirements](https://uql-orm.dev/getting-started.md#requirements)). - A bundler that compiles TypeScript itself must support standard decorators. esbuild, SWC, Babel (`version: '2023-11'`) and Bun do. Oxc, Vite 8’s own transformer, does not: add a plugin for one of the others. - Next.js compiles legacy decorators only, so it needs [a Babel config](https://uql-orm.dev/nextjs.md#decorators). - On Node, `uql-migrate` needs `tsx` to import a TypeScript config ([Running the CLI](https://uql-orm.dev/migrations.md#running-the-cli)). ### “Cannot find module ‘uql-orm’” Set `"module": "nodenext"`, or `"preserve"` behind a bundler, so TypeScript reads the package’s `exports`. If Node runs the output, set `"type": "module"` in `package.json`. Under `nodenext`, relative imports end in `.js`. ### “Cannot find global type ‘AsyncDisposable’” Add `"lib": ["esnext"]`. `await using` needs it, and no dated target’s default lib has it. ### “Connection refused” Check that the database is running and exists (`createdb your_db`), the credentials in `uql.config.ts`, and on Docker, the network and port mappings. ### A query is slow Index the columns you filter by, page with `$limit` and `$skip`, and use [`findManyStream`](https://uql-orm.dev/querying/streaming.md) for large reads. [Query logging](https://uql-orm.dev/logging.md) shows the SQL and its timing. # Drizzle vs MikroORM vs Prisma vs TypeORM vs UQL > Drizzle vs MikroORM vs Prisma vs TypeORM vs UQL, the same queries, relations and migrations side by side, with a feature matrix and database support. Source: https://uql-orm.dev/comparison Here are the most common ORM operations, written in Drizzle, MikroORM, Prisma, TypeORM and UQL. A note below each example says how they differ. | Library | Version | | - | - | | [Drizzle](https://orm.drizzle.team) | `0.45.4` | | [MikroORM](https://mikro-orm.io) | `7.2.8` | | [Prisma](https://www.prisma.io) | `7.10.1` | | [TypeORM](https://typeorm.io) | `1.1.2` | | UQL | `0.114.3` | ## Entity definition ```ts title="Drizzle" // Dialect-specific helpers, one import per column type. import { pgTable, serial, varchar, integer } from 'drizzle-orm/pg-core'; export const users = pgTable('users', { id: serial('id').primaryKey(), email: varchar('email', { length: 255 }).unique(), name: varchar('name', { length: 255 }), companyId: integer('company_id').references(() => companies.id), }); ``` ```ts title="MikroORM" // `defineEntity`; decorators live in a separate package. import { defineEntity, p } from '@mikro-orm/core'; const UserSchema = defineEntity({ name: 'User', properties: { id: p.integer().primary(), email: p.string().unique(), name: p.string(), company: () => p.manyToOne(Company), }, }); export class User extends UserSchema.class {} UserSchema.setClass(User); ``` ```prisma title="Prisma" // Its own language, with a generate step. model User { id Int @id @default(autoincrement()) email String @unique name String? companyId Int company Company @relation(fields: [companyId], references: [id]) } ``` ```ts title="TypeORM" // Needs `experimentalDecorators` and `emitDecoratorMetadata`, unless you use `EntitySchema`. import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column({ unique: true }) email: string; @Column() name: string; @ManyToOne(() => Company) company: Company; } ``` ```ts title="UQL" // Standard TC39 decorators, no compiler flags. Or no decorators: `defineEntity` (/entities/define-entity). import { f, Entity, Field, ManyToOne } from 'uql-orm'; @Entity() export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().unique()) email!: string; @Field(f.string().nullable()) name?: string | null; @Field(f.references(() => Company)) companyId!: number; @ManyToOne(() => Company, { references: (user) => user.companyId }) company?: Company; } ``` Only Prisma uses its own schema language. --- ## Select and filter Ten users aged 18 to 65 whose name starts with “A”, newest first, with only two columns. ```ts title="Drizzle" // Closest to SQL. A function per operator, so the filter cannot be serialized. import { and, desc, gte, ilike, lte, notInArray } from 'drizzle-orm'; const results = await db .select({ id: users.id, name: users.name }) .from(users) .where( and( gte(users.age, 18), lte(users.age, 65), ilike(users.name, 'A%'), notInArray(users.status, ['banned', 'inactive']), ), ) .orderBy(desc(users.createdAt)) .limit(10); ``` ```ts title="Prisma" // Operators typed per field. Case-insensitive `mode` works only on PostgreSQL, CockroachDB and MongoDB. const results = await prisma.user.findMany({ select: { id: true, name: true }, where: { age: { gte: 18, lte: 65 }, name: { startsWith: 'A', mode: 'insensitive' }, status: { notIn: ['banned', 'inactive'] }, }, orderBy: { createdAt: 'desc' }, take: 10, }); ``` ```ts title="TypeORM" // Plain on equality; any other operator is a function inside the object. import { Between, ILike, In, Not } from 'typeorm'; const results = await manager.find(User, { select: { id: true, name: true }, where: { age: Between(18, 65), name: ILike('A%'), status: Not(In(['banned', 'inactive'])), }, order: { createdAt: 'DESC' }, take: 10, }); ``` ```ts title="UQL" // Operators typed per field: `{ age: { $like: '3%' } }` fails to compile. // `$istartsWith` and `$iincludes` work on every dialect. const results = await pool.findMany(User, { $select: { id: true, name: true }, $where: { age: { $gte: 18, $lte: 65 }, name: { $istartsWith: 'A' }, status: { $nin: ['banned', 'inactive'] }, }, $sort: { createdAt: 'desc' }, $limit: 10, }); ``` MikroORM’s `em.find` takes a plain object too, but accepts any operator on any field, so `{ age: { $like: '3%' } }` compiles, and its `$ilike` is PostgreSQL-only. Only MikroORM’s, Prisma’s and UQL’s queries survive `JSON.stringify`, so you can build them, store them or send them over the wire. --- ## Relations Users with only their published posts. ```ts title="Drizzle" // The nested `where` is a callback, to-many only. Object filters and to-one `where` are in the 1.0 beta. const results = await db.query.users.findMany({ columns: { id: true, name: true }, with: { posts: { columns: { title: true }, where: (post, { eq }) => eq(post.published, true), }, }, }); ``` ```ts title="Prisma" // Inline on the relation: a to-many or an optional to-one takes `where`. const results = await prisma.user.findMany({ select: { id: true, name: true, posts: { select: { title: true }, where: { published: true } }, }, }); ``` ```ts title="UQL" // The condition sits on the join, at any depth, to-one or to-many. `$required: true` makes it an INNER JOIN. const results = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { posts: { $select: { title: true }, $where: { published: true } }, }, }); ``` TypeORM’s `find()` cannot filter a relation without also filtering the parents, so it takes a QueryBuilder `leftJoinAndSelect` with a string condition. MikroORM’s `populateFilter` does it as a LEFT JOIN, so users with no matching posts stay. --- ## Aggregation Users created since 2025, counted per status with their average age, keeping groups whose average age is over 30. ```ts title="Drizzle" // SQL helpers, one import per operator. import { count, avg, gt, gte, desc } from 'drizzle-orm'; const results = await db .select({ status: users.status, count: count(), avgAge: avg(users.age) }) .from(users) .where(gte(users.createdAt, new Date('2025-01-01'))) .groupBy(users.status) .having(({ avgAge }) => gt(avgAge, 30)) .orderBy(desc(count())) .limit(10); ``` ```ts title="Prisma" // Declarative and typed, but keyed by operator (`_avg`, `_count`). SQL only. const results = await prisma.user.groupBy({ by: ['status'], where: { createdAt: { gte: new Date('2025-01-01') } }, _count: { status: true }, _avg: { age: true }, having: { age: { _avg: { gt: 30 } } }, orderBy: { _count: { status: 'desc' } }, take: 10, }); ``` ```ts title="UQL" // Plain JSON on every SQL engine and MongoDB, typed from `$group` through to the rows. const results = await pool.aggregate(User, { $where: { createdAt: { $gte: new Date('2025-01-01') } }, $group: { status: true }, $select: { count: { $count: '*' }, avgAge: { $avg: { age: true } } }, $having: { avgAge: { $gt: 30 } }, $sort: { count: -1 }, $limit: 10, }); ``` Only Prisma and UQL aggregate declaratively. MikroORM and TypeORM need their QueryBuilder: MikroORM checks `having` against the aliases but returns the values as `unknown`, and TypeORM takes string `groupBy` and `having` and returns `any[]`. In UQL, [soft-delete, default and `security` filters](https://uql-orm.dev/querying/filters.md) apply to `aggregate()` too, so tenant scoping covers grouped queries. --- ## Counting A total, a per-user post count to sort by, and a cheap “does any exist”. ```ts title="Prisma" // `_count` selects, filters and sorts relation tallies. No cheap existence check or estimate. const results = await prisma.user.findMany({ select: { id: true, _count: { select: { posts: true } } }, orderBy: { posts: { _count: 'desc' } }, take: 10, }); ``` ```ts title="UQL" const results = await pool.findMany(User, { $count: { posts: true }, // or a filter of its own: { posts: { $where: { ... } } } $sort: { posts: { $count: -1 } }, // the users with the most posts $limit: 10, }); await pool.exists(User, { $where: { name: 'Jane' } }); // stops at the first match await pool.count(User, { $limit: 1000 }); // capped: "1,000+ matches", no full scan await pool.estimatedCount(User); // the engine's own statistic, no scan ``` Drizzle’s `db.$count()` is a query of its own, and a per-parent count is an `sql` subquery you write in `extras` and repeat to sort by. MikroORM has `em.count` and `em.findAndCount` but no existence check, and `collection.loadCount()` runs one query per parent. TypeORM has `count` and `exists`, but a per-parent count is a QueryBuilder GROUP BY returning raw rows you merge yourself. In Prisma and UQL a relation count is part of the read: filtered and sortable with no subquery. UQL’s `estimatedCount` is approximate and whole-table; see [Counting](https://uql-orm.dev/querying/counting.md). Its `findManyAndCount` reads a page and its total in one SQL statement in most cases, so the two agree. --- ## Computed fields A `fullName` built from two columns, usable in a filter. ```ts title="Drizzle" // A `sql` expression, restated in every query. A `generatedAlwaysAs` column is the reusable form, but needs a migration. import { sql } from 'drizzle-orm'; const results = await db .select({ id: users.id, fullName: sql`CONCAT(${users.firstName}, ' ', ${users.lastName})`, }) .from(users); ``` ```ts title="MikroORM" // A SQL formula: selects, filters and sorts like a column, no migration. import { defineEntity, p } from '@mikro-orm/core'; const UserSchema = defineEntity({ name: 'User', properties: { firstName: p.string(), lastName: p.string(), fullName: p.formula( (cols) => `CONCAT(${cols.firstName}, ' ', ${cols.lastName})`, ), }, }); ``` ```ts title="Prisma" // No database-side option. `$extends({ result })` computes in JS, so you cannot filter or sort by it. const users = await prisma.user.findMany(); const results = users.map((u) => ({ ...u, fullName: `${u.firstName} ${u.lastName}`, })); ``` ```ts title="UQL" // Inlined into SELECT, WHERE and ORDER BY, or a real column with `.stored()`. // You write the SQL, so portability is up to you. import { Computed, f, sql } from 'uql-orm'; @Entity() class User { @Field(f.string()) firstName!: string; @Field(f.string()) lastName!: string; @Computed((user) => f.string().as(sql`CONCAT(${user.firstName}, ' ', ${user.lastName})`), ) readonly fullName!: string; } ``` MikroORM, TypeORM and UQL declare the expression on the entity, so you can filter by it with no schema change. TypeORM’s `@VirtualColumn` is inlined into SELECT and WHERE but not ORDER BY. A value computed after the fetch, as in Prisma, cannot be filtered or sorted in the database. --- ## Mutations One insert and one bulk update. ```ts title="Drizzle" // You get what the database returned. import { eq } from 'drizzle-orm'; const [user] = await db.insert(users).values({ name: 'Jane' }).returning(); await db .update(users) .set({ status: 'archived' }) .where(eq(users.status, 'inactive')); ``` ```ts title="MikroORM" // Nothing is written until `flush` runs. const user = em.create(User, { name: 'Jane' }); await em.flush(); await em.nativeUpdate(User, { status: 'inactive' }, { status: 'archived' }); ``` ```ts title="UQL" // Cardinality is in the method name. An insert returns the id, or the row with `{ returning: true }`. const id = await pool.insertOne(User, { name: 'Jane' }); await pool.updateMany( User, { $where: { status: 'inactive' } }, { status: 'archived' }, ); ``` MikroORM waits for a flush; the others write right away. Prisma’s `create` returns the record, and TypeORM’s `save` inserts or updates depending on the id. Batch inserts differ most. UQL’s [`insertMany`](https://uql-orm.dev/querying/methods.md#insert-ids) returns an id per row on every database, accepts rows with different columns in one statement, and splits a batch past the driver’s parameter limit. Prisma’s `createMany` returns only a count (`createManyAndReturn` returns rows, but not on MySQL). On MySQL, which has no `RETURNING`, Drizzle, MikroORM and TypeORM count up from the one reported `insertId`, so a batch mixing explicit and generated ids gets wrong ids; UQL sends those rows in a statement of their own. --- ## Soft delete Drizzle and Prisma have no built-in soft delete: you add a `deletedAt` column and filter it in every query, so one missed clause leaks deleted rows. MikroORM hides them with a default filter (`cond: { deletedAt: null }`), but turning `em.remove()` into an update needs an `onFlush` subscriber. ```ts title="TypeORM" // Built-in soft delete, restore and read filtering. @Entity() export class User { @PrimaryGeneratedColumn() id: number; @DeleteDateColumn() deletedAt: Date; } await manager.softDelete(User, id); ``` ```ts title="UQL" import { f, Entity, Field } from 'uql-orm'; // Marking the field turns on soft delete for every read and delete. @Entity() export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.date().nullable().softDelete()) deletedAt?: Date | null; } await pool.deleteOneById(User, id); // soft delete await pool.restoreOneById(User, id); // bring it back await pool.deleteOneById(User, id, { hardDelete: true }); // remove for good ``` In UQL, soft delete is one use of [query filters](https://uql-orm.dev/querying/filters.md). --- ## Indexes One email per tenant, ignoring soft-deleted rows: a composite, unique, partial index. ```prisma title="Prisma" // Preview feature `partialIndexes`. Checked, but only literals, `null` and `{ not }`; else `raw("...")`. model User { id Int @id @default(autoincrement()) email String tenantId Int deletedAt DateTime? @@unique([email, tenantId], where: { deletedAt: null }) } ``` ```ts title="UQL" // Columns and `where` are checked against the entity: `where: { deletedAt: 'yes' }` fails to compile. import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (user, index) => [ index([user.email, user.tenantId], { unique: true, where: { deletedAt: null }, }), ], }) export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string()) email!: string; @Field(f.number()) tenantId!: number; @Field(f.date().nullable().softDelete()) deletedAt?: Date | null; } ``` All five can declare this index; they differ in what gets checked. Drizzle types the columns but takes the predicate as an `sql` fragment. TypeORM takes columns and predicate as strings (`where: '"deletedAt" IS NULL'`). MikroORM checks the property names but not its `where` object. MySQL has no partial indexes. MikroORM emulates one with a functional index, Prisma rejects the `where`, and UQL throws when it generates the migration instead of indexing the whole table. See [Rename Safety](https://uql-orm.dev/rename-safety.md) for which declarations follow a rename, and [Indexes](https://uql-orm.dev/entities/indexes.md) for every index option. --- ## JSON | JSON capability | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Nested / dot-notation JSON filtering | ❌¹ | ✅² | ✅³ | 🔌⁴ | ✅ | | Atomic JSON key merge/update | ❌¹ | ❌² | 🔌⁴ | 🔌⁴ | ✅ | | Atomic JSON key removal (`unset`) | ❌¹ | ❌² | ❌ | ❌ | ✅ | | Atomic JSON array update (`push`, `pull`, `addToSet`) | ❌¹ | ❌² | ❌ | ❌ | ✅ | | JSON array query operators (`size`, `all`, `elemMatch`) | ❌¹ | ✅² | 🔌⁴ | 🔌⁴ | ✅ | | Same JSON API on every SQL dialect | ❌ | ✅² | ❌ | ❌ | ✅ | | Declared index on a JSON path | 🔌⁵ | 🔌⁵ | 🔌⁵ | 🔌⁵ | ✅ | ¹ Raw SQL. ² One JSON query API across SQL dialects (nested objects, `$elemMatch`), but updates replace the whole object. ³ On some connectors, with connector-specific limits. ⁴ Through dialect-specific SQL or query-builder escape hatches. ⁵ As a raw, unchecked expression index. UQL’s index reads the path off the column’s ref, checks it against the field’s type, and emits a path index on PostgreSQL, CockroachDB, SQLite, MySQL and MongoDB; MariaDB throws. See [JSON / JSONB](https://uql-orm.dev/querying/json.md) for the generated SQL and minimum dialect versions. --- ## Semantic search The ten items closest to a query embedding. ```ts title="Drizzle" // pgvector types, distance helpers and HNSW/IVFFlat indexes. PostgreSQL only. import { cosineDistance } from 'drizzle-orm'; const results = await db .select() .from(items) .orderBy(cosineDistance(items.embedding, queryVector)) .limit(10); ``` ```ts title="UQL" // `$near` bounds the distance; `$candidates` widens the index search. const results = await pool.findMany(Item, { $select: { id: true, name: true }, $where: { embedding: { $near: { $vector: queryVector, $lt: 0.35 } } }, $sort: { embedding: { $vector: queryVector, $distance: 'cosine' } }, $limit: 10, }); ``` Drizzle’s helpers are pgvector only. MikroORM and TypeORM order by a hand-written SQL string, and Prisma needs `$queryRaw`. UQL’s query runs on PostgreSQL, CockroachDB, MariaDB, SQLite, libSQL/Turso, MSSQL and MongoDB Atlas, through each engine’s own vector functions. | Ability | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Native vector operator | ✅¹ | ❌ | ❌ | ❌² | ✅ | | Multi-dialect support | 🔌³ | 🔌³ | 🔌³ | 🔌³ | ✅ | | Index migration | ✅¹ | 🔌⁴ | 🔌⁵ | ❌ | ✅ | | Distance predicate | ✅⁶ | ❌ | ❌ | ❌ | ✅ | | Query-time ANN tuning | ❌⁷ | ❌⁷ | ❌⁷ | ❌⁷ | ✅ | | JSON path vectors | ❌ | ❌ | ❌ | ❌ | ✅ | ¹ pgvector only. `drizzle-kit generate` emits an index declared with `index().using('hnsw', ...)`. ² Maps the column (`@Column('vector', { length: 3 })`) on Postgres, MySQL/MariaDB and MSSQL, with no distance operator. ³ On any engine but PostgreSQL you write that engine’s SQL or pipeline by hand. ⁴ Through a raw index expression, not a declared vector index. ⁵ `@@index` on a vector column emits a plain B-tree; HNSW/IVFFlat need `Unsupported("vector(n)")` and a hand-written migration. ⁶ Drizzle’s helpers are SQL expressions, so they work in a `where`, on pgvector only. ⁷ UQL’s `$candidates` sets `hnsw.ef_search` or `ivfflat.probes` for the query. With the others you run `SET LOCAL` yourself inside a transaction. --- ## Full-text search Listings matching a search term, best match first. ```ts title="Drizzle" // No full-text API: `sql` fragments, PostgreSQL only. import { sql } from 'drizzle-orm'; const document = sql`to_tsvector('spanish', ${listings.title} || ' ' || ${listings.description})`; const query = sql`websearch_to_tsquery('spanish', ${term})`; const results = await db .select() .from(listings) .where(sql`${document} @@ ${query}`) .orderBy(sql`ts_rank(${document}, ${query}) desc`); ``` ```ts title="Prisma" // Preview feature `fullTextSearchPostgres`. `search` filters and `_relevance` orders, repeating fields and term. No weights. const results = await prisma.listing.findMany({ where: { title: { search: term } }, orderBy: { _relevance: { fields: ['title', 'description'], search: term, sort: 'desc', }, }, }); ``` ```ts title="UQL" // Fields, language and weights come from one index, `{ type: 'fulltext', config: 'spanish' }`. const results = await pool.findMany(Listing, { $where: { $text: { $value: 'wireless keyboard' } }, $sort: { $text: { $project: 'score' } }, }); ``` UQL runs this query on PostgreSQL, CockroachDB, MySQL, MariaDB and MongoDB, and on SQLite once an FTS5 table exists. MikroORM filters with `$fulltext` across engines but cannot rank. TypeORM’s query is a `MATCH ... AGAINST` string on MySQL. | Ability | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Search operator | ❌¹ | ✅² | ✅³ | ❌⁴ | ✅ | | Relevance sort | ❌¹ | ❌ | ✅⁵ | ❌⁴ | ✅ | | Returns the score | ❌ | ❌ | ❌ | ❌ | ✅ | | Column weights | ❌ | 🔌⁶ | ❌ | ❌ | ✅ | | Index in migrations | ✅¹ | ✅² | ✅⁷ | ✅⁴ | ✅ | | One query on every engine | ❌ | 🔌² | 🔌³ | ❌ | ✅ | ¹ `sql` fragments, PostgreSQL only; `drizzle-kit` emits the GIN index. ² PostgreSQL, MySQL/MariaDB and MongoDB via a `type: 'fulltext'` index and `$fulltext`; SQLite needs a hand-made FTS5 table. On PostgreSQL the index uses `to_tsvector('simple', ...)`. ³ Preview feature, PostgreSQL and MySQL; the query syntax is the engine’s own. ⁴ `@Index({ fulltext: true })` builds a MySQL `FULLTEXT` index; query and ordering are strings. ⁵ `_relevance` on PostgreSQL and MySQL, repeating the fields and term. ⁶ PostgreSQL only, as `A` to `D` labels in a `tsvector` column you compute on every write. ⁷ `@@fulltext` on MySQL and MongoDB; a PostgreSQL index is hand-written SQL. --- ## Querying over HTTP With Drizzle, MikroORM, Prisma and TypeORM you write and maintain an API route per model, even where the query itself is a plain object. UQL serves the entities you list over one route per operation, and the browser sends the same query object: ```ts title="UQL" // Server import { createApi, toFetchHandler } from 'uql-orm/http'; const handler = toFetchHandler(createApi({ pool, include: [User] })); // Browser import { createClientQuerier, httpTransport } from 'uql-orm/browser'; const client = createClientQuerier(httpTransport('/api/v1')); const results = await client.findMany(User, { $where: { status: 'active' }, }); ``` The [API](https://uql-orm.dev/http.md) mounts on Hono, Elysia, Next.js, Bun, Workers or [Express](https://uql-orm.dev/express.md), or runs inside a [tRPC](https://uql-orm.dev/trpc.md) or [oRPC](https://uql-orm.dev/orpc.md) procedure, serving what each definition’s `wire` lets a client read and write, per entity and per field. Its typed [client](https://uql-orm.dev/browser.md) answers what the pool answers. --- ## Migrations ```bash title="UQL" # Diff your entities against the live database and write a timestamped migration. npx uql-migrate generate:entities add_nickname npx uql-migrate up # Or apply the same diff in place, with no file (dev databases). npx uql-migrate sync # Fail when the database has drifted from its entities. npx uql-migrate drift:check ``` MikroORM works the same way: entities are the source of truth, diffed against the live database. Prisma diffs its own schema language through a shadow database (`prisma migrate dev`). Drizzle diffs the TypeScript schema against a stored snapshot (`drizzle-kit generate`). TypeORM generates by diffing a live database (`typeorm migration:generate`). The in-place modes differ in safety. TypeORM’s `synchronize: true` and Prisma’s `db push` drop columns or change types to reach the target, as does MikroORM’s `schema:update` without `--safe`. [`uql-migrate sync`](https://uql-orm.dev/migrations.md#syncing-without-a-migration-file) only adds what is missing and refuses destructive changes unless you pass `--unsafe`. --- ## Streaming Streaming keeps memory flat when you export millions of rows: ```ts title="UQL" // An AsyncIterable of entities, on every driver. const results = await pool.findManyStream(User, { $where: { status: 'active' }, }); for await (const user of results) { await writeToCsv(user); } ``` MikroORM’s `em.stream()` is also an AsyncIterable on every driver, though `populate` throws on MongoDB. Drizzle’s `.iterator()` exists only on MySQL-family drivers (mysql2, PlanetScale, TiDB, SingleStore). TypeORM’s `.stream()` yields raw rows as a Node stream, and PostgreSQL also needs `pg-query-stream`. Prisma has no streaming, so you page through with a cursor yourself. --- ## Feature matrix The rest at a glance. ✅ built in, 🔌 through an extension or plugin, ❌ not available. | Capability | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Serializable queries (JSON) | ❌¹ | ✅² | ✅² | ❌³ | ✅ | | No custom DSL or codegen | ✅ | ✅ | ❌ | ✅ | ✅ | | Entities without decorators | ✅ | ✅ | ❌ | ✅ | ✅ | | Standard (TC39) decorators | ❌ | ✅ | ❌ | ❌ | ✅ | | Deep relation operators | ❌ | ✅ | ✅ | ❌ | ✅ | | Global query filters (scopes) | ❌ | ✅ | 🔌 | ❌ | ✅ | | Multi-tenancy | ❌⁴ | ✅⁴ | 🔌⁴ | ❌ | ✅⁴ | | Row-level locking (`FOR UPDATE`, `SKIP LOCKED`) | ✅ | ✅ | ❌⁵ | ✅ | ✅ | | Optimistic locking (version column) | ❌⁶ | ✅ | ❌⁶ | ✅ | ✅ | | Lifecycle hooks | ❌ | ✅ | 🔌 | ✅ | ✅ | | Database triggers declared on the entity | ❌ | ✅⁷ | ❌ | ❌ | ✅⁷ | | Works without a Unit of Work / flush cycle | ✅ | ❌ | ✅ | ✅ | ✅ | | Auto HTTP API and browser querier | ❌ | ❌ | ❌ | ❌ | ✅ | | CommonJS (`require`) | ✅ | ❌⁸ | ✅ | ✅ | ❌⁸ | | Bun built-in drivers (`bun:sql`, `bun:sqlite`) | ✅ | ❌ | ❌ | ❌ | ✅ | | Data browser / GUI | ✅⁹ | ❌ | ✅⁹ | ❌ | ❌ | | One query model across SQL and MongoDB | ❌ | ✅ | 🔌¹⁰ | ❌¹¹ | ✅ | ¹ Drizzle’s HTTP proxy sends compiled `{ sql, params, method }`, so the server can run a query but not validate, scope or recompile it. ² Until a value is not JSON: a `Date` becomes a string, a `BigInt` throws, and Prisma’s `Decimal` and MikroORM’s `RegExp` arrive as strings or `{}`. The server must revive them by hand. UQL reads a `Date` and a `bigint` back by the entity, both ways. ³ Equality filters serialize, but `Between`, `ILike`, `Not` and `In` are functions. ⁴ App-level, so raw SQL escapes them. UQL’s `security` filters cannot be bypassed and fail closed without a request context; MikroORM’s can be turned off per query, and Prisma’s client extensions bypassed. Drizzle declares Postgres row-level security policies (`pgPolicy`) instead. ⁵ A work queue needs `$queryRaw`. UQL’s is [`$lock`](https://uql-orm.dev/querying/locking.md). Every ORM needs a transaction for it, and none locks rows on SQLite. ⁶ You write the `where` and check the row count yourself. UQL checks the version in the `UPDATE` itself, on every engine. ⁷ Installed by schema sync and migrations, SQL engines only. MikroORM’s body is SQL you write per dialect; UQL’s [trigger](https://uql-orm.dev/entities/triggers.md) bodies are typed against the entities and rendered per engine. ⁸ UQL and MikroORM v7 are ESM-only. UQL also needs Node 22.18 or newer. ⁹ Drizzle Studio and Prisma Studio. With UQL, use your database’s own tools. ¹⁰ Mostly consistent, but connector capabilities and raw-query APIs differ. ¹¹ The MongoDB path behaves differently from SQL (QueryBuilder support, for one). --- ## Database support | Database | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Cloudflare D1 | ✅ | 🔌¹ | ✅ | ❌ | ✅ | | CockroachDB | ✅ | ✅ | ✅ | ✅ | ✅ | | LibSQL / Turso | ✅ | ✅ | ✅ | ❌ | ✅ | | MariaDB | ✅ | ✅ | ✅ | ✅ | ✅ | | MongoDB | ❌ | ✅ | ✅ | ✅ | ✅ | | MSSQL | ✅² | ✅ | ✅ | ✅ | ✅ | | MySQL | ✅ | ✅ | ✅ | ✅ | ✅ | | Neon Serverless | ✅ | 🔌³ | ✅ | 🔌³ | ✅ | | Oracle | ❌ | ✅ | ❌ | ✅ | ❌ | | PGlite | ✅ | ✅ | 🔌⁴ | 🔌⁴ | ✅ | | PostgreSQL | ✅ | ✅ | ✅ | ✅ | ✅ | | SQLite | ✅ | ✅ | ✅ | ✅ | ✅ | ¹ Experimental, through the SQL query builder. ² In the v1.0 beta, not a stable release. ³ No adapter: pass the `@neondatabase/serverless` pool to the PostgreSQL driver yourself (MikroORM’s `driverOptions`, TypeORM’s `driver`). ⁴ Through a third-party package (`pglite-prisma-adapter`, `typeorm-pglite`). --- ## Install footprint Disk size of each package alone, before adding a driver, measured on a fresh install. | | **Drizzle** | **MikroORM** | **Prisma** | **TypeORM** | **UQL** | | - | - | - | - | - | - | | Installed | 10.0 MB | 4.9 MB | 71.2 MB | 22.6 MB | **1.9 MB** | | Files | 2,691 | 1,154 | 94 | 3,664 | **483** | Packages: `drizzle-orm` 0.45.4, `@mikro-orm/postgresql` 7.2.5, `@prisma/client` 7.10.1, `typeorm` 1.1.2 (September 2026), `uql-orm` 0.106.1 (October 2026). A driver such as `pg` adds the same to each. 92% of `@prisma/client` is WebAssembly query compilers, one per engine. Per dialect, Prisma’s PostgreSQL compiler is 4.4 MB (`fast` build), against 48.1 kB gzipped for all of `uql-orm/postgres`. UQL is one package with no runtime dependencies. Its `fetch`-based drivers (Turso Cloud, Neon, Cloudflare D1) need no native binaries, so they fit edge bundles. [Zero Dependencies: what we deleted to fit on the edge](https://uql-orm.dev/blog/zero-dependencies.md)The full table, how it was measured, and what came out to get there. --- ## Benchmark The [benchmark](https://uql-orm.dev/benchmark.md) measures what each ORM adds over hand-written driver code on PostgreSQL. In the latest run UQL adds the least measured time on both `pg` and Bun SQL, the least memory ([129 KB per request, against 523 KB for Drizzle](https://uql-orm.dev/benchmark.md#memory)), and is the only entry that catches all twelve common mistakes at compile time. [Full Benchmark Results](https://uql-orm.dev/benchmark.md)Result tables, method, interactive charts, and how to reproduce them. [Rename Safety](https://uql-orm.dev/rename-safety.md)Six ORMs renaming a field, a foreign key and a relation: which indexes, checks, relations, queries and raw SQL follow. --- ## Try it ```sh npm install uql-orm ``` Then [add your database driver](https://uql-orm.dev/getting-started.md#1-install). Entities are plain classes and queries are plain JSON: nothing to generate, and no schema file to keep in sync. [Quick Start](https://uql-orm.dev/getting-started.md) [GitHub](https://github.com/rogerpadilla/uql) --- # TypeScript ORM Benchmark > What Drizzle, MikroORM, Prisma, Sequelize, TypeORM and UQL each cost per request against a real PostgreSQL, and which mistakes their types catch. Source: https://uql-orm.dev/benchmark The [open-source benchmark](https://github.com/rogerpadilla/ts-orm-benchmark) runs each ORM through the same PostgreSQL lifecycle: insert, read, update, read, nested read, delete, read. These are the numbers from its latest run. > PostgreSQL 18.6 (Homebrew), Bun 1.4.4, Apple M4 Max, November 2026. Median µs per operation over 250 rounds, after 125 warmup rounds, interleaved and rotated. Every median is ±2.9% or tighter at 95% confidence. *Versions: [Drizzle](https://orm.drizzle.team) 0.45.4 · [MikroORM](https://mikro-orm.io) 7.2.5 · [Prisma](https://www.prisma.io) 7.10.1 · [Sequelize](https://sequelize.org) 6.37.8 · [TypeORM](https://typeorm.io) 1.1.2 · [UQL](https://uql-orm.dev) 0.111.1.* ## Results **Adds** is what the ORM itself costs on top of the driver. The two `ref` rows are the floors: hand-written SQL with the rows mapped by hand. Bun SQL entries are measured against `bun sql`, the rest against `raw pg`. | # | Entry | Adds µs | Total µs | | - | - | - | - | | ref | *bun sql* | floor | 1306 | | ref | *raw pg* | floor | 1381 | | 1 | **UQL (bunSql)** | +430 | 1736 | | 1 | **Drizzle (bunSql)** | +480 | 1786 | | 1 | **UQL** | +503 | 1884 | | 2 | Drizzle | +558 | 1939 | | 5 | TypeORM | +703 | 2084 | | 6 | Sequelize | +1127 | 2508 | | 6 | Prisma | +1145 | 2526 | | 8 | MikroORM | +2033 | 3414 | Entries share a place when their confidence intervals overlap, meaning this run cannot tell them apart. Totals only span 2.0x, because every entry pays the same database cost. What the ORM itself adds spans 5x: 430µs for UQL (bunSql), 2033µs for MikroORM. Each entry is measured against its own driver’s floor, so a faster driver is never counted as the ORM’s win. Running the same UQL code on Bun SQL instead of `pg` saves 148µs, but only 73µs of that is UQL: the other 75µs is the gap between the two floors, free to anything on that driver. UQL keeps its share small by working out schema metadata once at startup, so nothing is looked up while a query runs, and by writing SQL straight into a string buffer, with no intermediate builder objects. ### Per step The three steps that move the most data. The [interactive charts](https://rogerpadilla.github.io/ts-orm-benchmark/chart.html) show all seven. | Entry (µs) | insert | read | nested | Total, 7 steps | | - | - | - | - | - | | *[bun sql](https://bun.sh/docs/api/sql)* | 440 | 207 | 230 | 1306 | | *[raw pg](https://node-postgres.com)* | 423 | 249 | 265 | 1381 | | [UQL (bunSql)](https://uql-orm.dev) | **496** | 278 | **411** | **1736** | | [Drizzle (bunSql)](https://orm.drizzle.team) | 521 | **276** | 460 | 1786 | | [UQL](https://uql-orm.dev) | 525 | 328 | 450 | 1884 | | [Drizzle](https://orm.drizzle.team) | 532 | 326 | 510 | 1939 | | [TypeORM](https://typeorm.io) | 580 | 410 | 431 | 2084 | | [Sequelize](https://sequelize.org) | 587 | 479 | 656 | 2508 | | [Prisma](https://www.prisma.io) | 1031 | 347 | 468 | 2526 | | [MikroORM](https://mikro-orm.io) | 579 | 900 | 1078 | 3414 | Columns: insert is INSERT 10 rows, returning ids; read is SELECT with WHERE, SORT, LIMIT 200; nested is SELECT 50 parents with their children. The biggest gap is MikroORM’s nested: 1078µs against 411-656µs for everyone else. The other 4 steps are asserted every round but not published: they are round trips with almost nothing in them, worth 529-857µs of each total and separating the field by at most 139µs. ### Two runtimes The same lifecycle on Bun and Node, from one Bun-built bundle, so the runtime is the only variable. Bun SQL entries are left out because that client exists only on Bun. > Bun 1.4.4, Node 24.20.0, all running the same bundled JavaScript, one at a time against the same database. PostgreSQL 18.6 (Homebrew), Apple M4 Max, November 2026. µs for a whole lifecycle, nearest-rank percentiles over 2000 rounds after 250 warmup, so a p99 is drawn from the 21 slowest rounds. | Entry (µs) | Bun p50 | Bun p99 | Node p50 | Node p99 | | - | - | - | - | - | | [raw pg](https://node-postgres.com) | **1272** | **6449** | 2973 | 10558 | | [UQL](https://uql-orm.dev) | **1689** | **7397** | 3908 | 12503 | | [Drizzle](https://orm.drizzle.team) | **1769** | **8339** | 4201 | 13909 | | [TypeORM](https://typeorm.io) | **1810** | **7075** | 4311 | 14419 | | [Sequelize](https://sequelize.org) | **2157** | **7626** | 5083 | 15216 | | [Prisma](https://www.prisma.io) | **2265** | **8170** | 5306 | 16300 | | [MikroORM](https://mikro-orm.io) | **3000** | **12323** | 8101 | 22692 | On `raw pg`, where the code is identical, the runtimes are 1701µs apart at p50 but 4109µs apart at p99: Bun leads both, and each p99 is 407% on Bun, 255% on Node above its own p50. Switching runtime moves any single entry by at most 5101µs at p50 (MikroORM), where switching ORM on one runtime moves it 1246-4164µs. Both are differences of measured medians, known to ±360µs and ±31µs, so read them as ranges rather than as a ranking. Ranked by what each ORM adds, every runtime agrees: UQL < Drizzle < TypeORM < Sequelize < Prisma < MikroORM. ### Memory What the same lifecycle allocates on Node, one process per entry. **Adds KB** is the heap allocated above the hand-written floor, per request. > PostgreSQL 18.6 (Homebrew), Node 24.20.0, Apple M4 Max, November 2026. Median KB allocated per step over 60 rounds after 60 warmup of a 7-step lifecycle. Rounds a garbage collection ran in are discarded, never corrected, and no entry lost more than 1% of its own (MikroORM). | Entry | insert | read | nested | Total KB | Adds KB | | - | - | - | - | - | - | | *[raw pg](https://node-postgres.com)* | 14 | 86 | 105 | 239 | floor | | [UQL](https://uql-orm.dev) | 55 | 112 | 88 | 368 | **+129** | | [Drizzle](https://orm.drizzle.team) | 141 | 250 | 243 | 762 | +523 | | [TypeORM](https://typeorm.io) | 126 | 295 | 503 | 1066 | +827 | | [Prisma](https://www.prisma.io) | 274 | 221 | 374 | 1076 | +837 | | [Sequelize](https://sequelize.org) | 100 | 425 | 590 | 1311 | +1072 | | [MikroORM](https://mikro-orm.io) | 83 | 1476 | 2089 | 3916 | +3677 | Above the floor the field spans 28.5x: 129KB for UQL, 3677KB for MikroORM, and nested opens it widest: MikroORM’s 2089KB against UQL’s 88KB. Almost none of it survives: another 60 lifecycles, collected either side, leave at most 36KB behind (Sequelize), identity maps included. What the table prices is collector pressure, not a resident set that grows. ## Type safety The benchmark also writes ordinary mistakes in each ORM’s own API and counts which ones the compiler rejects. A ✅ means the mistake failed to compile and its corrected version compiled clean. > Checked with TypeScript 7.0.2, 12 probes per entry. | Mistake | [Drizzle](https://orm.drizzle.team) | [MikroORM](https://mikro-orm.io) | [Prisma](https://www.prisma.io) | [Sequelize](https://sequelize.org) | [TypeORM](https://typeorm.io) | [UQL](https://uql-orm.dev) | | - | - | - | - | - | - | - | | Misspelled column in the projection | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | | Misspelled column in the filter | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | String value against a numeric column | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | Text operator against a numeric column | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Misspelled column in the sort | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | Sum over a text column | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | | Misspelled column inside a loaded relation | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | | Misspelled column in inserted data | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Required column left out of inserted data | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | | Number written into a text column | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Reading a column the projection left out | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | | Reading a misspelled column off a loaded relation | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **Caught** | 10 of 12 | 10 of 12 | 11 of 12 | 6 of 12 | 10 of 12 | **12 of 12** | UQL misses none; Sequelize misses 6 of the 12 its API can express. Every mistake here is caught by at least one entry. The copy with every mistake corrected compiles clean, so a red mark is a missing check, never a broken file. Columns are alphabetical, not ranked. The queries behind each mark are [in the benchmark](https://github.com/rogerpadilla/ts-orm-benchmark/tree/main/type-safety), and [Type Safety](https://uql-orm.dev/type-safety.md) lets you try them in an editor. ## Method Every entry defines the same `Company` and `User`, runs the same seven steps through its own idiomatic API, and gets one connection with no pool. Entries are interleaved and rotated, and every step asserts on the rows it returns, so a step that silently does nothing fails. Numbers are medians, so one GC pause cannot dominate. The type-safety probes compile with TypeScript 7.0.2 at `strict`, against the same entities the timed lifecycle uses. To reproduce every table against a local PostgreSQL: ```bash git clone https://github.com/rogerpadilla/ts-orm-benchmark.git cd ts-orm-benchmark bun install DATABASE_URL=postgres:///postgres bun run bench DATABASE_URL=postgres:///postgres bun run bench.runtimes DATABASE_URL=postgres:///postgres bun run bench.memory bun run bench.types ``` --- For how the APIs and features line up, see the [comparison](https://uql-orm.dev/comparison.md). [Comparison](https://uql-orm.dev/comparison.md)Drizzle, MikroORM, Prisma, TypeORM and UQL, with code for every common operation. --- ## Try it ```sh npm install uql-orm ``` Then [add your database driver](https://uql-orm.dev/getting-started.md#1-install). Entities are plain classes and queries are plain JSON: nothing to generate, and no schema file to keep in sync. [Quick Start](https://uql-orm.dev/getting-started.md) [GitHub](https://github.com/rogerpadilla/uql) --- # ORM Type Safety Comparison > Ordinary mistakes written in six TypeScript ORMs, compiled live: Drizzle vs MikroORM vs Prisma vs Sequelize vs TypeORM vs UQL. Source: https://uql-orm.dev/type-safety The same ordinary mistakes, written in six ORMs’ own APIs against the same two entities: a misspelled key, a text operator on a number, a sum over a text column, a read of a column you never selected, and eight more. The editor runs the real TypeScript compiler over the real packages. Switch tabs to see what each one catches. ```ts import { asc, eq, gt, like, sum } from 'drizzle-orm'; import { drizzleUsers } from '../src/schema'; import { clients } from './clients'; const { drizzleDb: db } = clients; // Misspelled column in the projection | emial -> email await db .select({ id: drizzleUsers.id, email: drizzleUsers.emial }) .from(drizzleUsers); // Misspelled column in the filter | createdat -> createdAt await db .select({ id: drizzleUsers.id }) .from(drizzleUsers) .where(gt(drizzleUsers.createdat, 0)); // String value against a numeric column | 'one' -> 1 await db .select({ id: drizzleUsers.id }) .from(drizzleUsers) .where(eq(drizzleUsers.createdAt, 'one')); // Text operator against a numeric column | like(drizzleUsers.createdAt, 'abc') -> gt(drizzleUsers.createdAt, 1) await db .select({ id: drizzleUsers.id }) .from(drizzleUsers) .where(like(drizzleUsers.createdAt, 'abc')); // Misspelled column in the sort | idd -> id await db .select({ id: drizzleUsers.id }) .from(drizzleUsers) .orderBy(asc(drizzleUsers.idd)); // Sum over a text column | name -> id await db.select({ total: sum(drizzleUsers.name) }).from(drizzleUsers); // Misspelled column inside a loaded relation | nmae -> name await db.query.Company.findMany({ columns: { id: true }, with: { users: { columns: { nmae: true } } }, }); // Misspelled column in inserted data | emails -> email await db .insert(drizzleUsers) .values([{ name: 'New User', emails: 'new@example.com' }]); // Required column left out of inserted data | 'New User' } -> 'New User', email: 'new@example.com' } await db.insert(drizzleUsers).values([{ name: 'New User' }]); // Number written into a text column | 42 -> 'Updated Name' await db.update(drizzleUsers).set({ name: 42 }).where(eq(drizzleUsers.id, 1)); // Reading a column the projection left out | user.email -> user.name const [user] = await db .select({ id: drizzleUsers.id, name: drizzleUsers.name }) .from(drizzleUsers); export const unselected = user.email; // Reading a misspelled column off a loaded relation | .nmae -> .name const [company] = await db.query.Company.findMany({ columns: { id: true }, with: { users: { columns: { id: true, name: true } } }, }); export const nested = company.users[0].nmae; ``` type-safety/drizzle.ts · static preview ## How it is scored The files come unchanged from [ts-orm-benchmark](https://github.com/rogerpadilla/ts-orm-benchmark), which also runs the [speed benchmark](https://uql-orm.dev/benchmark.md). Each ORM’s file compiles twice: as written, and with every mistake fixed. A mistake counts as caught only when it errors and the fixed version compiles clean. The benchmark scores with TypeScript 7.0.2. This site recompiles the same files at build time with TypeScript 6.0.3, the compiler the editor runs too, and the deploy fails if a verdict changes. Each entry uses the API its main package offers. MikroORM’s entities use `defineEntity`, since its decorators moved to `@mikro-orm/decorators`. TypeORM’s decorators are the legacy kind, so its entities use `EntitySchema`, which scores the same. Drizzle’s flat probes use `db.select()` and its relation probes `db.query.*`, the same code its benchmark times. ## Reading the result UQL catches all twelve, Prisma eleven, Drizzle, MikroORM and TypeORM ten, and Sequelize six. A one-probe gap should not decide a tool on its own, and this page says nothing about migrations, error readability or type-checking speed on large schemas. I wrote UQL, so weigh the verdict accordingly. The [method](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) is open, and every entry faces the same probes. [Rename Safety](https://uql-orm.dev/rename-safety.md)Six ORMs renaming a field, a foreign key and a relation: which indexes, checks, relations, queries and raw SQL follow. [Benchmark](https://uql-orm.dev/benchmark.md)The other half: what each ORM costs on a full PostgreSQL round trip, on Bun and Node. [Comparison](https://uql-orm.dev/comparison.md)Drizzle vs MikroORM vs Prisma vs TypeORM vs UQL, with actual code for every common operation. --- ## Try it ```sh npm install uql-orm ``` Then [add your database driver](https://uql-orm.dev/getting-started.md#1-install). Entities are plain classes and queries are plain JSON: nothing to generate, and no schema file to keep in sync. [Quick Start](https://uql-orm.dev/getting-started.md) [GitHub](https://github.com/rogerpadilla/uql) --- # What survives a rename? Six TypeScript ORMs > Six ORMs renamed the way your editor renames, and compiled live: which mentions follow, which the compiler catches, and which break silently. Source: https://uql-orm.dev/rename-safety Press F2 on a field and your editor renames every use it can link to the declaration. With an ORM, that covers only the places the schema links to your code. Each tab is one ORM’s model and 19 places that name three of its members, renamed the way F2 does: `emailAddress` to `email`, `employerId` to `workplaceId`, `employer` to `workplace`. Green is what the rename edited, red what it missed and the compiler stops, amber what it missed and still compiles. - renamed - stopped by the compiler - left behind silently ```ts import { count, eq, relations, type SQL, sql } from 'drizzle-orm'; import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import { check, index, integer, pgTable, serial, text, uniqueIndex, } from 'drizzle-orm/pg-core'; export const companies = pgTable('Company', { id: serial().primaryKey() }); export const users = pgTable( 'User', { id: serial().primaryKey(), emailAddress: text().notNull(), employerId: integer().references(() => companies.id), // Generated column emailLower: text().generatedAlwaysAs( (): SQL => sql`lower(${users.emailAddress})`, ), }, (t) => [ // Index on the field index().on(t.emailAddress), // Composite unique index uniqueIndex().on(t.emailAddress, t.employerId), // Covering index column | n/a: Drizzle's index builder has no INCLUDE // Expression index index().on(sql`lower(${t.emailAddress})`), // Partial index condition index() .on(t.employerId) .where(sql`${t.emailAddress} <> ''`), // Check constraint check('address_present', sql`${t.emailAddress} <> ''`), ], ); export const usersRelations = relations(users, ({ one }) => ({ // Foreign key of a relation employer: one(companies, { fields: [users.employerId], references: [companies.id], }), })); export const companiesRelations = relations(companies, ({ many }) => ({ // Inverse side of a relation staff: many(users), })); const schema = { companies, users, usersRelations, companiesRelations }; declare const db: NodePgDatabase; // Field in the projection await db.select({ id: users.id, address: users.emailAddress }).from(users); // Field in the filter await db.select().from(users).where(eq(users.emailAddress, 'ada@example.com')); // Field in the sort await db.select().from(users).orderBy(users.emailAddress); // Field inside a loaded relation await db.query.companies.findMany({ with: { staff: { columns: { emailAddress: true } } }, }); // Relation loaded by name await db.query.users.findMany({ with: { employer: true } }); // Field in inserted data await db.insert(users).values({ emailAddress: 'ada@example.com' }); // Field in updated data await db .update(users) .set({ emailAddress: 'ada@example.com' }) .where(eq(users.id, 1)); // Foreign key in a grouped count await db .select({ company: users.employerId, total: count() }) .from(users) .groupBy(users.employerId); // Field read off the result const [user] = await db.select().from(users); export const address = user.emailAddress; // Raw SQL in a filter await db .select() .from(users) .where(sql`lower(${users.emailAddress}) = ${'ada@example.com'}`); ``` rename-safety/drizzle.ts · static preview ## What each one left behind The last column is what reaches production: a stale name that compiles, then fails at run time or in a migration. Rows can add to less than 19 where an ORM cannot express a probe. | ORM | Followed the rename | Stopped by the compiler | Left behind silently | | - | - | - | - | | Sequelize | 4 | 0 | 12 | | TypeORM | 12 | 0 | 5 | | Prisma | 4 | 7 | 3 | | MikroORM | 3 | 13 | 3 | | Drizzle | 14 | 4 | 0 | | UQL | 19 | 0 | 0 | Sequelize types the model with `InferAttributes`, but indexes, associations and queries take unchecked strings: `fields: ['emailAddress']`, `as: 'employer'`, `attributes`, `include`. TypeORM’s `@Index((user: User) => [user.emailAddress])` follows the rename. Three of its 5 silent misses are SQL strings in the same decorators: a partial index’s `where`, a `@Check` body, and a generated column’s `asExpression`. Prisma renames its schema and regenerates the client, so most misses become compile errors. Raw SQL in `$queryRaw` is among the 3 that slip through. MikroORM follows the fewest renames, but its `defineEntity` builder types index properties, so 13 misses stop the build. The 3 silent ones are a `joinColumn('employerId')` string, a generated-column template and one query. Drizzle’s schema is values its queries import, so nothing slips through silently. The 4 compile errors are writes and loaded relations checked against the table without a link to it. UQL follows all 19. Indexes, checks and relations name members through callbacks, and every query key is typed off the entity. ## How it is measured The files, renames and marks are [ts-orm-benchmark](https://github.com/rogerpadilla/ts-orm-benchmark#rename-safety)’s. Each rename is TypeScript 7.0.2’s own, or prisma-language-server 31.13.0’s for `schema.prisma`, replayed in your browser and checked live. The build fails if F2 here would edit any other place, or if a red line would move. Prisma’s tab renames `schema.prisma`, regenerates the client, and compiles the queries against it. TypeORM’s legacy decorators compile in a project and a worker of their own. I wrote UQL, so weigh this accordingly. The benchmark is open, and every tab runs the same compiler. [Type Safety](https://uql-orm.dev/type-safety.md)Six ORMs against ordinary mistakes: a misspelled key, a text operator on a number, a column you did not select. [Benchmark](https://uql-orm.dev/benchmark.md)What each ORM costs on a full PostgreSQL round trip, on Bun and Node. # Decorators > Define entities with the @Entity and @Field decorators, and choose column types with the f builders. Source: https://uql-orm.dev/entities/basic An entity is a plain TypeScript class that maps to a table. `@Entity` marks the class and `@Field` each column, its builder naming the type; `.id()` marks the primary key: ```ts import { f, Entity, Field } from 'uql-orm'; import { v7 as uuidv7 } from 'uuid'; @Entity() export class User { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.string()) name!: string; @Field(f.string().nullable().unique()) email?: string | null; } ``` These are standard TC39 decorators: leave `experimentalDecorators` off. To define entities without decorators, use [`defineEntity`](https://uql-orm.dev/entities/define-entity.md); the two styles mix in one project, and [which to pick](https://uql-orm.dev/entities/define-entity.md#decorators-or-defineentity) comes down to taste and tooling. ## Column types The builder names the column’s type, and it must match the property: `@Field(f.string())` on a `number` property does not compile. Each dialect maps it to its own SQL type: `f.uuid()` is `UUID` on Postgres and `CHAR(36)` on MySQL. The constructors are `f.string()`, `f.number()`, `f.boolean()`, `f.bigint()`, `f.date()`, `f.text()`, `f.uuid()`, `f.decimal(precision, scale)`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum([...])`, and `f.column('')` for any other SQL type. A JSON column’s optional schema types its payload, as [JSON / JSONB](https://uql-orm.dev/querying/json.md#a-schema-for-the-payload) describes. A builder is immutable, so one held in a constant is shared safely: `const money = f.decimal(12, 2)`, then `@Field(money.nullable())` on one field and `@Field(money)` on another. - `Date` is stored in UTC to the millisecond on every engine. - `f.number()` is a `BIGINT`. Past 2^53 it reads back as exact text, never a rounded number, except on D1, whose API returns a JS number. Use `f.bigint()` for an exact typed integer. - An `f.decimal(precision, scale)` reads and writes as exact text (`price?: string | null`). `f.number().precision(12).scale(2)` gives a JS number instead, which rounds past 15 digits. SQLite stores a float either way. - A JSON property typed `Json` counts as a field, so `$where`, `$select` and `$sort` take its [dot-notation paths](https://uql-orm.dev/querying/comparison-operators.md#jsonb-dot-notation-operators). ```ts import { f, type Json } from 'uql-orm'; @Field(f.decimal(12, 2).nullable()) price?: string | null; @Field(f.jsonb().nullable()) metadata?: Json<{ theme?: string; priority?: number }> | null; ``` `f.column(type)` declares a column of any SQL type uql names, typed by its family: ```ts import { f } from 'uql-orm'; @Field(f.column('smallint').nullable()) pickupFrom?: number | null; @Field(f.column('date').nullable()) pickupDate?: Date | null; ``` It names `int`, `integer`, `tinyint`, `smallint`, `bigint`, `float`, `float4`, `float8`, `double`, `double precision`, `decimal`, `numeric`, `real`, `char`, `varchar`, `text`, `uuid`, `date`, `time` (read as a string), `datetime`, `timestamp`, `timestamptz`, `json`, `jsonb`, `blob`, `bytea`, `bool`, `boolean`, `vector`, `halfvec` and `sparsevec`, each mapped to the engine’s nearest type. `.columnType()` sets the exact SQL type of a builder that already chose its family. For a type uql does not map (`tsvector`, `ltree`, `inet`, `citext`, geometry), pass a `sql` constant (never a bare string). It is emitted verbatim, so `length`, `precision`, `scale` and `dimensions` are refused beside it: ```ts import { Computed, f, sql } from 'uql-orm'; @Field(f.string().length(500).columnType('varchar').nullable()) longBio?: string | null; @Computed((post) => f.string().nullable().columnType(sql`tsvector`).as(sql`to_tsvector('simple', ${post.body})`).stored()) readonly searchVector?: string | null; ``` ### Values the database computes These constants are SQL the database evaluates. Use them in a `.default()`, an `.onUpdate()`, a stamp or `$where`, and in [migrations](https://uql-orm.dev/migrations/builder.md#default-expressions): | Value | What it is | Where | | - | - | - | | `currentTimestamp` | the clock, UTC to the millisecond | everywhere | | `currentDate` | today | everywhere | | `currentTime` | the time of day | everywhere | | `uuid` | a UUID: version 4, or version 1 on MySQL and MariaDB | not SQLite | | `uuidv7` | a time-ordered version 7 UUID, which indexes better | Postgres 18+, MariaDB 11.7+ | ```ts import { currentTimestamp, f } from 'uql-orm'; @Field(f.date().default(currentTimestamp).nullable()) createdAt?: Date | null; ``` Prefer `currentTimestamp` to a raw `CURRENT_TIMESTAMP`, which is not UTC to the millisecond on MySQL, SQL Server or SQLite. An engine lacking one of these throws; write [`sql`](https://uql-orm.dev/querying/raw-sql.md) there. ## Nullable columns A column is NOT NULL unless the builder says `.nullable()`, and a nullable column’s property must include `null`. A mismatch does not compile: ```ts @Field(f.string()) title!: string; // NOT NULL @Field(f.date().nullable()) publishedAt?: Date | null; // nullable ``` The [codemod](https://uql-orm.dev/codemod.md) adds `| null` to existing entities. ## Branded types A branded type keeps one string from passing as another, like a user’s id where a function expects an email. A column constructor’s type argument narrows what the row holds: a brand, a template literal, or a JSON column’s payload with no runtime schema, `f.json()`. The row carries it through every read, filter and write: ```ts import { defineEntity, f } from 'uql-orm'; type UserId = string & { readonly __brand: 'UserId' }; type UserEmail = string & { readonly __brand: 'UserEmail' }; const User = defineEntity({ name: 'User', fields: { id: f .uuid() .id() .onInsert(() => crypto.randomUUID() as UserId), email: f.string().unique(), }, }); ``` The type has to fit the column, so `f.number()` does not compile. It exists only in types and changes no SQL, and a default or `onInsert` value is written as the brand. To brand a SQL type of your choosing, set it after: `f.number().columnType('int')`. A filter on the column takes a `UserEmail`, not a plain string; operators on text, like `$iendsWith`, still take a string. A foreign key to a branded key has to hold the same brand, or the relation does not compile: `authorId: f.uuid()`. With decorators, type the property instead: `@Field(f.string()) email!: UserEmail;`, and `@Field(f.references(() => User)) authorId?: UserId;` for a foreign key, whose type comes from the key. A plain `f.uuid().references(() => User)` holds its property to the same brand. ## Required fields Declare a NOT NULL property with `!`, like `name` above. Inserts must include it, and a read that selects it always has it: ```ts await pool.insertOne(User, { name: 'Ada' }); // `{}` does not compile: `name` is missing const [user] = await pool.findMany(User, { $select: { id: true, name: true } }); user.name.trim(); // a `string`, never `undefined` ``` An insert may still omit a `?` property, MongoDB’s `_id`, a [version](https://uql-orm.dev/entities/optimistic-locking.md) column, which uql fills, and the fields the `filledKey` brand lists: each NOT NULL field something fills, such as a `.default()`, an `.onInsert()` or a key the database generates. Any other key is the caller’s to write. `@Field` refuses a listed field nothing fills, and `?` or `| undefined` on a numeric or `.references()` key nothing fills; `defineEntity` works all of this out itself. A read still has what the brand lists: ```ts import { f, currentTimestamp, filledKey } from 'uql-orm'; @Entity() export class Product { [filledKey]?: 'id' | 'stock' | 'createdAt'; @Field(f.number().autoIncrement()) id!: number; @Field(f.string()) name!: string; @Field(f.number().default(0)) stock!: number; @Field(f.date().default(currentTimestamp)) createdAt!: Date; } await pool.insertOne(Product, { name: 'Lamp' }); // `stock` and `createdAt` are filled const [product] = await pool.findMany(Product, {}); product.stock.toFixed(); // a `number`, never `undefined` ``` Declare everything else an insert may omit with `?`: nullable columns, `.eager(false)` and `@Computed` fields, and relations. A composite key must be given in full. ## Primary keys `.id()` makes a column the primary key, and a key is never `null`; the caller supplies its value. `f.number().autoIncrement()` is a key the database generates, which keeps indexes small and joins fast. `f.uuid().id().onInsert(uuidv7)` generates a UUID in your code before the row exists, and cannot be guessed from a public URL. ### Naming the key A key named `id`, `_id` or `uuid` is recognized. Any other name needs the `idKey` brand, or `findOneById` would accept any column’s values: ```ts import { f, idKey } from 'uql-orm'; @Entity() export class TaxCategory { [idKey]?: 'pk'; @Field(f.uuid().id().onInsert(uuidv7)) pk?: string; } ``` ## Composite primary keys Several `.id()` columns make one composite key, in declaration order. The brand names every key column, and every by-id call takes all of them: ```ts import { f } from 'uql-orm'; @Entity() export class Enrolment { [idKey]?: 'studentId' | 'courseId'; @Field(f.number().id()) studentId!: number; @Field(f.string().id()) courseId!: string; @Field(f.string().nullable()) grade?: string | null; } await pool.updateOneById( Enrolment, { studentId: 1, courseId: 'maths' }, { grade: 'A' }, ); ``` The type cannot require every key, so an id missing one throws at run time instead of matching more rows. ### Pointing at a composite key A foreign key to a composite key needs one column per key column, paired in the relation, and the pairs form one `FOREIGN KEY`. `f.references(() => Enrolment)` is refused. A junction pointing at a composite side needs this `@ManyToOne` too. ```ts import { ManyToOne } from 'uql-orm'; @ManyToOne(() => Enrolment, { references: (note, enrolment) => [ { local: note.enrolmentStudentId, foreign: enrolment.studentId }, { local: note.enrolmentCourseId, foreign: enrolment.courseId }, ], }) enrolment?: Enrolment; ``` A [`cascade`](https://uql-orm.dev/entities/relations.md#writing-related-rows-cascade) to-many or many-to-many over a composite side writes those columns too: each child, or junction row, carries the whole key of its parent and of its target. ### What is not supported Reads, writes, cascading deletes and saving a relation all handle composite keys. Two paths throw on one: MongoDB, where a document has a single `_id` (use a unique compound index instead), and the [HTTP API](https://uql-orm.dev/http.md)’s by-id calls, where a composite row is reachable through `$where`. ## Table name The table takes the class name. `@Entity({ name })` overrides it, and `@Entity({ schema })` sets its [schema](https://uql-orm.dev/multiple-schemas.md). ### If your build minifies, name the table A minifier renames classes (`User` becomes `b`), and the table name would follow. Set `@Entity({ name: 'user' })` in any build that minifies, Next’s server build included; `drift:check` catches a mismatch. ## Field options A column’s builder takes these methods, besides its constructor: | Method | What it does | | - | - | | `.columnType(type)` | Exact SQL type, or a `sql` constant. | | `.length(n)` | String length. Unset: `TEXT` (Postgres, SQLite) or `VARCHAR(255)` (MySQL, MariaDB). | | `.precision(p)`, `.scale(s)` | A `decimal`’s digits and digits after the point. `.precision()` on a `Date` sets fractional-second digits. | | `.dimensions(n)` | A vector’s dimensions, as `f.vector(n)` states them. | | `.name(n)`, `.comment(c)` | Column name (defaults to the property name) and its database comment. | | `.nullable()` | Makes the column nullable. NOT NULL otherwise. | | `.unique()` | Unique index, named by `.index(name)` or `
___idx`. | | `.index()` | Adds an [index](https://uql-orm.dev/entities/indexes.md); a string names it. A foreign key is indexed unless `.index(false)`. | | `f.enum([...])` | Allowed values as a [`CHECK`](https://uql-orm.dev/entities/enum-checks.md#enum-fields). A list held in a constant needs `as const`. | | `.default(value)` | A value, or per-row SQL such as `currentTimestamp`. JSON columns take a document, `[]` or `{}`. | | `f.references(() => Entity)` | A foreign key typed by the target’s key, so it replaces the type constructor. A [relation](https://uql-orm.dev/entities/relations.md) over it loads the target. | | `.onDelete(action)` | The foreign key’s [`ON DELETE` action](https://uql-orm.dev/entities/relations.md#database-actions-ondelete-and-onupdate). A relation’s own wins. | | `.onInsert(v)`, `.onUpdate(v)` | Value for a new row (`uuidv7`), or on every update (`() => new Date()`). | | `.updatable(false)` | Leaves the field out of updates, e.g. `createdAt`; an API update naming it is a `403`. | | `.eager(false)` | Leaves the field out of reads unless selected, e.g. `password`. A read that selects it still gets it: keep a client off it with `.wire(false)`. | | `.wire(access)` | [What a client may do](https://uql-orm.dev/http.md#what-a-client-may-do) to the field over an API: `false` hides it, `['read']` makes it read-only. | | `.autoIncrement()` | Makes a numeric column the primary key, which the database generates. A key the caller supplies is `.id()`. | | `@Computed(...)` | A [database expression or relation aggregate](https://uql-orm.dev/entities/computed-fields.md). `.stored()` makes it a generated column; `.stored(['update'])` makes it a [stamp](https://uql-orm.dev/entities/computed-fields.md#stamps-stored-on-an-event). | | `.softDelete()` | Marks the [soft-delete](https://uql-orm.dev/entities/soft-delete.md) field: it stamps `new Date()`, or give the value to stamp. | | `f.version()` | Makes the column an [optimistic lock](https://uql-orm.dev/entities/optimistic-locking.md). | | `.distance(metric)` | Default vector metric: `'cosine'`, `'l2'`, `'inner'` or `'l1'`. Falls back to the vector index’s, then `'cosine'`. | A method that would have no effect does not compile, and throws at registration where no type reaches it, as in JavaScript. `.length()` needs a string column, `.precision()` a numeric or date one, `.scale()` and `.autoIncrement()` a numeric one, `.dimensions()` and `.distance()` a vector. A `@Computed` field takes no `.default()`, `.onInsert()` or `.onUpdate()`, and unless `.stored()`, no `.index()`, `.unique()` or `.columnType()`. A relation aggregate takes neither a constructor nor `.stored()`. `.onUpdate()` conflicts with `.updatable(false)`, and a key cannot be `.nullable()`. `@Entity`’s `indexes`, `filters` and `triggers` have their own pages: [Indexes](https://uql-orm.dev/entities/indexes.md), [Filters](https://uql-orm.dev/querying/filters.md), [Triggers](https://uql-orm.dev/entities/triggers.md); so do the [relation decorators](https://uql-orm.dev/entities/relations.md). `abstract: true` declares a base that is never a table: see [Inheritance](https://uql-orm.dev/entities/inheritance.md). # defineEntity > Declare an entity as data with defineEntity, its row type derived from the fields, with no decorators. Source: https://uql-orm.dev/entities/define-entity `defineEntity` declares an entity as data and returns its class. The row type is derived from the fields, so nothing is written twice, and no decorator is involved. Its options are the [decorators’](https://uql-orm.dev/entities/basic.md), so the two styles mix freely in one project. ```ts import { f, defineEntity, sql } from 'uql-orm'; import { v7 as uuidv7 } from 'uuid'; import { z } from 'zod'; // Any Standard Schema types the payload: Zod here, or Valibot, ArkType, or one written by hand. const Settings = z.object({ theme: z.string(), bio: z.string().optional() }); export const User = defineEntity({ name: 'User', fields: { id: f.uuid().id().onInsert(uuidv7), email: f.string().nullable().unique(), settings: f.json(Settings).nullable(), }, }).relations((rel) => ({ posts: () => rel.oneToMany(Post, { mappedBy: (post) => post.author }), })); // One name for the entity and its rows, as a class has: a function takes `user: User`. export interface User extends InstanceType {} export const Post = defineEntity({ name: 'Post', fields: { id: f.number().autoIncrement(), title: f.string(), status: f.enum(['draft', 'published']).default('draft'), authorId: f.uuid().nullable(), publishedAt: f.date().nullable(), }, }) .computed((post) => ({ slug: f .string() .nullable() .as(sql`lower(${post.title})`), })) .indexes((post, index) => [ index([post.title, post.authorId], { unique: true }), ]) .filters({ published: { where: { publishedAt: { $ne: null } }, default: false }, }) .hooks({ beforeInsert: [(post) => void (post.title = post.title.trim())] }) .relations((rel) => ({ author: () => rel.manyToOne(User, { references: (post) => post.authorId }), })); export interface Post extends InstanceType {} ``` `Post` reads `title` and `status` as always present, `status` as `'draft' | 'published'`, and `authorId` as `string | null`. An insert may leave `status` out, since it has a default, and `id`, which the database assigns. ## Decorators or defineEntity Both give the same queries and the same types, and you can mix them entity by entity. **Decorators** suit you if you think in classes. You get a named type on hover and in errors, and a foreign key right on its column, so entities can point at each other in any order. It is also what TypeORM and MikroORM users already know. They are a little stricter, too: - A relation’s `mappedBy` must name a relation, or a foreign key holding this entity’s key, at compile time. `defineEntity` takes any member’s name there and checks the rest when the entity is first read. - Two entities reading each other never trip TypeScript’s inference, which `defineEntity` can when an eager read crosses them (TS7022). **`defineEntity`** suits you if you’d rather write each field once. The row type comes from the builders, so entities run 19 to 30% shorter and cost the compiler about 45% less. It needs no decorator transform, which helps when: - Your transformer does not implement decorators, like Oxc (Vite 8’s own). - You are in NestJS, which keeps `experimentalDecorators` on for its own DI, and one config cannot compile both decorator specs. - You run the CLI on plain `node`: type stripping runs no decorators, so decorated entities need Bun or `tsx`. - You write JavaScript, or build entities at run time, like a CMS content type. A column narrower than its builder is a [type argument](https://uql-orm.dev/entities/basic.md#branded-types): a branded id, `f.uuid()`, or a JSON payload with no runtime schema, `f.json()`. In return, relations come last as thunks, a foreign key is a relation rather than a column option, and each entity needs an `interface Post extends InstanceType {}` line, so hovers and errors print `Post`. The rest is in [what defineEntity asks for](#what-defineentity-asks-for). Both forms share structure. A decorated base class carries its fields, relations, hooks, filters, indexes, checks, triggers and `wire` to every entity extending it, and `defineEntity` does the same with [`extends`](https://uql-orm.dev/entities/inheritance.md#a-base-for-defineentity). Its fields are a plain object too, so a shared set spreads in: `fields: { ...stamped, title: f.string() }`. ## Options The object names the entity and its columns: | Key | Decorator | Notes | | - | - | - | | `name` | The class name | A [naming strategy](https://uql-orm.dev/naming-strategy.md) derives the table from it, as from a decorated class’s name. | | `table` | `@Entity({ name })` | The table, exactly as written. | | `schema` | `@Entity({ schema })` | See [multiple schemas](https://uql-orm.dev/multiple-schemas.md). | | `fields` | `@Field` | [Column builders](https://uql-orm.dev/entities/basic.md#field-options); a key is `.id()`, as a decorated field declares it. | | `extends` | `class Child extends Base` | The class it inherits from, see [Inheritance](https://uql-orm.dev/entities/inheritance.md#a-base-for-defineentity). | | `abstract` | `@Entity({ abstract: true })` | `true` for a base that is never a table, see [Inheritance](https://uql-orm.dev/entities/inheritance.md). | | `wire` | `@Entity({ wire })` | What a client may do to it over an API, see [what a client may do](https://uql-orm.dev/http.md#what-a-client-may-do). | Everything else is a section chained after it, each called once, in any order but `.relations()`, which comes last; only a `.filters()` reading through the relations may follow it: | Section | Decorator | Notes | | - | - | - | | `.computed()` | `@Computed` | Columns the database computes, read off the stored ones: ``(post) => ({ slug: f.string().as(sql`...`) })``. | | `.indexes()` | `@Entity({ indexes })` | `(post, index) => [index([post.title], 'by_title')]`, see [Indexes](https://uql-orm.dev/entities/indexes.md). | | `.checks()` | `@Entity({ checks })` | [Check constraints](https://uql-orm.dev/entities/enum-checks.md#check-constraints). | | `.triggers()` | `@Entity({ triggers })` | [Trigger options](https://uql-orm.dev/entities/triggers.md). | | `.filters()` | `@Entity({ filters })` | [Filter options](https://uql-orm.dev/querying/filters.md#defining-a-filter). | | `.hooks()` | Hook decorators | Each [lifecycle event](https://uql-orm.dev/entities/lifecycle-hooks.md) and its functions of the row: `{ beforeInsert: [(post, ctx) => ...] }`. | | `.relations()` | `@ManyToOne` and the others | `(rel) => ({ author: () => rel.manyToOne(User, { ... }) })`, each taking its [relation options](https://uql-orm.dev/entities/relations.md). | ## What defineEntity asks for - Each relation is a thunk, `author: () => rel.manyToOne(...)`. TypeScript infers two entities that point at each other only when each reads the other lazily, so either can be declared first, in either file. - `.computed()`, `.indexes()`, `.checks()`, `.triggers()` and `.hooks()` read the columns, not the relations. `.filters()` reads them too, or, declared after `.relations()`, the relations at any depth. - A JSON column’s payload is a [Standard Schema](https://standardschema.dev), `f.json(schema)`, typed by its output: any library’s schema (Zod, Valibot, ArkType), or one written by hand. Paths into it are typed in indexes and queries; without one, any path reads. - Behaviour on a row is a function of it, `label(post: Post)`: rows read back as plain objects, so a method would never be there. - A value over a to-many reads as a column declared in `.relations()`’ second callback, as a thunk of its aggregate, `(author) => ({ bookCount: () => author.books.count(), topStock: () => author.books.max((book) => book.stock) })`. The same callback reads the entity’s own columns, so one expression can combine them. - Each relation takes the options its cardinality joins by: a `manyToOne` names its `references`, a `oneToMany` its `mappedBy`, `through` or `references` pairs, or nothing, where its target holds one relation pointing back. A to-one’s `references` column is checked against its target’s key type at compile time; `mappedBy` is checked when the entity is first read. ## An entity defined at runtime When the shape is data, such as a CMS content type an admin creates, the fields are built from it and `sync({ entity })` gives the entity a table. See [Runtime entities](https://uql-orm.dev/entities/runtime.md). # Runtime Entities > Define entities from data, such as a CMS content type an admin creates, and apply them to the database while the process is running. Source: https://uql-orm.dev/entities/runtime Some entities exist only at runtime, such as a content type an admin creates in a CMS. uql reads no TypeScript types at runtime, so a [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) call built from data registers like any other, and `sync({ entity })` gives it a table: ```typescript import { defineEntity, f, type ColumnType } from 'uql-orm'; import { Migrator } from 'uql-orm/migrate'; type ContentType = { name: string; fields: { name: string; type: ColumnType }[]; }; async function registerContentType(contentType: ContentType) { const entity = defineEntity({ name: contentType.name, fields: { id: f .uuid() .id() .onInsert(() => crypto.randomUUID()), ...Object.fromEntries( contentType.fields.map((field) => [field.name, f.column(field.type)]), ), }, }); await new Migrator(pool).sync({ entity }); return entity; } ``` Rows come back as plain objects. Pass the entity to a querier like any other. Translate your UI’s own vocabulary (`text`, `longtext`, `money`) to a SQL [column type](https://uql-orm.dev/entities/basic.md#column-types) as you build the fields. Columns every content type shares (`createdBy`, a tenant key) belong on a base passed as [`extends`](https://uql-orm.dev/entities/inheritance.md#a-base-for-defineentity). ## Applying it to the database If the table does not exist, `sync({ entity })` runs `CREATE TABLE IF NOT EXISTS` after one existence check, so two instances handling the same admin save both finish. If it exists, uql applies what a full [`sync`](https://uql-orm.dev/migrations.md#syncing-without-a-migration-file) would: in the default safe mode, that adds new columns and skips, with a log line, any column retyped or removed. Change existing columns with a migration. A `Migrator` built without an `entities` option reads the registry live, so entities registered later are included without a restart. One built with an explicit list still syncs an entity passed to `sync({ entity })`. uql takes no lock across instances beyond `IF NOT EXISTS`, and does not validate rows against the content type: the database enforces what the DDL says. ## Editing and deleting a content type An edited content type is a new entity for the same table. Remove the previous entity first, so it does not stay in every diff, then register the new one and sync it: ```typescript import { removeEntity } from 'uql-orm'; const previous = registered.get(contentType.name); if (previous) removeEntity(previous); registered.set(contentType.name, await registerContentType(contentType)); ``` Call `removeEntity(entity)` for a deleted content type too, or its table stays in every diff for the life of the process. ## Typing Built from a record, the row is a record too: `$where`, `$sort`, `$populate` and projections take any column by name, and each value reads `unknown`, since nothing at compile time says which columns the admin created. Build the fields as one record and spread it into the literal beside the other columns: a record’s index signature is dropped there, and only those other columns are typed. To type the rows your code handles, generate an interface per content type with `npx uql-migrate types`, which writes one for every registered entity. # Relations > Define one-to-one, one-to-many and many-to-many relations between UQL entities. Source: https://uql-orm.dev/entities/relations A relation links two entities so you can load, filter and write related rows. Members are named with callbacks such as `(post) => post.author`, so a typo is a compile error and a rename follows. Decorators: ```ts import { v7 as uuidv7 } from 'uuid'; import { f, Entity, Field, OneToOne, OneToMany, ManyToOne, ManyToMany, } from 'uql-orm'; @Entity() export class User { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.string().nullable()) name?: string | null; @OneToOne(() => Profile, { mappedBy: (profile) => profile.user, cascade: true, }) profile?: Profile; @OneToMany(() => Post, { mappedBy: (post) => post.author }) posts?: Post[]; } @Entity() export class Profile { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.references(() => User).nullable()) userId?: string | null; @OneToOne(() => User, { references: (profile) => profile.userId }) user?: User; } @Entity() export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.references(() => User).nullable()) authorId?: string | null; @ManyToOne(() => User, { references: (post) => post.authorId }) author?: User; @ManyToMany(() => Tag, { through: () => PostTag, cascade: true }) tags?: Tag[]; } @Entity() export class Tag { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.string().nullable()) name?: string | null; } @Entity() export class PostTag { @Field(f.uuid().id().onInsert(uuidv7)) id?: string; @Field(f.references(() => Post).nullable()) postId?: number | null; @Field(f.references(() => Tag).nullable()) tagId?: string | null; } ``` defineEntity: ```ts import { v7 as uuidv7 } from 'uuid'; import { f, defineEntity } from 'uql-orm'; export const User = defineEntity({ name: 'User', fields: { id: f.uuid().id().onInsert(uuidv7), name: f.string().nullable(), }, }).relations((rel) => ({ profile: () => rel.oneToOne(Profile, { mappedBy: (profile) => profile.user, cascade: true, }), posts: () => rel.oneToMany(Post, { mappedBy: (post) => post.author }), })); export interface User extends InstanceType {} export const Profile = defineEntity({ name: 'Profile', fields: { id: f.uuid().id().onInsert(uuidv7), userId: f.uuid().nullable(), }, }).relations((rel) => ({ user: () => rel.oneToOne(User, { references: (profile) => profile.userId }), })); export interface Profile extends InstanceType {} export const Post = defineEntity({ name: 'Post', fields: { id: f.number().autoIncrement(), title: f.string().nullable(), authorId: f.uuid().nullable(), }, }).relations((rel) => ({ author: () => rel.manyToOne(User, { references: (post) => post.authorId }), tags: () => rel.manyToMany(Tag, { through: () => PostTag, cascade: true }), })); export interface Post extends InstanceType {} export const Tag = defineEntity({ name: 'Tag', fields: { id: f.uuid().id().onInsert(uuidv7), name: f.string().nullable(), }, }); export interface Tag extends InstanceType {} export const PostTag = defineEntity({ name: 'PostTag', fields: { id: f.uuid().id().onInsert(uuidv7), postId: f.number().nullable(), tagId: f.uuid().nullable(), }, }); export interface PostTag extends InstanceType {} ``` ## Foreign keys The side of a to-one relation that holds the foreign key declares the column with `f.references(() => Target)` (in `defineEntity`, a plain field of the key’s type) and names it in the relation’s `references`, which may be left out when it is the only foreign key to that target. The column takes its type from the key it points at, and stays a normal field you can select, filter and write. A column with no relation over it is still a foreign key in the DDL, with nothing to `$populate`. A to-many has no column of its own, so it says where its rows are in one of three ways: | Option | Use it for | | - | - | | `mappedBy` | The inverse side: the member on the other entity holding the foreign key or relation. Optional when one many-to-one there points back. | | `through` | A junction entity with a foreign key to each side, for `@ManyToMany` or `@OneToMany`. | | `references` | Explicit join columns: `(order, customer) => [{ local: order.customerCode, foreign: customer.code }]`. Not with `through`. | With `through`, uql joins on the junction’s one column referencing each side (`postId` and `tagId` above), whatever its name. A junction with none or two for a side fails when the entity loads, as does a join column referencing a different entity than the relation’s. A [composite key](https://uql-orm.dev/entities/basic.md#composite-primary-keys) cannot be referenced by one column: [pair a column per key](https://uql-orm.dev/entities/basic.md#pointing-at-a-composite-key) in the relation’s `references` instead. A relation takes `wire` too, as a field does: `wire: false` keeps a client from reading or writing it over an [API](https://uql-orm.dev/http.md#what-a-client-may-do). ## Writing related rows: `cascade` `cascade: true` makes inserts, updates and deletes reach the relation’s rows; `'persist'` or `'delete'` enables one half. On SQL, such a write runs in one transaction, whether or not you opened one; on MongoDB, it is atomic only inside a [transaction](https://uql-orm.dev/querying/transactions.md) you open. | The relation | An insert or update | A delete | | - | - | - | | holds the key: `@ManyToOne`, `@OneToOne` with `references` | writes the target first. `{ id }` links an existing target without writing it; `null` clears the key. | `'persist'` only, since other rows may share the target | | is held by its rows: `@OneToMany`, `@OneToOne` with `mappedBy` | writes the rows, pointed at the parent. An update replaces them: listed rows are saved, the parent’s other rows deleted. `null` or `[]` deletes all. | deletes the rows first | | goes through a junction: `@ManyToMany`, `@OneToMany` with `through` | writes the targets, then the links. An update keeps or adds the listed links and removes the rest; targets stay. | deletes the links first | A soft delete cascades as a soft delete: rows that can be stamped are, and the rest, junction links included, are kept so a restore brings everything back. ## Database actions: `onDelete` and `onUpdate` To have the database act instead of uql, set the foreign key’s action on the side holding the key. A single `DELETE` then removes the children: ```ts @ManyToOne(() => User, { references: (post) => post.authorId, onDelete: 'CASCADE' }) author?: User; ``` Each takes `'CASCADE'`, `'SET NULL'`, `'SET DEFAULT'`, `'RESTRICT'` or `'NO ACTION'`. A column with no relation takes `f.references(() => Target).onDelete(...)`; a relation’s action wins over its column’s. The default is `'NO ACTION'`, or `defaultForeignKeyAction` from your migration config. ## Querying relations Columns go in `$select`, related entities in `$populate`, each with its own selection and filter: ```ts title="You write" const posts = await pool.findMany(Post, { $select: { id: true, title: true }, $populate: { author: { $select: { id: true, name: true } }, tags: { $select: { name: true }, $where: { name: { $istartsWith: 'typescript' } }, }, }, $where: { author: { name: 'Roger' } }, }); ``` PostgreSQL: ```sql -- One statement: the author is joined, the tags are a correlated subquery, the author filter an EXISTS. SELECT "Post"."id", "Post"."title", "author"."id" "author.id", "author"."name" "author.name", (SELECT COALESCE(JSON_AGG("_uql_row"), '[]'::json) FROM (SELECT "tags"."name" FROM "Tag" "tags" WHERE "tags"."name" ILIKE $1 ESCAPE '\' AND "tags"."id" IN ( SELECT "PostTag"."tagId" FROM "PostTag" WHERE "PostTag"."postId" = "Post"."id")) "tags" CROSS JOIN LATERAL (SELECT "tags"."name") "_uql_row") "tags" FROM "Post" LEFT JOIN "User" "author" ON "author"."id" = "Post"."authorId" WHERE EXISTS ( SELECT 1 FROM "User" "author_2" WHERE "author_2"."id" = "Post"."authorId" AND "author_2"."name" = $2 ) -- values: ['typescript%', 'Roger'] ``` MySQL: ```sql -- One statement: the author is joined, the tags are a correlated subquery, the author filter an EXISTS. SELECT /*+ SET_VAR(group_concat_max_len=18446744073709551615) */ `Post`.`id`, `Post`.`title`, `author`.`id` `author.id`, `author`.`name` `author.name`, (SELECT COALESCE(CONCAT('[', GROUP_CONCAT(JSON_OBJECT('name', `tags`.`name`) SEPARATOR ','), ']'), '[]') FROM (SELECT `tags`.`name` FROM `Tag` `tags` WHERE LOWER(`tags`.`name`) LIKE ? ESCAPE '\\' AND `tags`.`id` IN ( SELECT `PostTag`.`tagId` FROM `PostTag` WHERE `PostTag`.`postId` = `Post`.`id`)) `tags`) `tags` FROM `Post` LEFT JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` WHERE EXISTS ( SELECT 1 FROM `User` `author_2` WHERE `author_2`.`id` = `Post`.`authorId` AND `author_2`.`name` = ? ) -- values: ['typescript%', 'Roger'] ``` MariaDB: ```sql -- One statement: the author is joined, the tags are a correlated subquery, the author filter an EXISTS. SET STATEMENT group_concat_max_len=18446744073709551615 FOR SELECT `Post`.`id`, `Post`.`title`, `author`.`id` `author.id`, `author`.`name` `author.name`, COALESCE((SELECT JSON_ARRAYAGG(JSON_OBJECT('name', `tags`.`name`)) FROM `Tag` `tags` WHERE LOWER(`tags`.`name`) LIKE ? ESCAPE '\\' AND `tags`.`id` IN ( SELECT `PostTag`.`tagId` FROM `PostTag` WHERE `PostTag`.`postId` = `Post`.`id`)), JSON_ARRAY()) `tags` FROM `Post` LEFT JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` WHERE EXISTS ( SELECT 1 FROM `User` `author_2` WHERE `author_2`.`id` = `Post`.`authorId` AND `author_2`.`name` = ? ) -- values: ['typescript%', 'Roger'] ``` SQLite: ```sql -- One statement: the author is joined, the tags are a correlated subquery, the author filter an EXISTS. SELECT `Post`.`id`, `Post`.`title`, `author`.`id` `author.id`, `author`.`name` `author.name`, (SELECT json_group_array(json_object('name', `tags`.`name`)) FROM (SELECT `tags`.`name` FROM `Tag` `tags` WHERE `tags`.`name` LIKE ? ESCAPE '\' AND `tags`.`id` IN ( SELECT `PostTag`.`tagId` FROM `PostTag` WHERE `PostTag`.`postId` = `Post`.`id`)) `tags`) `tags` FROM `Post` LEFT JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` WHERE EXISTS ( SELECT 1 FROM `User` `author_2` WHERE `author_2`.`id` = `Post`.`authorId` AND `author_2`.`name` = ? ) -- values: ['typescript%', 'Roger'] ``` SQL Server: ```sql -- One statement: the author is joined, the tags are a correlated subquery, the author filter an EXISTS. SELECT "Post"."id", "Post"."title", "author"."id" "author.id", "author"."name" "author.name", JSON_QUERY(COALESCE((SELECT "tags"."name" FROM "Tag" "tags" WHERE LOWER("tags"."name") LIKE @p1 ESCAPE N'\' AND "tags"."id" IN ( SELECT "PostTag"."tagId" FROM "PostTag" WHERE "PostTag"."postId" = "Post"."id") FOR JSON PATH, INCLUDE_NULL_VALUES), '[]')) "tags" FROM "Post" LEFT JOIN "User" "author" ON "author"."id" = "Post"."authorId" WHERE EXISTS ( SELECT 1 FROM "User" "author_2" WHERE "author_2"."id" = "Post"."authorId" AND "author_2"."name" = @p2 ) -- values: ['typescript%', 'Roger'] ``` [Querying relations](https://uql-orm.dev/querying/relations.md) covers deep filtering and selection. On an existing database, `generate:from-db` [writes these decorators from its foreign keys](https://uql-orm.dev/migrations.md#relations-when-scaffolding). # Computed Fields > Fields the database computes, either recomputed in each query or stored as a real column. Source: https://uql-orm.dev/entities/computed-fields A computed field holds a value the database produces: an SQL expression over the row, or a [relation aggregate](#relation-aggregates) such as a count of children. You read, filter and sort it like any other field, and UQL never writes it: every insert and update leaves it out, and an [API](https://uql-orm.dev/http.md#what-a-client-may-do) refuses a write naming it with a `403`. Declare it `readonly`, so a write payload naming it fails to compile. What backs the field depends on how you declare it. Only a stamp uses a trigger: | Declared as | What is behind it | Who writes it | | - | - | - | | ``@Computed((p) => f.number().as(sql`...`))`` | Nothing stored. The expression is pasted into each statement that reads the field. | Nobody: it is worked out on each read | | ``.as(sql`...`)``, [`.stored()`](#storing-the-value-stored) | A generated column, `GENERATED ALWAYS AS (...) STORED` | The engine, on every insert and update | | ``.as(sql`...`)``, [`.stored(['update'])`](#stamps-stored-on-an-event) | A plain column plus a [trigger](https://uql-orm.dev/entities/triggers.md) | The trigger, on each listed event | | [`@Computed((o) => o.items.count())`](#relation-aggregates) | Nothing stored. A correlated subquery in each statement that reads it (a `$lookup` on MongoDB). | Nobody: it is worked out on each read | The first and last are computed on each read, so they are always current but cost their expression every time. The stored kinds are real columns: computed once per write, then read and indexed like any other. Decorators: ```ts import { Computed, f, Entity, Field, sql } from 'uql-orm'; @Entity() export class Product { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) cost?: number | null; @Field(f.number().nullable()) salePrice?: number | null; @Computed((product) => f .number() .nullable() .as(sql`${product.salePrice} - ${product.cost}`), ) readonly profit?: number | null; } ``` defineEntity: ```ts import { f, defineEntity, sql } from 'uql-orm'; export const Product = defineEntity({ name: 'Product', fields: { id: f.number().autoIncrement(), cost: f.number().nullable(), salePrice: f.number().nullable(), }, }).computed((product) => ({ profit: f .number() .nullable() .as(sql`${product.salePrice} - ${product.cost}`), })); export interface Product extends InstanceType {} ``` Each ref (`product.salePrice`) renders as its column, qualified and escaped, so the expression works in joins and subqueries and follows a rename in your editor. A ref to another computed field pastes that field’s expression in turn. The field is read even when a query names no fields (`.eager(false)` leaves it out then), and wherever `$where` or `$sort` names it, the expression is repeated there, in parentheses, since an alias from the `SELECT` list is not visible in those clauses: ```ts title="You write" const products = await pool.findMany(Product, { $select: { id: true, profit: true }, $where: { profit: { $gte: 10 } }, }); ``` PostgreSQL: ```sql SELECT "id", ("Product"."salePrice" - "Product"."cost") "profit" FROM "Product" WHERE ("Product"."salePrice" - "Product"."cost") >= $1 ``` MySQL: ```sql SELECT `id`, (`Product`.`salePrice` - `Product`.`cost`) `profit` FROM `Product` WHERE (`Product`.`salePrice` - `Product`.`cost`) >= ? ``` MariaDB: ```sql SELECT `id`, (`Product`.`salePrice` - `Product`.`cost`) `profit` FROM `Product` WHERE (`Product`.`salePrice` - `Product`.`cost`) >= ? ``` SQLite: ```sql SELECT `id`, (`Product`.`salePrice` - `Product`.`cost`) `profit` FROM `Product` WHERE (`Product`.`salePrice` - `Product`.`cost`) >= ? ``` SQL Server: ```sql SELECT "id", ("Product"."salePrice" - "Product"."cost") "profit" FROM "Product" WHERE ("Product"."salePrice" - "Product"."cost") >= @p1 ``` MongoDB runs no SQL, so it refuses a query naming an expression field. Relation aggregates work on every engine. ## Storing the value: `.stored()` `.stored()` turns the expression into a generated column the database keeps up to date, which you can index and constrain. Queries stay the same, so switching it on or off touches no call site. ```ts @Computed((product) => f.number().nullable().as(sql`${product.salePrice} - ${product.cost}`).stored()) readonly profit?: number | null; ``` PostgreSQL: ```sql CREATE TABLE "Product" ( ... "profit" BIGINT GENERATED ALWAYS AS ("salePrice" - "cost") STORED, ... ) ``` MySQL: ```sql CREATE TABLE `Product` ( ... `profit` BIGINT GENERATED ALWAYS AS (`salePrice` - `cost`) STORED, ... ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` MariaDB: ```sql CREATE TABLE `Product` ( ... `profit` BIGINT GENERATED ALWAYS AS (`salePrice` - `cost`) STORED, ... ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` SQLite: ```sql CREATE TABLE `Product` ( ... `profit` INTEGER GENERATED ALWAYS AS (`salePrice` - `cost`) STORED ) ``` SQL Server: ```sql CREATE TABLE "Product" ( ... "profit" AS ("salePrice" - "cost") PERSISTED, ... ) ``` The engine evaluates the expression whenever a row is inserted or updated, from any client, and a query reads `"profit"` as a plain column. | | Not stored (default) | `.stored()` | `.stored(['update'])` (a stamp) | | - | - | - | - | | Indexable | no | yes | yes | | Expression | anything the engine accepts | deterministic, over the row only | anything, even `currentTimestamp` | A stored field works on Postgres 12+, CockroachDB, MySQL 5.7+, MariaDB 5.2+, SQLite 3.31+ and SQL Server (as `PERSISTED`). `generate:from-db` reads a stored generated column back as a `@Computed` field ending in `.stored()`. A column recomputed on each read (SQL Server’s non-persisted one, SQLite’s `VIRTUAL`) comes back as a plain field for you to adjust. Sync and drift detection do not compare a stored column’s expression, so editing it changes nothing in the database: write a [migration](https://uql-orm.dev/migrations.md) that drops the column and adds it again. ### Stamps: `.stored()` on an event A generated column cannot hold the current time. Give `.stored()` a list of events (`'insert'`, `'update'`) instead, and uql installs a [trigger](https://uql-orm.dev/entities/triggers.md) that writes the column on each one: ```ts import { Computed, currentTimestamp, f } from 'uql-orm'; @Computed(() => f.date().nullable().as(currentTimestamp).stored(['update'])) readonly updatedAt?: Date | null; ``` [`currentTimestamp`](https://uql-orm.dev/entities/basic.md#values-the-database-computes) is the database clock. `.onUpdate(currentTimestamp)` also reads it, but only on writes uql makes. A stamp covers every write, including a console `UPDATE`, a data migration or another service, so use one when writes can come from outside uql. PostgreSQL: ```sql CREATE OR REPLACE FUNCTION "_uql_Product__updatedAt_update_048f80"() RETURNS trigger AS $uql$ BEGIN NEW."updatedAt" := CURRENT_TIMESTAMP; RETURN NEW; END $uql$ LANGUAGE plpgsql; CREATE TRIGGER "_uql_Product__updatedAt_update_048f80" BEFORE UPDATE ON "Product" FOR EACH ROW EXECUTE FUNCTION "_uql_Product__updatedAt_update_048f80"() ``` MySQL: ```sql CREATE TRIGGER `_uql_Product__updatedAt_update_c27c75` BEFORE UPDATE ON `Product` FOR EACH ROW BEGIN SET NEW.`updatedAt` = CURRENT_TIMESTAMP(3); END ``` MariaDB: ```sql CREATE TRIGGER `_uql_Product__updatedAt_update_c27c75` BEFORE UPDATE ON `Product` FOR EACH ROW BEGIN SET NEW.`updatedAt` = CURRENT_TIMESTAMP(3); END ``` SQLite: ```sql CREATE TRIGGER `_uql_Product__updatedAt_update_a3e1d4` AFTER UPDATE ON `Product` FOR EACH ROW BEGIN UPDATE `Product` SET `updatedAt` = (strftime('%Y-%m-%d %H:%M:%f', 'now')) WHERE `Product`.`id` = NEW.`id` AND `Product`.`updatedAt` IS NOT (strftime('%Y-%m-%d %H:%M:%f', 'now')); END ``` SQL Server: ```sql CREATE TRIGGER "_uql_Product__updatedAt_update_471eaf" ON "Product" AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF TRIGGER_NESTLEVEL(@@PROCID) > 1 RETURN; UPDATE "Product" SET "updatedAt" = SYSUTCDATETIME() FROM inserted JOIN deleted ON inserted."id" = deleted."id" WHERE "Product"."id" = inserted."id" AND EXISTS (SELECT "Product"."updatedAt" EXCEPT SELECT SYSUTCDATETIME()); END ``` Postgres and the MySQL family set the value on the incoming row. SQLite and SQL Server run an `UPDATE` right after the write, skipping rows whose stamp already matches so the trigger does not keep firing itself. Either way, the next query reads the new value. A stamp is installed, synced and dropped like any trigger. It cannot read another table; for that, write the trigger yourself. ### Timestamps `createdAt` and `updatedAt` both read the database clock: a default for the first, a stamp for the second. Declared on a base class, each child gets its own trigger: ```ts import { Computed, currentTimestamp, f, Field } from 'uql-orm'; export abstract class Timestamped { @Field(f.date().default(currentTimestamp)) createdAt!: Date; @Computed(() => f.date().nullable().as(currentTimestamp).stored(['update'])) readonly updatedAt?: Date | null; } ``` MongoDB runs no SQL and has no triggers, so it takes the app clock instead, on uql’s writes only: `.onInsert(() => new Date())` and `.onUpdate(() => new Date())`. ## Relation aggregates A relation aggregate reads a to-many relation: `count()`, `sum()`, `min()`, `max()` or `avg()`, and types itself, so it takes no `f` column. ```ts import { Computed, f, Entity, Field, ManyToOne, OneToMany } from 'uql-orm'; @Entity() export class Order { @Field(f.number().autoIncrement()) id?: number; @OneToMany(() => OrderItem, { mappedBy: (item) => item.order }) items?: OrderItem[]; @Computed((order) => order.items.count()) readonly itemCount?: number; @Computed((order) => order.items.sum((item) => item.amount)) readonly total?: number; @Computed((order) => order.items.count({ $where: { refunded: false } })) readonly paidCount?: number; @Computed((order) => order.items.sum((item) => item.amount, { $sort: { amount: -1 }, $limit: 5, }), ) readonly topFiveTotal?: number; } @Entity() export class OrderItem { @Field(f.number().autoIncrement()) id?: number; @Field( f .number() .nullable() .references(() => Order), ) orderId?: number | null; @ManyToOne(() => Order, { references: (item) => item.orderId }) order?: Order; @Field(f.number().nullable()) amount?: number | null; @Field(f.boolean().nullable()) refunded?: boolean | null; } ``` With no related rows, `count` and `sum` read `0`, while `min`, `max` and `avg` read `null`, so include `null` in their type. `sum` and `avg` take only a numeric column. On a many-to-many, `count` counts the links, and an aggregate over a target column reads each target once. `$where` picks which related rows count. A value aggregate over only some rows needs a `$sort` with its `$limit`, as in `topFiveTotal`. A `count` takes `$limit` (and `$skip`) without a `$sort`, which caps the count: it answers “at least 500?” without counting a million rows. Each aggregate is a correlated subquery in the parent’s statement, so no related row is loaded: ```ts title="You write" const orders = await pool.findMany(Order, { $select: { id: true, total: true }, $where: { itemCount: { $gte: 2 } }, }); ``` PostgreSQL: ```sql SELECT "id", (SELECT COALESCE(SUM("items"."amount"), 0) FROM "OrderItem" "items" WHERE "items"."orderId" = "Order"."id") "total" FROM "Order" WHERE (SELECT COUNT(*) FROM "OrderItem" "items_2" WHERE "items_2"."orderId" = "Order"."id") >= $1 ``` MySQL: ```sql SELECT `id`, (SELECT COALESCE(SUM(`items`.`amount`), 0) FROM `OrderItem` `items` WHERE `items`.`orderId` = `Order`.`id`) `total` FROM `Order` WHERE (SELECT COUNT(*) FROM `OrderItem` `items_2` WHERE `items_2`.`orderId` = `Order`.`id`) >= ? ``` MariaDB: ```sql SELECT `id`, (SELECT COALESCE(SUM(`items`.`amount`), 0) FROM `OrderItem` `items` WHERE `items`.`orderId` = `Order`.`id`) `total` FROM `Order` WHERE (SELECT COUNT(*) FROM `OrderItem` `items_2` WHERE `items_2`.`orderId` = `Order`.`id`) >= ? ``` SQLite: ```sql SELECT `id`, (SELECT COALESCE(SUM(`items`.`amount`), 0) FROM `OrderItem` `items` WHERE `items`.`orderId` = `Order`.`id`) `total` FROM `Order` WHERE (SELECT COUNT(*) FROM `OrderItem` `items_2` WHERE `items_2`.`orderId` = `Order`.`id`) >= ? ``` SQL Server: ```sql SELECT "id", (SELECT COALESCE(SUM("items"."amount"), 0) FROM "OrderItem" "items" WHERE "items"."orderId" = "Order"."id") "total" FROM "Order" WHERE (SELECT COUNT(*) FROM "OrderItem" "items_2" WHERE "items_2"."orderId" = "Order"."id") >= @p1 ``` On MongoDB it renders as a `$lookup` ending in `$count` or `$group`. Like a relation, an aggregate is read only when a query names it in `$select`, `$where` or `$sort`. An aggregate cannot be `.stored()`. # Soft Delete > Soft delete marks rows deleted instead of removing them. In UQL one field keeps them out of every query by default and lets you restore them later. Source: https://uql-orm.dev/entities/soft-delete A soft delete stamps a row as deleted instead of removing it. The row drops out of queries, but you can still restore or audit it, and rows pointing at it stay valid. Chain `.softDelete()` on one field to enable it: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity() export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.column('timestamptz').nullable().softDelete()) deletedAt?: Date | null; } ``` `.softDelete()` stamps `new Date()`. To stamp something else, pass it a value, SQL such as `currentTimestamp`, or a callback, like `() => Date.now()` for an epoch-millis column. An entity has at most one soft-delete field. ## Deleting and reading A delete becomes an update that stamps only rows not already deleted: ```ts title="You write" await pool.deleteOneById(User, 1); ``` PostgreSQL: ```sql UPDATE "User" SET "deletedAt" = $1 WHERE "id" = $2 AND "deletedAt" IS NULL ``` MySQL: ```sql UPDATE `User` SET `deletedAt` = ? WHERE `id` = ? AND `deletedAt` IS NULL ``` MariaDB: ```sql UPDATE `User` SET `deletedAt` = ? WHERE `id` = ? AND `deletedAt` IS NULL ``` SQLite: ```sql UPDATE `User` SET `deletedAt` = ? WHERE `id` = ? AND `deletedAt` IS NULL ``` SQL Server: ```sql UPDATE "User" SET "deletedAt" = @p1 WHERE "id" = @p2 AND "deletedAt" IS NULL ``` Every read leaves deleted rows out, through the built-in `softDelete` [query filter](https://uql-orm.dev/querying/filters.md), which combines with any filters you define: ```ts title="You write" const users = await pool.findMany(User, { $select: { id: true, name: true } }); ``` PostgreSQL: ```sql SELECT "id", "name" FROM "User" WHERE "deletedAt" IS NULL ``` MySQL: ```sql SELECT `id`, `name` FROM `User` WHERE `deletedAt` IS NULL ``` MariaDB: ```sql SELECT `id`, `name` FROM `User` WHERE `deletedAt` IS NULL ``` SQLite: ```sql SELECT `id`, `name` FROM `User` WHERE `deletedAt` IS NULL ``` SQL Server: ```sql SELECT "id", "name" FROM "User" WHERE "deletedAt" IS NULL ``` ## Reading deleted rows The filter steps aside when your `$where` names the field, so reading only deleted rows is a plain query, which works over HTTP too. To read live and deleted rows together, pass `withDeleted()`, a server-side option that never travels over the wire. It covers the read’s own rows; populated relations still hide their deleted ones. Given options, `withDeleted(opts)` returns them with soft-deleted rows let in. ```ts import { withDeleted } from 'uql-orm'; const trashed = await pool.findMany(User, { $where: { deletedAt: { $ne: null } }, }); const all = await pool.findMany(User, {}, withDeleted()); ``` ## Restoring and hard deletes `restoreOneById` and `restoreMany` set the field back to `null`, finding deleted rows despite the filter. `{ hardDelete: true }` removes rows for good, already-deleted ones included: ```ts await pool.restoreMany(User, { $where: { name: 'Ada' } }); await pool.deleteOneById(User, 1, { hardDelete: true }); ``` A soft delete [cascades](https://uql-orm.dev/entities/relations.md#writing-related-rows-cascade) only to related entities that also soft-delete, and keeps the rest. A restore does not cascade, so restore related rows yourself. # Optimistic Locking > Guard an update with a version column, so a write against a row someone else changed throws instead of overwriting it. Source: https://uql-orm.dev/entities/optimistic-locking A version column stops one user from overwriting another’s changes. An update sends the version it read, and matches only if the row is still at that version. It works across requests, on every engine. ```ts import { f, Entity, Field, filledKey, versionKey } from 'uql-orm'; import { v7 as uuidv7 } from 'uuid'; @Entity() export class Post { [versionKey]?: 'version'; [filledKey]?: 'id'; @Field(f.uuid().id().onInsert(uuidv7)) id!: string; @Field(f.string().nullable()) title?: string | null; @Field(f.version()) version!: number; } ``` The `[versionKey]` line tells TypeScript which field is the version, since decorator options never reach the type. With it, an update that leaves out the version does not compile: ```ts const postId = '0190a1b2-c3d4-7e5f-8a6b-7c8d9e0f1a2b'; const post = await pool.findOneById(Post, postId); // version: 3 await pool.updateOneById(Post, postId, { title: 'Edited', version: post!.version, }); ``` PostgreSQL: ```sql UPDATE "Post" SET "title" = $1, "version" = $2 WHERE "id" = $3 AND "version" = $4 ``` MySQL: ```sql UPDATE `Post` SET `title` = ?, `version` = ? WHERE `id` = ? AND `version` = ? ``` MariaDB: ```sql UPDATE `Post` SET `title` = ?, `version` = ? WHERE `id` = ? AND `version` = ? ``` SQLite: ```sql UPDATE `Post` SET `title` = ?, `version` = ? WHERE `id` = ? AND `version` = ? ``` SQL Server: ```sql UPDATE "Post" SET "title" = @p1, "version" = @p2 WHERE "id" = @p3 AND "version" = @p4 ``` If someone saved first, the update matches nothing and throws `UqlOptimisticLockError`, with `expected` and `actual` versions and a message saying whether the version moved on, the row is gone, or another `$where` condition excluded it. [`queryErrorKind(err)`](https://uql-orm.dev/querying/errors.md) answers `'optimisticLock'`, and over [HTTP](https://uql-orm.dev/http.md) it is a `409`. ```ts import { UqlOptimisticLockError } from 'uql-orm'; try { await pool.updateOneById(Post, postId, { title: 'Edited', version: 3 }); } catch (err) { if (err instanceof UqlOptimisticLockError) { // err.expected === 3, err.actual === 4 } } ``` ## Rules The column is `NOT NULL DEFAULT 0` and uql writes it, so `f.version()` takes only `.name()` and `.comment()`: nothing else may decide its value. An update without a version that slips past the compiler throws `UqlUsageError` (a `400` over HTTP). A versioned update names one row by its primary key, with other conditions beside it if you like (`{ id, tenantId }`). It must be a single statement, so these are refused: - `updateMany` over a filter matching many rows. - `$sort`, `$limit` or `$skip`, and a payload that writes a relation. - A `$where` on a relation, on engines that cannot filter by one in an `UPDATE`. `saveOne`, `saveMany`, `upsertOne` and `upsertMany` read the rows first, in a transaction (on MongoDB, in one you open): one they find is updated by its id at the version it carries, as above, and the rest are inserted. `deleteOneById`, `restoreOneById` and `restoreMany` take no version and leave it alone. ## Version or row lock [`$lock`](https://uql-orm.dev/querying/locking.md) holds a row until the transaction ends. A user who loads a form and saves it a minute later makes two requests, and only a version covers that. | | `$lock` | `version` | | - | - | - | | Covers | one transaction | any number of requests | | Costs | a held lock, and waiting writers | a retry when a conflict happens | | Engines | all but SQLite, libSQL, Turso, D1 and MongoDB | all | | Fails by | waiting, or `$wait: 'nowait'` | throwing `UqlOptimisticLockError` | | Error kind | `'retryable'` | `'optimisticLock'` | Use `$lock` when the read and the write share a transaction and contention is likely. Use a version when they do not, which on the web is most of the time. # Lifecycle Hooks > Run your own code before and after inserts, updates, upserts, deletes and loads, per entity or for every entity. Source: https://uql-orm.dev/entities/lifecycle-hooks Hooks run your code at points in an entity’s lifecycle: validating input, filling a slug, masking data after a read, sending a mail after a write. ```ts import { f, Entity, Field, BeforeInsert, AfterLoad } from 'uql-orm'; @Entity() export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) slug?: string | null; @Field(f.string().nullable()) internalCode?: string | null; @BeforeInsert() generateSlug() { if (this.title) { this.slug = this.title.toLowerCase().replace(/\s+/g, '-'); } } @AfterLoad() maskInternalCode() { this.internalCode = '***'; } } ``` ## Events | Operation | Before | After | | - | - | - | | insert | `@BeforeInsert()` | `@AfterInsert()` | | update | `@BeforeUpdate()` | `@AfterUpdate()` | | upsert | `@BeforeUpsert()` | `@AfterUpsert()` | | delete | `@BeforeDelete()` | `@AfterDelete()` | | load | | `@AfterLoad()` | A hook runs once per payload, with `this` bound to it: the record for an insert, the update payload for an update, each row for a load or a delete. Populated rows run `@AfterLoad` too, children before their parent, and `findManyStream` runs it on each row as it arrives. `upsertOne` and `upsertMany` run only the upsert pair, never insert or update, because the database picks the branch while the statement runs. `saveOne` and `saveMany` run the upsert pair for a row that includes its key, and the insert pair for one that does not. ## What a hook can change In `@BeforeInsert` and `@BeforeUpdate`, changes to `this` are written. In `@AfterLoad`, they reach the result, which is how you derive or mask values. The `after*` write hooks are for side effects such as logging, cache invalidation or notifications. `this` is a copy of the row as written, so `@AfterInsert` sees the generated id and every `.onInsert()` value, `@AfterUpdate` every `.onUpdate()` value, and `@AfterUpsert` the id the database reported. The object you passed is left alone. Throwing from an after-hook fails the call, but the row stays written unless a transaction is open. ## The hook context Every hook receives a `HookContext`. Its `querier` is the one running the write, so the hook’s queries join its transaction. Its `onCommit` defers a callback until the transaction [commits](https://uql-orm.dev/querying/transactions.md#after-the-commit-oncommit). An after-hook runs before the commit, so a mail sent straight from it would go out even if a rollback undoes the row. `async` hooks are awaited. A hook refuses a write by throwing. Over [HTTP](https://uql-orm.dev/http.md), a `UqlError` answers the client its own status and message, as `UqlRequestError` does below; any other error answers a `500`. ```ts import { AfterInsert, f, type HookContext, UqlRequestError } from 'uql-orm'; @Entity() export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) email?: string | null; @BeforeInsert() async validateEmail({ querier }: HookContext) { if (await querier.count(User, { $where: { email: this.email } })) throw new UqlRequestError('Email taken', 409); } @AfterInsert() async welcome({ onCommit }: HookContext) { await onCommit(() => mailer.welcome(this.email)); } } ``` > **Caution** > > While `findManyStream` holds a querier, a hook cannot query through it. Use another querier. ## Delete hooks `@BeforeDelete` and `@AfterDelete` both see the row as it was before the delete, so an `@AfterDelete` can still name what it removed: ```ts import { AfterDelete, f } from 'uql-orm'; @Entity() export class Attachment { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) storageKey?: string | null; @AfterDelete() async dropFile(this: Attachment) { await bucket.delete(this.storageKey!); } } ``` They also run for soft deletes and for children removed by a `cascade: 'delete'` relation. Reading the rows first costs one extra query, paid only when a delete hook or listener exists. ## Order Hooks for one event run in declaration order, and one method can serve several events. A parent’s hooks are inherited and run first: ```ts import { BeforeInsert, BeforeUpdate, Entity, Field, f, UqlRequestError, } from 'uql-orm'; class BaseEntity { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) slug?: string | null; @BeforeInsert() @BeforeUpdate() normalizeSlug() { this.slug = this.slug?.trim().toLowerCase(); } } @Entity() class Post extends BaseEntity { @Field(f.string().nullable()) title?: string | null; @BeforeInsert() validate() { if (!this.title) throw new UqlRequestError('Title is required', 400); } } // on insert: normalizeSlug(), then validate() ``` ## Global listeners For logic that applies to every entity, such as audit logging, register listeners on the pool: ```ts import { type QuerierListener } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; const auditListener: QuerierListener = { afterInsert({ entity, payloads }) { console.log(`Inserted ${payloads.length} ${entity.name} records`); }, }; const pool = new PgQuerierPool( { connectionString: process.env.DATABASE_URL }, { listeners: [auditListener] }, ); ``` A listener receives the `entity` class, the `payloads`, the `event` name and the `querier` running the write. Listeners run before entity hooks, in registration order, so a listener can set audit metadata the hooks then read. Hooks and listeners run in uql, so they behave the same on every engine but do not see writes made outside uql. For those, use a [trigger](https://uql-orm.dev/entities/triggers.md). # Triggers > Declare database triggers in the entity's triggers option, rendered for every SQL engine and kept in sync by migrations. Source: https://uql-orm.dev/entities/triggers `@Entity({ triggers })` declares database triggers on an entity. It fires on every write to the table, whether from uql, a console `UPDATE`, a data migration or another service. uql types it against the entity, renders it for each SQL engine, and installs it with `sync` and generated migrations. This one logs every status change of a post: Decorators: ```ts import { f, Entity, Field, insertInto } from 'uql-orm'; @Entity() export class PostAudit { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().name('post_id')) postId!: number; @Field(f.string().nullable().name('from_status')) fromStatus?: Post['status'] | null; @Field(f.string().nullable().name('to_status')) toStatus?: Post['status'] | null; } @Entity({ triggers: (post, trigger) => [ trigger({ on: 'afterUpdate', name: 'audit', of: [post.status], run: (newRow, oldRow) => insertInto(PostAudit, { postId: newRow.id, fromStatus: oldRow.status, toStatus: newRow.status, }), }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` defineEntity: ```ts import { f, defineEntity, insertInto } from 'uql-orm'; export const PostAudit = defineEntity({ name: 'PostAudit', fields: { id: f.number().autoIncrement(), postId: f.number().name('post_id'), fromStatus: f.string().nullable().name('from_status'), toStatus: f.string().nullable().name('to_status'), }, }); export const Post = defineEntity({ name: 'Post', fields: { id: f.number().autoIncrement(), status: f.string().nullable(), views: f.number().nullable(), }, }).triggers((post, trigger) => [ trigger({ on: 'afterUpdate', name: 'audit', of: [post.status], run: (newRow, oldRow) => insertInto(PostAudit, { postId: newRow.id, fromStatus: oldRow.status, toStatus: newRow.status, }), }), ]); ``` `on` is the event. `of`, on update events, fires the trigger only when one of the listed columns changes value. `run` returns the SQL to run, reading the rows through refs such as `newRow.status`. `name` is an optional [label](#naming). Without decorators, [`defineEntity`](https://uql-orm.dev/entities/define-entity.md)’s `.triggers()` section takes the same entries. ## What uql renders Column names come from the entities, so `postId` becomes `post_id`. Each engine fires only when `status` actually changes: PostgreSQL: ```sql CREATE OR REPLACE FUNCTION "_uql_Post__audit_0a57e9"() RETURNS trigger AS $uql$ BEGIN INSERT INTO "PostAudit" ("post_id", "from_status", "to_status") VALUES (NEW."id", OLD."status", NEW."status"); RETURN NULL; END $uql$ LANGUAGE plpgsql; CREATE TRIGGER "_uql_Post__audit_0a57e9" AFTER UPDATE OF "status" ON "Post" FOR EACH ROW WHEN (OLD."status" IS DISTINCT FROM NEW."status") EXECUTE FUNCTION "_uql_Post__audit_0a57e9"() ``` MySQL: ```sql CREATE TRIGGER `_uql_Post__audit_94c077` AFTER UPDATE ON `Post` FOR EACH ROW BEGIN IF NOT (OLD.`status` <=> NEW.`status`) THEN INSERT INTO `PostAudit` (`post_id`, `from_status`, `to_status`) VALUES (NEW.`id`, OLD.`status`, NEW.`status`); END IF; END ``` MariaDB: ```sql CREATE TRIGGER `_uql_Post__audit_94c077` AFTER UPDATE ON `Post` FOR EACH ROW BEGIN IF NOT (OLD.`status` <=> NEW.`status`) THEN INSERT INTO `PostAudit` (`post_id`, `from_status`, `to_status`) VALUES (NEW.`id`, OLD.`status`, NEW.`status`); END IF; END ``` SQLite: ```sql CREATE TRIGGER `_uql_Post__audit_08d35c` AFTER UPDATE OF `status` ON `Post` FOR EACH ROW WHEN (OLD.`status` IS NOT NEW.`status`) BEGIN INSERT INTO `PostAudit` (`post_id`, `from_status`, `to_status`) VALUES (NEW.`id`, OLD.`status`, NEW.`status`); END ``` SQL Server: ```sql CREATE TRIGGER "_uql_Post__audit_d8fbff" ON "Post" AFTER UPDATE AS BEGIN SET NOCOUNT ON; INSERT INTO "PostAudit" ("post_id", "from_status", "to_status") SELECT inserted."id", deleted."status", inserted."status" FROM inserted JOIN deleted ON inserted."id" = deleted."id" WHERE EXISTS (SELECT deleted."status" EXCEPT SELECT inserted."status"); END ``` CockroachDB renders the Postgres function with the change check inside it, as an `IF`, on a plain `AFTER UPDATE` trigger. ## Writing a table: `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` These helpers cover most trigger bodies; `insertInto` is in the example above. Each is typed by the entity it writes, so an unknown field, a wrongly typed value or a `$where` on a relation does not compile: ```ts import { deleteFrom, updateTable } from 'uql-orm'; @Entity({ triggers: (_post, trigger) => [ trigger({ on: 'afterUpdate', run: (newRow) => updateTable( PostAudit, { $where: { postId: newRow.id } }, { toStatus: newRow.status }, ), }), trigger({ on: 'afterDelete', run: (_newRow, oldRow) => deleteFrom(PostAudit, { $where: { postId: oldRow.id } }), }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` `upsertInto` inserts a row or updates the one its conflict keys find, like [`upsertOne`](https://uql-orm.dev/querying/methods.md#upsert-operations), a `$where` included. The existing row takes the incoming values unless the query has an `$update`, such as a running total: ```ts import { f } from 'uql-orm'; @Entity() export class PostStats { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable().unique()) postId?: number | null; @Field(f.number().nullable()) edits?: number | null; } ``` ```ts import { upsertInto } from 'uql-orm'; @Entity({ triggers: (_post, trigger) => [ trigger({ on: 'afterUpdate', run: (newRow) => upsertInto( PostStats, { $conflict: { postId: true }, $update: { edits: { $inc: 1 } } }, { postId: newRow.id, edits: 1 }, ), }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` In that `$update`, SQL can read the existing row (``sql`${refs(PostStats).edits} + 1` ``), `$inc` can step by a column of the changed row (`{ $inc: newRow.amount }`), and `{}` leaves the row as it is. A trigger runs inside the database, so uql adds nothing to what it writes: - An insert fills an `.onInsert()` value or SQL, but runs no callback, and no `.onUpdate()` applies. An insert leaving out a required column that only a callback fills (`.onInsert(() => crypto.randomUUID())`) is refused unless the column has a `.default()`: name it, as SQL if needed, ``id: sql`gen_random_uuid()` ``. - No entity filters apply. `deleteFrom` on a soft-delete entity removes the row, and security filters are not added, so scope each write by the row’s columns: `{ tenantId: newRow.tenantId }`. - An update or delete whose `$where` names no rows is refused, as in the querier. - SQL Server refuses `$inc`, `$mul` and `$push`: its trigger runs once per statement, so an `$inc` would count once when several changed rows match it. ## Conditions: `where` `of` checks whether a column changed; `where` checks anything else. Conditions on the new row go under `$new`, on the old one under `$old`, with the usual `$where` operators. With both, `where` matches a transition: ```ts @Entity({ triggers: (_post, trigger) => [ trigger({ on: 'afterUpdate', where: { $old: { status: 'draft' }, $new: { status: { $in: ['published', 'featured'] } }, }, run: (newRow, oldRow) => insertInto(PostAudit, { postId: newRow.id, fromStatus: oldRow.status }), }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` For anything else, `where` takes SQL: ``where: (newRow, oldRow) => sql`${newRow.views} > 2 * ${oldRow.views}` ``. No soft-delete or security filter is added. ## Events and rows `run` and a `where` callback always receive `(newRow, oldRow)`, in that order. Insert events have only `newRow`, delete events only `oldRow`, and update events both; reading a row the event lacks is a compile error. Since the positions never change, one body reading only `oldRow` serves an update trigger and a delete trigger alike. ## Your own SQL Any SQL the engine runs can be the body, written with `sql`. Refs render as columns, and helpers can sit inside the same `sql`: ```ts import { deleteFrom, sql } from 'uql-orm'; @Entity({ triggers: (_post, trigger) => [ trigger({ on: 'afterDelete', run: (_newRow, oldRow) => sql`${deleteFrom(PostAudit, { $where: { postId: oldRow.id } })} DELETE FROM post_cache;`, }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` uql does not translate your SQL. It must run on every engine you use, or give a [body per engine](#sql-server). ## Refusing a write: `refuse` `refuse(message)` fails the write that fired the trigger, on every engine. It keeps a table append-only or, with a `where`, refuses only some rows: ```ts import { refuse } from 'uql-orm'; @Entity({ triggers: (_entry, trigger) => [ trigger({ on: 'beforeDelete', run: () => refuse('ledger entries are kept'), }), trigger({ on: 'beforeUpdate', where: { $old: { posted: true } }, run: () => refuse('a posted entry is final'), }), ], }) export class LedgerEntry { @Field(f.number().autoIncrement()) id?: number; @Field(f.number()) transactionId!: number; @Field(f.number()) amount!: number; @Field(f.boolean()) posted!: boolean; } ``` SQL Server has no `before*` events. Use `afterUpdate` and `afterDelete` there; they still roll the statement back. ## Deferred to commit: `deferred` On Postgres, `deferred: true` fires an `after*` trigger at commit instead of after each statement, so a check sees every write in the transaction. A ledger whose entries must sum to zero can then take them in any order. Other engines refuse it. ```ts import { refuse, sql } from 'uql-orm'; @Entity({ triggers: (_entry, trigger) => [ trigger({ on: 'afterInsert', deferred: true, run: { postgres: (newRow) => sql`IF (SELECT SUM(amount) FROM ledger_entry WHERE transaction_id = ${newRow.transactionId}) <> 0 THEN ${refuse('a ledger transaction must balance')} END IF;`, }, }), ], }) export class LedgerEntry { @Field(f.number().autoIncrement()) id?: number; @Field(f.number()) transactionId!: number; @Field(f.number()) amount!: number; @Field(f.boolean()) posted!: boolean; } ``` ## Sync and migrations `sync` and `generate:entities` install the triggers an entity declares and drop the ones it no longer declares. They leave an unchanged trigger alone and replace an edited one, so a second `sync` runs nothing. A trigger whose name does not start with `_uql_` is never touched. You can retype, rename or drop a column a trigger names. Postgres refuses a retype or drop while the trigger exists, so uql drops the trigger and restores it around the change. A trigger naming none of the changed columns stays in place. ### Naming The installed name is `_uql_`, the table, your `name` and a hash of the SQL: `name: 'audit'` installs as `_uql_Post__audit_0a57e9` on Postgres. Without a `name`, the label is the event and the trigger’s position, such as `afterUpdate_0`. ## Engine notes ### MySQL With binary logging on (the MySQL default), a user without `SUPER` cannot create triggers unless you set `log_bin_trust_function_creators = 1`, in the parameter group on managed MySQL. MariaDB needs nothing. ### SQL Server SQL Server fires a trigger once per statement, with `inserted` and `deleted` tables instead of single rows, and has no `before*` events. An update pairs the two tables by primary key, so a statement that changes a row’s key leaves that row out of `of`, `where` and the body. The write helpers work there unchanged. Your own SQL reads `inserted` and `deleted` whole, so it is refused alongside `of` or `where`. To support SQL Server and another engine, give a body per engine: ```ts @Entity({ triggers: (_post, trigger) => [ trigger({ on: 'afterInsert', run: { postgres: (newRow) => sql`PERFORM pg_notify('post_status', ${newRow.id}::text);`, mssql: () => sql`INSERT INTO post_outbox (post_id) SELECT id FROM inserted;`, }, }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) views?: number | null; } ``` `postgres` also covers CockroachDB, and `mysql` covers MariaDB. A map missing the engine in use is refused at `sync`. ### MongoDB MongoDB has no trigger that runs within a write, so it refuses writes to an entity that declares one, a [stamp](https://uql-orm.dev/entities/computed-fields.md#stamps-stored-on-an-event) included. Atlas Database Triggers run after the commit, so they cannot block, roll back with or stamp a write. For logic that needs to follow only uql’s own writes, use a [lifecycle hook](https://uql-orm.dev/entities/lifecycle-hooks.md). # Indexes > Declare single-column, composite, partial, JSON, full-text and vector indexes on your entities. Source: https://uql-orm.dev/entities/indexes Use `.index()` on a column to index it and `@Entity({ indexes })` for anything more. [Migrations](https://uql-orm.dev/migrations.md) create and update them. Decorators: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (auditLog, index) => [ index( [auditLog.entityType, auditLog.entityId, auditLog.createdAt], 'audit_lookup_idx', ), ], }) export class AuditLog { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable().index()) // named AuditLog__action_idx action?: string | null; @Field(f.string().nullable()) entityType?: string | null; @Field(f.string().nullable()) entityId?: string | null; @Field(f.column('timestamptz').nullable()) createdAt?: Date | null; } ``` defineEntity: ```ts import { f, defineEntity } from 'uql-orm'; export const AuditLog = defineEntity({ name: 'AuditLog', fields: { id: f.number().autoIncrement(), action: f.string().nullable().index(), entityType: f.string().nullable(), entityId: f.string().nullable(), createdAt: f.column('timestamptz').nullable(), }, }).indexes((auditLog, index) => [ index( [auditLog.entityType, auditLog.entityId, auditLog.createdAt], 'audit_lookup_idx', ), ]); export interface AuditLog extends InstanceType {} ``` An entry reads its columns off the class, so a typo is a compile error and an editor rename updates every index. Every foreign key column gets an index of its own, unless the primary key, a unique column or another index already leads with it. A partial, full-text, GIN, GiST, BRIN, vector or prefix (`prefixLength`) index does not count. `.index(false)` opts a column out. ## Index options | Option | What it does | | - | - | | `name` | Index name. Defaults to `
___idx`. | | `unique` | Enforce uniqueness, e.g. one email per tenant: `index([u.email, u.tenantId], { unique: true })`. | | `type` | Engine-specific index type, see [Index types](#index-types). | | `where` | Makes it a [partial index](#partial-indexes). | | `include` | Extra columns stored in the index (`INCLUDE`), `(user) => [user.name]`. Postgres and CockroachDB. | | `distance` | Vector metric, such as `'cosine'` or `'l2'`. Required for `'hnsw'`, `'ivfflat'` and `'vector'`. | | `m`, `efConstruction`, `lists` | Vector tuning: HNSW connections per node; build-time candidate list (`ef_construction`, CockroachDB’s `build_beam_size`, libSQL’s `insert_l`); IVFFlat lists. | | `config` | `fulltext` stemming language, such as `'english'`. Default `'simple'`. PostgreSQL, CockroachDB, MongoDB. | ### Index types | Engine | `type` values | | - | - | | PostgreSQL | `btree`, `hash`, `gin`, `gist`, `brin`, `hnsw`, `ivfflat`, `fulltext` | | CockroachDB | `btree`, `gin`, `gist`, `vector`, `hnsw` (both its vector index), `fulltext` | | MySQL | `btree`, `hash`, `fulltext` | | MariaDB | `btree`, `hash`, `fulltext`, `vector` | | MSSQL | `btree` | | SQLite | any, each built as a plain index, so Postgres entities migrate unchanged | A type or option the engine cannot express throws, naming the index, when the migration is generated. On MongoDB, `order` maps to `1`/`-1`, `fulltext` creates a `text` index, and SQL-only options are refused. ## Per-column options Each entry is a member, a `sql` expression over members, or an object with more options: ```ts import { f, Entity, Field, type Json, sql } from 'uql-orm'; @Entity({ indexes: (note, index) => [ // keyset pagination index([note.tenantId, { column: note.createdAt, order: 'desc' }]), // case-insensitive unique index([sql`lower(${note.email})`], { unique: true }), // MySQL TEXT needs a prefix index([{ column: note.body, prefixLength: 64 }]), index([{ column: note.data, opsClass: 'jsonb_path_ops' }], { type: 'gin' }), ], }) export class Note { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) tenantId?: string | null; @Field(f.column('timestamptz').nullable()) createdAt?: Date | null; @Field(f.string().nullable()) email?: string | null; @Field(f.text().nullable()) body?: string | null; @Field(f.jsonb().nullable()) data?: Json<{ source?: string }> | null; } ``` | Option | What it does | Engines | | - | - | - | | `column` | The member, a path inside a JSON one, or `sql` for an expression. | expressions: all but MariaDB and MSSQL | | `order` | `'asc'` (default) or `'desc'`, the order stored in the index. | all | | `prefixLength` | Index only the first *n* characters of a column. Required for `TEXT` on MySQL. | MySQL, MariaDB | | `charLength` | The `CHAR(n)` a string [JSON path](#json-indexes) or element is keyed as. | MySQL | | `type` | How a [JSON path](#json-indexes) is read; `[type]` for each element of an array. | Postgres, CockroachDB, SQLite, MySQL, MongoDB | | `nulls` | `'first'` or `'last'`. | Postgres | | `opsClass` | Operator class, e.g. `jsonb_path_ops`. | Postgres | | `weight` | How much a match in this column counts in [full-text](#full-text-indexes) ranking. | all with full-text search | ### JSON indexes Read the path off the JSON column’s ref, as the `$where` key it serves. The index matches the expression your queries compile to, which a hand-written index often does not, and the path is checked against the column’s type, so a typo is a compile error. A path holding text needs nothing more; any other states its `type`, and `[type]` indexes each element of an array: ```ts import { f } from 'uql-orm'; @Entity({ indexes: (account, index) => [ index([account.settings.theme.color]), index([{ column: account.settings.rating, type: Number }]), index([{ column: account.tags, type: [String], charLength: 64 }]), ], }) export class Account { @Field(f.number().autoIncrement()) id?: number; @Field(f.jsonb().nullable()) settings?: Json<{ theme: { color: string }; rating: number }> | null; // serves 'settings.theme.color': 'red' @Field(f.jsonb().nullable()) tags?: Json | null; // serves tags: { $all: ['admin'] } } ``` On MySQL a string path or element needs a `charLength`, the text it is cast to, which every other engine, casting nothing, ignores; a boolean path cannot be indexed there. An array’s elements are MySQL’s multi-valued index and MongoDB’s multikey one, which serve `$all` and an `$elemMatch` asking for one or several strings or numbers. On SQL engines a full-text index holds whole columns, never a JSON path. ## Partial indexes A partial index covers only rows matching `where`, so it stays small. With [soft delete](https://uql-orm.dev/entities/soft-delete.md), it can keep emails unique among live rows only: ```ts @Entity({ indexes: (user, index) => [ index([user.email], { unique: true, where: { deletedAt: null } }), ], }) export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) email?: string | null; @Field(f.date().nullable()) deletedAt?: Date | null; } ``` `where` is a `$where` predicate, checked against the entity, with values written in as literals. The entity’s own filters are not added. Prefer it to a callback returning [`sql`](https://uql-orm.dev/querying/raw-sql.md): the planner uses the index only when the query’s filter has the same shape, so ``sql`${user.archived} IS NOT TRUE` ``never serves `{ archived: { $ne: true } }`. > **Engine support** > > MySQL and MariaDB have no partial indexes, so `where` throws there. SQL Server takes only comparisons, `$in`, `$isNull` and `$isNotNull` joined by `AND`. MongoDB takes equality, `$gt`, `$gte`, `$lt`, `$lte`, `$between`, `$in`, `$and` and `$or`, but no `null`, `$ne`, `$nin`, `sql` or `Date` value, so `{ deletedAt: null }` cannot be expressed. ## Full-text indexes A `fulltext` index is what [`$text`](https://uql-orm.dev/querying/full-text.md) searches, on every engine that has full-text search. A column’s `weight` (1 to 99999, default 1) sets how much its matches count when `$sort: { $text }` ranks: ```ts @Entity({ indexes: (listing, index) => [ index([{ column: listing.title, weight: 3 }, listing.description], { type: 'fulltext', config: 'spanish', }), ], }) export class Listing { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) description?: string | null; } ``` It builds a `GIN` index on PostgreSQL and CockroachDB, a `FULLTEXT` index on MySQL and MariaDB (plus one per column heavier than the lightest), and a weighted `text` index on MongoDB. See [column weights](https://uql-orm.dev/querying/full-text.md#column-weights). ## Vector indexes A vector index serves [semantic search](https://uql-orm.dev/querying/semantic-search.md). `distance` is required on it, and a compile error on any other index. Match the metric your queries sort by: on MariaDB, a cosine query against a euclidean index scans the whole table. ```ts @Entity({ indexes: (article, index) => [ index([article.embedding], { type: 'hnsw', distance: 'cosine', m: 16, efConstruction: 64, }), ], }) export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.vector(1536).nullable()) embedding?: number[] | null; } ``` Changing `m` or `efConstruction` rebuilds it in the next migration. See [Semantic search](https://uql-orm.dev/querying/semantic-search.md#vector-indexes) for each engine’s vector indexes. ## Synchronization `generate:entities` and `sync` create each index with every option the engine supports. An existing index is matched by name, then by columns, and rebuilt if it differs. An index you stop declaring is dropped (by a generated migration or `sync --unsafe`) only if uql named it or a declared index now takes its name. Indexes you named by hand are left alone. `generate:from-db` goes the other way: a plain single-column index becomes `.index()`, anything else an `indexes` entry. [`drift:check`](https://uql-orm.dev/migrations.md#drift-detection) compares what each engine reports: | Engine | Compared | | - | - | | Postgres | Columns and their order, uniqueness, access method, `INCLUDE` columns, operator class, a vector index’s distance | | CockroachDB | The same, except nulls order and operator class | | MariaDB, libSQL | Columns, uniqueness, a vector index’s distance | | MySQL, MSSQL, SQLite | Columns and uniqueness | Expressions and JSON paths are never compared, since the database reprints them in its own spelling. An unnamed JSON index carries its path in its name (`Row__kind_theme_idx`), so changing the path replaces it; one you name keeps its name, so changing its path is a migration you write. An unnamed partial index carries a hash of its `where` in its name (`Order__total_3fa9c1_idx`), so editing the predicate replaces the index. A partial index you name keeps its name, so editing its predicate is a migration you write. # Enum + Checks > Enum fields and table-level CHECK constraints, so the database enforces what the entity declares. Source: https://uql-orm.dev/entities/enum-checks Constraints limit the values a column or row may hold. Declare them on the entity, and uql creates them with the table. ## Enum fields `enum` lists the values a column accepts. The database enforces them with a `CHECK (col IN (...))`, and the property type must not allow anything outside the list: ```ts import { Entity, Field, f } from 'uql-orm'; @Entity() export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.enum(['draft', 'paid', 'void']).nullable()) status?: 'draft' | 'paid' | 'void' | null; } ``` Values are strings or numbers. A list written inline needs nothing more; one held in a constant needs `as const` (`const CURRENCIES = ['COP', 'MXN'] as const`), or its values widen to `string`. Builders are immutable, so `const currency = f.enum(CURRENCIES)` can be shared across entities, each adding its own `.nullable()` or `.updatable(false)`. A check rather than PostgreSQL’s `CREATE TYPE ... AS ENUM` works on every engine, and changing the list is an ordinary migration. A TypeScript string enum works too, without `as const`. Type the property as the enum itself, since the enum does not accept the matching literal union: ```ts import { Entity, Field, f } from 'uql-orm'; enum Status { Draft = 'draft', Paid = 'paid', } @Entity() export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.enum(Object.values(Status)).nullable()) status?: Status | null; } ``` Numeric enums do not work: they accept any `number`, and `Object.values` also returns their member names. Write the values as literals, `f.enum([0, 1] as const)` with a `0 | 1` property. ## Check constraints `@Entity({ checks })` adds conditions over the whole row. Write each as a `$where` predicate, or as a callback returning [`sql`](https://uql-orm.dev/querying/raw-sql.md) for what a predicate cannot say: ```ts import { Entity, Field, f, sql } from 'uql-orm'; @Entity({ checks: (wallet, check) => [ check({ creditsBalance: { $gte: 0 } }, 'wallet_non_negative_ck'), check(sql`${wallet.spent} <= ${wallet.creditsBalance}`), ], }) export class Wallet { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) creditsBalance?: number | null; @Field(f.number().nullable()) spent?: number | null; } ``` Columns are quoted for the engine and follow a rename. Values are written as literals, since DDL cannot bind them: `{ stock: { $gt: 0 } }` becomes `CHECK ("stock" > 0)`. ## How a change is detected A check is installed as `_uql_
___`: `` is yours (`ck` if unnamed, the column’s for an enum) and the hash is of its SQL. Databases reprint a check in their own spelling, so `generate:entities`, `sync` and `drift:check` compare these names, not the SQL. Editing a check, or adding or removing an enum value, changes the hash, so the old check is dropped and the new one added. An enum’s values are sorted first, so reordering them changes nothing, in a `CHECK` or MongoDB’s validator. SQLite cannot alter a constraint, so there the table is rebuilt. > **Caution** > > `sync` in its default safe mode never drops a check. A changed check is added beside the old one, which keeps enforcing until a migration or `sync` with `safe: false` drops it. A check without the `_uql_` prefix is never touched. uql warns about each one on a table whose entity declares checks, so you can drop it by hand if a declared check replaces it. ## MongoDB MongoDB enforces checks and enums as one collection validator: each check’s `where`, then each enum as `{ field: { $in: [...values, null] } }`. Unlike a SQL `CHECK`, a check there can fail a document that lacks the field, and a `sql` check is refused. See [MongoDB](https://uql-orm.dev/mongodb.md#checks-and-enums). # Inheritance > Declare shared fields once in a base class and inherit them in every entity. Source: https://uql-orm.dev/entities/inheritance An entity inherits what the class it extends declares, abstract or concrete, so shared columns are declared once: ```ts import { f, Entity, Field } from 'uql-orm'; import { v7 as uuidv7 } from 'uuid'; export abstract class BaseEntity { @Field(f.string().id().onInsert(uuidv7)) id?: string; @Field( f .column('timestamptz') .nullable() .onInsert(() => new Date()), ) createdAt?: Date | null; @Field( f .column('timestamptz') .nullable() .onUpdate(() => new Date()), ) updatedAt?: Date | null; } @Entity({ name: 'company' }) export class Company extends BaseEntity { @Field(f.string().nullable().length(150)) name?: string | null; } ``` These timestamps come from the app clock, on uql’s writes only. To take them from the database clock on every write, see [timestamps](https://uql-orm.dev/entities/computed-fields.md#timestamps). A child inherits the base’s fields, relations, hooks, filters, indexes, checks, triggers and `wire`, a child declaring none taking its base’s. They are typed and queried like its own, and a change to the base reaches every child. The base’s entries come first, and a child entry with the same name replaces the base’s. A base of fields alone needs no `@Entity()`. One that declares indexes, filters, checks or triggers for its children, without being a table itself, says `abstract: true`, in `defineEntity` too. A query or write on such a base does not compile, a decorated one being declared `abstract class` too, which is what the compiler reads. A child may add nothing of its own, which gives a second table of the same shape: ```ts import { f } from 'uql-orm'; @Entity({ abstract: true, indexes: (tenanted, index) => [index([tenanted.tenantId])], triggers: (tenanted, trigger) => [ trigger({ on: 'afterInsert', name: 'audit', run: logInsert }), ], }) abstract class Tenanted { @Field(f.string().nullable()) tenantId?: string | null; } @Entity() export class Invoice extends Tenanted {} // gets its own tenant index and audit trigger ``` Each table derives its own index and trigger names. An index you name yourself keeps that name in every child, and PostgreSQL and SQLite need index names unique across tables, so leave a shared index unnamed. ## Replacing an inherited key A child that declares its own `.id()` column replaces the parent’s key entirely (every column of it, if it was [composite](https://uql-orm.dev/entities/basic.md#composite-primary-keys)) and keeps every other inherited field. Name the new key with the `idKey` brand, or TypeScript still reads the inherited `id` as the key: ```ts import { f, Entity, Field, idKey } from 'uql-orm'; import { v7 as uuidv7 } from 'uuid'; @Entity() export class TaxCategory extends BaseEntity { [idKey]?: 'pk'; @Field(f.string().id().onInsert(uuidv7)) pk?: string; @Field(f.string().nullable()) name?: string | null; } ``` ## A base for defineEntity [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) names the class it inherits from as `extends`, and the class it declares extends that one, so it merges the same way. The base can be another `defineEntity` class or a class whose fields are decorated, which has no table of its own: ```ts import { f, defineEntity, Field } from 'uql-orm'; class Audited { @Field(f.string().nullable()) createdBy?: string | null; } export const Faq = defineEntity({ name: 'faq', extends: Audited, fields: { id: f.column('bigint').id(), question: f.text().nullable() }, }); ``` The row type includes the base’s properties, so `createdBy` is read and written like the entity’s own columns. # Example Entities > The entities every query example in this section imports. Source: https://uql-orm.dev/querying/models The query examples in this section import these entities from one shared module. Every field and relation their `$select`, `$where`, `$sort` and `$populate` name is declared here. ```ts title="shared/models/index.ts" import { f, Entity, Field, ManyToMany, ManyToOne, OneToMany, OneToOne, } from 'uql-orm'; @Entity() export class Company { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.string().nullable()) country?: string | null; @Field(f.date().nullable()) createdAt?: Date | null; } /** A lookup table, soft-deletable, which is why a join to it carries `deletedAt IS NULL`. */ @Entity() export class Tax { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.date().nullable().softDelete()) deletedAt?: Date | null; } @Entity() export class MeasureUnitCategory { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @OneToMany(() => MeasureUnit, { mappedBy: (measureUnit) => measureUnit.category, }) measureUnits?: MeasureUnit[]; } @Entity() export class MeasureUnit { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.references(() => MeasureUnitCategory).nullable()) categoryId?: number | null; @ManyToOne(() => MeasureUnitCategory, { references: (measureUnit) => measureUnit.categoryId, }) category?: MeasureUnitCategory; @Field(f.date().nullable().softDelete()) deletedAt?: Date | null; } @Entity() export class Profile { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) picture?: string | null; @Field(f.string().nullable()) bio?: string | null; @Field(f.references(() => User).nullable()) userId?: number | null; @OneToOne(() => User, { references: (profile) => profile.userId }) user?: User; } @Entity() export class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable().unique()) email?: string | null; @Field(f.string().nullable()) name?: string | null; @Field(f.string().nullable().wire(['insert'])) password?: string | null; /** `'active'`, `'pending'`, `'banned'`. */ @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) age?: number | null; @Field(f.boolean().nullable()) active?: boolean | null; @Field(f.date().nullable()) createdAt?: Date | null; @Field(f.number().nullable()) creatorId?: number | null; @Field(f.references(() => Company).nullable()) companyId?: number | null; @ManyToOne(() => Company, { references: (user) => user.companyId }) company?: Company; @OneToOne(() => Profile, { mappedBy: (profile) => profile.user, cascade: true, }) profile?: Profile; @OneToMany(() => Post, { mappedBy: (post) => post.author }) posts?: Post[]; } @Entity() export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) body?: string | null; @Field(f.boolean().nullable()) published?: boolean | null; /** `null` until published, which the [null placement](/querying/sorting#where-nulls-land) examples sort on. */ @Field(f.date().nullable()) publishedAt?: Date | null; /** Upvotes, which the [raw projection](/querying/querier#raw-projections-in-select) example ranks on. */ @Field(f.number().nullable()) points?: number | null; @Field(f.date().nullable()) createdAt?: Date | null; @Field(f.references(() => User).nullable()) authorId?: number | null; @Field(f.references(() => User).nullable()) creatorId?: number | null; @ManyToOne(() => User, { references: (post) => post.authorId }) author?: User; } @Entity() export class Item { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.string().nullable()) description?: string | null; @Field(f.string().nullable()) code?: string | null; @Field(f.number().nullable()) price?: number | null; /** What the [row-locking](/querying/locking) examples decrement under a lock. */ @Field(f.number().nullable()) stock?: number | null; @Field(f.boolean().nullable()) isActive?: boolean | null; @Field(f.date().nullable()) createdAt?: Date | null; @Field(f.vector(1536).nullable()) embedding?: number[] | null; @Field(f.references(() => Company).nullable()) companyId?: number | null; @ManyToOne(() => Company, { references: (item) => item.companyId }) company?: Company; @Field(f.references(() => Tax).nullable()) taxId?: number | null; @ManyToOne(() => Tax, { references: (item) => item.taxId }) tax?: Tax; @Field(f.references(() => MeasureUnit).nullable()) measureUnitId?: number | null; @ManyToOne(() => MeasureUnit, { references: (item) => item.measureUnitId, }) measureUnit?: MeasureUnit; /** What the [relation `$size`](/querying/relations) and [`$count`](/querying/counting) examples tally. */ @ManyToMany(() => Tag, { through: () => ItemTag }) tags?: Tag[]; } @Entity() export class Tag { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; } /** The junction `Item.tags` counts through. */ @Entity() export class ItemTag { @Field(f.number().autoIncrement()) id?: number; @Field(f.references(() => Item).nullable()) itemId?: number | null; @Field(f.references(() => Tag).nullable()) tagId?: number | null; } /** What the [transaction](/querying/transactions) examples debit, so they have a balance to get wrong. */ @Entity() export class Account { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) balance?: number | null; @Field(f.references(() => Company).nullable()) companyId?: number | null; } /** What the [aggregate](/querying/aggregate) examples group and total. */ @Entity() export class Order { @Field(f.number().autoIncrement()) id?: number; /** `'pending'`, `'shipped'`, `'cancelled'`. */ @Field(f.string().nullable()) status?: string | null; @Field(f.number().nullable()) amount?: number | null; @Field(f.number().nullable()) customerId?: number | null; @Field(f.date().nullable()) createdAt?: Date | null; } @Entity() export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) amount?: number | null; @Field(f.number().nullable()) total?: number | null; @Field(f.boolean().nullable()) paid?: boolean | null; @Field(f.date().nullable()) createdAt?: Date | null; @Field(f.references(() => Company).nullable()) companyId?: number | null; } ``` # Querier > Run queries on the pool or on a querier, and get rows typed by what you selected. Source: https://uql-orm.dev/querying/querier A `querier` holds one database connection and runs UQL’s query methods on it. The [pool](https://uql-orm.dev/pool.md) has the same methods and takes a connection for you on each call, so most code calls the pool: ```ts title="You write" import { pool } from './uql.config.js'; import { User } from './shared/models/index.js'; const users = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { profile: true }, $where: { $or: [{ name: 'roger' }, { creatorId: 1 }] }, $sort: { createdAt: 'desc' }, $limit: 10, }); ``` PostgreSQL: ```sql SELECT "User"."id", "User"."name", "profile"."id" "profile.id", "profile"."picture" "profile.picture", "profile"."bio" "profile.bio", "profile"."userId" "profile.userId" FROM "User" LEFT JOIN "Profile" "profile" ON "profile"."userId" = "User"."id" WHERE "User"."name" = $1 OR "User"."creatorId" = $2 ORDER BY "User"."createdAt" DESC LIMIT 10 ``` MySQL: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture`, `profile`.`bio` `profile.bio`, `profile`.`userId` `profile.userId` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` WHERE `User`.`name` = ? OR `User`.`creatorId` = ? ORDER BY `User`.`createdAt` DESC LIMIT 10 ``` MariaDB: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture`, `profile`.`bio` `profile.bio`, `profile`.`userId` `profile.userId` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` WHERE `User`.`name` = ? OR `User`.`creatorId` = ? ORDER BY `User`.`createdAt` DESC LIMIT 10 ``` SQLite: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture`, `profile`.`bio` `profile.bio`, `profile`.`userId` `profile.userId` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` WHERE `User`.`name` = ? OR `User`.`creatorId` = ? ORDER BY `User`.`createdAt` DESC LIMIT 10 ``` SQL Server: ```sql SELECT "User"."id", "User"."name", "profile"."id" "profile.id", "profile"."picture" "profile.picture", "profile"."bio" "profile.bio", "profile"."userId" "profile.userId" FROM "User" LEFT JOIN "Profile" "profile" ON "profile"."userId" = "User"."id" WHERE "User"."name" = @p1 OR "User"."creatorId" = @p2 ORDER BY "User"."createdAt" DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` Every method and its arguments are in the [methods reference](https://uql-orm.dev/querying/methods.md). ## Choosing: `pool.x` vs. `querier.x` `pool.findMany(User, q)` is exactly `pool.withQuerier((querier) => querier.findMany(User, q))`: one connection, taken and released for that call. | You’re running | Use | | - | - | | A single operation | `pool.findMany`, `pool.insertOne`, … (or [`pool.all`](https://uql-orm.dev/querying/raw-sql.md#raw-sql-on-the-pool) for raw SQL) | | Several operations on one connection | `pool.withQuerier((querier) => ...)` | | Work that must be all-or-nothing | `pool.transaction((querier) => ...)` | Two pool calls are two units of work: if the second fails, the first stays committed. They run on separate connections, so `Promise.all` over pool calls runs in parallel, while the same calls inside one `withQuerier` wait for each other. A pool call holds no connection once it returns, so you can read, call a slow external API and write back without starving the pool. An enclosing [`withContext`](https://uql-orm.dev/multi-tenancy.md) scopes pool calls like any other query, so one wrapper covers a whole parallel fan-out. > **Where pool calls differ** > > - They take the entity as the first argument only. The `{ $entity }` form needs a querier. > - [`pool.findManyStream`](https://uql-orm.dev/querying/streaming.md) holds its connection until the loop ends, so always finish the `for await`. > - Inside a `transaction` callback, a pool call runs on the transaction’s querier, so it is part of the transaction. > - On backends with one shared connection (the SQLite drivers, embedded Turso, PGlite and libSQL), pool calls wait for any open transaction. ## The result is the row you asked for The projection shapes the result type, so reading a field the query did not fetch is a compile error: ```ts const [user] = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { profile: true, company: { $required: true }, posts: { $select: { title: true } }, }, }); user.profile; // Profile | undefined: a join can find no row user.company; // Company: `$required` drops the users with none user.posts; // { title: string }[], empty when there are none user.posts[0].body; // error: not selected user.password; // error: not selected ``` Each populated relation is shaped by its own `$select` and `$populate`, at every depth. A query with no projection returns the whole entity, and so does one whose projection is unknown at compile time: a [raw projection](#raw-projections-in-select), or a query typed as `Query`. An entry typed `boolean` rather than `true` or `false` is decided at run time, so the field it names may be absent. A typo’d key in any clause, at any depth of `$populate`, fails to compile. ### Naming a projected row A narrowed row is not a `User`, so name its shape with `QueryFindResult`: ```ts import type { Query, QueryFindResult } from 'uql-orm'; type UserName = QueryFindResult; const card = { $select: { id: true, name: true }, $populate: { posts: { $select: { title: true } } }, } as const satisfies Query; type UserCard = QueryFindResult; ``` It takes the field names, or a whole query. A function that forwards a query keeps its shape by capturing it the way the querier does: ```ts import type { Captured, Query, QueryFindResult, Type } from 'uql-orm'; function findAll>( entity: Type, q: Captured, Q>, ): Promise[]> { return pool.findMany(entity, q); } ``` ## Leaving fields out `$select: { password: false }` returns every field except `password`. A map with any `true` entry selects those fields alone, so a `false` beside one changes nothing. A joined to-one row always keeps its primary key, since that key tells whether the join matched. ## Raw projections in `$select` For computed columns, pass `$select` an array of [`sql`](https://uql-orm.dev/querying/sub-queries.md#understanding-sql) expressions and name each with `.as()`. SQL databases only: ```ts title="You write" import { refs, sql } from 'uql-orm'; const post = refs(Post); const posts = await pool.findMany(Post, { $select: [ sql`*`, sql`LOG10(${post.points} + 1) * 287014.58 + ${post.createdAt}`.as( 'hotness', ), ], }); ``` PostgreSQL: ```sql SELECT *, LOG10("points" + 1) * 287014.58 + "createdAt" "hotness" FROM "Post" ``` MySQL: ```sql SELECT *, LOG10(`points` + 1) * 287014.58 + `createdAt` `hotness` FROM `Post` ``` MariaDB: ```sql SELECT *, LOG10(`points` + 1) * 287014.58 + `createdAt` `hotness` FROM `Post` ``` SQLite: ```sql SELECT *, LOG10(`points` + 1) * 287014.58 + `createdAt` `hotness` FROM `Post` ``` SQL Server: ```sql SELECT *, LOG10("points" + 1) * 287014.58 + "createdAt" "hotness" FROM "Post" ``` The array form cannot be mixed with the object form, and MongoDB rejects it. A populated relation’s `$select` takes it too. ## The same query, every transport A query is a plain object, so one value works on the server and in the browser, typed the same in both. Type it as `WireQuery`, a `Query` without [`sql`](https://uql-orm.dev/querying/raw-sql.md) fragments, since JSON cannot carry them: ```ts import type { WireQuery } from 'uql-orm'; const query: WireQuery = { $where: { status: 'active' }, $populate: { posts: { $where: { published: true }, $limit: 5 } }, }; await pool.findMany(User, query); // server await client.findMany(User, query); // browser, the same rows ``` See the [API](https://uql-orm.dev/http.md) and the [client](https://uql-orm.dev/browser.md). ## Managing a querier yourself When a connection must outlive one callback, take it with `pool.getQuerier()` and bind it with `await using`, which releases it on any exit, early return and throw included: ```ts async function report(companyId: number) { await using querier = await pool.getQuerier(); const users = await querier.findMany(User, { $where: { companyId } }); if (!users.length) return null; return { users, total: await querier.count(User, { $where: { companyId } }) }; } ``` A connection you never release is a leak the pool cannot recover. Without `await using`, call `await querier.release()` in a `finally`. ## Accept a `UniversalQuerier` `Querier` and `QuerierPool` share one interface, `UniversalQuerier`. Type a helper’s database parameter with it and the caller decides where its queries run: ```ts import type { UniversalQuerier } from 'uql-orm'; async function raiseInvoice(db: UniversalQuerier, invoice: Invoice) { await db.insertOne(Invoice, invoice); } const invoice: Invoice = { companyId: 42, total: 1200 }; await raiseInvoice(pool, invoice); // its own unit of work await pool.transaction(async (querier) => { await querier.updateMany( Invoice, { $where: { companyId: 42, paid: false } }, { paid: true }, ); await raiseInvoice(querier, invoice); // commits with the update, or not at all }); ``` A helper that calls `pool` directly joins a caller’s `transaction()` callback too, but not a querier the caller holds outside one, such as a `withQuerier` connection or a `beginTransaction`. Taking `UniversalQuerier` works in every case. Take `Querier` instead only when the helper needs a pinned connection: to open a transaction itself, to use the `{ $entity }` form, or to run `all`/`run` and a query on the same connection. ## Next steps - [Comparison operators](https://uql-orm.dev/querying/comparison-operators.md): everything you can put in `$where`. - [Relations](https://uql-orm.dev/querying/relations.md): `$populate`, relation filters and relation sorting. - [Transactions](https://uql-orm.dev/querying/transactions.md): units of work, isolation levels and nesting. # Methods Reference > Every querier and pool method, what each write returns, and how upserts work. Source: https://uql-orm.dev/querying/methods Every data method exists on the [querier](https://uql-orm.dev/querying/querier.md) and on the pool, with the same arguments ([which to use](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx)). The [client](https://uql-orm.dev/browser.md) answers the methods the [API](https://uql-orm.dev/http.md#wire-protocol) serves the same way. ## Available methods | Method | Does | | - | - | | `findMany(Entity, query, opts?)` | Returns the matching records. | | `findOne(Entity, query, opts?)` | Returns the first match, or `undefined`. | | `findOneById(Entity, id, query?, opts?)` | Returns the record with that key, or `undefined`. | | `findManyAndCount(Entity, query, opts?)` | Returns `[rows, total]`. | | `findManyPage(Entity, query, opts?)` | Returns [a page past a cursor](https://uql-orm.dev/querying/pagination.md). | | `findManyStream(Entity, query, opts?)` | [Streams the records](https://uql-orm.dev/querying/streaming.md) as an `AsyncIterable`. | | `count(Entity, query?, opts?)` | [Counts the matches](https://uql-orm.dev/querying/counting.md), or a page of them. | | `exists(Entity, query?, opts?)` | [Whether anything matches](https://uql-orm.dev/querying/counting.md#exists). | | `estimatedCount(Entity)` | [The engine’s row estimate](https://uql-orm.dev/querying/counting.md#estimatedcount), without a scan. | | `aggregate(Entity, query, opts?)` | Runs an [aggregate query](https://uql-orm.dev/querying/aggregate.md). | | `insertOne` / `insertMany(Entity, data, opts?)` | Inserts records; returns their [IDs](#insert-ids). | | `updateOneById(Entity, id, data, opts?)` | Updates by key; returns the count changed. | | `updateMany(Entity, query, data, opts?)` | Updates the matches; returns the count changed. | | `saveOne` / `saveMany(Entity, data, opts?)` | Inserts, or upserts rows naming their key ([details](#saveone--savemany)); returns IDs. | | `upsertOne` / `upsertMany(Entity, { $conflict, $where?, $update? }, data, opts?)` | Inserts, or updates on a conflict ([details](#upsert-operations)); returns IDs. | | `deleteOneById(Entity, id, opts?)` | Deletes by key, [softly](https://uql-orm.dev/entities/soft-delete.md) when the entity has a soft-delete field; returns the count. | | `deleteMany(Entity, query, opts?)` | Deletes the matches, softly by default; returns the count. | | `restoreOneById(Entity, id)` / `restoreMany(Entity, query)` | Restores soft-deleted records. Throws if the entity has no soft-delete field. | | [``all(sql`...`)`` / ``run(sql`...`)``](https://uql-orm.dev/querying/raw-sql.md) | Runs raw SQL: `all` returns rows, `run` executes writes and DDL. SQL only. | | `transaction(callback, opts?)` | Runs `callback` in a [transaction](https://uql-orm.dev/querying/transactions.md). | Only a querier has: - `beginTransaction`, `commitTransaction` and `rollbackTransaction`, which does nothing when no transaction is open. - `onCommit(callback)`, which runs after the outermost commit and never on a rollback. - `release()`, which rolls back any open transaction and returns the connection. A released querier throws if used again. Only the pool has: - `withQuerier(callback, opts?)`, and a `transaction(callback, opts?)` that hands the callback a querier. Both take `{ context }` to run under a [context](https://uql-orm.dev/multi-tenancy.md). - `getQuerier()`, whose querier **you must release**. - `end()`, which closes every connection. A SQL pool and its queriers also have [`all` and `run`](https://uql-orm.dev/querying/raw-sql.md#raw-sql-on-the-pool). On a querier, every method whose second argument is a query also takes the entity as `$entity` inside it, so the whole call is one JSON value: `querier.findMany({ $entity: User, $where: { status: 'active' } })`, `querier.upsertOne({ $entity: Job, $conflict: { key: true } }, row)`. ### Options The last argument takes: - `filters`: turns [query filters](https://uql-orm.dev/querying/filters.md) off or on for the call: `{ filters: false }`, `{ filters: { softDelete: false } }`, or `withDeleted()`. - `hardDelete`: on a delete, removes the rows instead of soft-deleting them. - `unfiltered`: lets `updateMany` or `deleteMany` touch the whole table. Without it, they throw when the query has neither a `$where` value nor a `$limit`. The entity’s own filters do not count. - `returning`: on a write, the fields to read back, or `true` for every field a read returns. ### `returning` With `returning`, a write resolves to the rows it wrote, typed by the fields you named, instead of IDs or a count: ```ts const [order] = await pool.updateMany( Order, { $where: { status: 'pending' }, $sort: { createdAt: 'asc' }, $limit: 1 }, { status: 'shipped' }, { returning: { id: true, amount: true } }, ); ``` `returning: true` reads back every field a read with no `$select` returns, typed as such, so a write returning whole rows needs no field list. The rows are read in the same transaction, on MongoDB the one you open: after an insert or update, so they hold defaults, trigger output and stored computed columns, and before a delete. A write is a single statement reporting its rows, `RETURNING` or SQL Server’s `OUTPUT`: an insert, an upsert, and a plain update or delete, on PostgreSQL, CockroachDB, the SQLite family and SQL Server, and all but the update on MariaDB. An upsert reports a row its `$where` or an empty `$update` kept by reading it after (MariaDB reports it in the statement), so a counter or a lease taken in one call is one round trip when it writes. Where a [stamp](https://uql-orm.dev/entities/computed-fields.md#stamps-stored-on-an-event) restates the row after the write, as on SQLite and SQL Server, the rows are read back instead. An update or delete writes exactly the rows it reports. On MySQL and MongoDB, for an update on MariaDB, and for a paged write, one filtered through a relation, a versioned row, or a delete with hooks or cascades, UQL reads the rows first and holds them, so another writer waits for the commit instead of changing them in between. SQLite cannot hold a row, so it fails that writer with a retryable error instead. MongoDB does the same inside a [transaction](https://uql-orm.dev/querying/transactions.md) you open; outside one, the read and the write are two steps. ## Atomic arithmetic `$inc` adds to a numeric field and `$mul` multiplies it, inside the statement, so no concurrent write is lost. Guard the change in `$where` and check the changed-row count: ```ts const taken = await pool.updateMany( Item, { $where: { id, stock: { $gte: quantity } } }, { stock: { $inc: -quantity } }, ); if (taken === 0) throw new Error('sold out'); ``` `NULL` counts as 0, and a field takes `$inc` or `$mul`, not both. A `bigint` field takes a `bigint` operand and stays exact. An `f.number()` field without `.scale()` is an integer column, so a fractional step needs `.precision(p).scale(s)`. The operators are plain JSON, so they work from the [browser](https://uql-orm.dev/browser.md). On SQL the operand can also be a ref or `sql` of the field’s type: `{ total: { $inc: refs(Invoice).amount } }`. JSON fields have their own [update operators](https://uql-orm.dev/querying/json.md). ## Insert IDs Writes report each ID as the column’s value, or as a [key map](#composite-keys) for a composite key, in payload order: ```ts const ids = await pool.insertMany(User, [ { name: 'Ada', email: 'ada@uql-orm.dev' }, { id: 5000, name: 'Alan' }, // Alan's email gets its column default ]); // [1, 5000] on every database ``` IDs you supply, or generate with a key’s `.onInsert()`, come back as they are. Generated IDs are exact per row on every engine but MySQL (Bun SQL’s MySQL mode included), which reports one ID per statement, so UQL infers the rest, mixed batches included. Each resolves to a defined key, so `findOneById` takes it as it is. On SQL engines, an insert refuses a key it leaves out unless the entity declares what fills it: `.autoIncrement()`, `.default()` or `.onInsert()`. > **MySQL under concurrent writes** > > Inferred IDs assume consecutive auto-increment values, which `innodb_autoinc_lock_mode` 0 or 1 guarantees. Under mode 2, the MySQL 8.0 default, concurrent inserts into the same table can break that. Set the mode to 0 or 1 on such tables, or do not rely on multi-row insert IDs. Records in one `insertMany` can set different columns, and a column a record leaves out gets its default (`NULL` on SQLite, which still generates keys). A batch past the engine’s bind-parameter limit becomes several statements, which still land whole: one request on D1, libSQL, Turso and Neon, and a transaction elsewhere. ## saveOne / saveMany `save` decides per row by whether the payload **names its primary key**, not by whether the row exists: | The row | What runs | | - | - | | Names no key | `INSERT` | | Names its key, and carries other columns | `INSERT ... ON CONFLICT DO UPDATE` on that key | | Names its key, and nothing else | Nothing: it links an existing row | So `{ tags: [{ id: 22 }] }` writes the junction row and leaves tag 22 untouched, and a stale ID inserts a new row. A row naming its key and other columns fires `@BeforeUpsert` and `@AfterUpsert`, never the update [hooks](https://uql-orm.dev/entities/lifecycle-hooks.md). ## Composite keys With a [composite primary key](https://uql-orm.dev/entities/basic.md#composite-primary-keys), writes report each key as the map the by-id methods take, such as `[{ studentId: 1, courseId: 'maths' }]`. `idOf(getMeta(Enrolment), row)` builds the same map from a row. MongoDB refuses composite keys; see [what is not supported](https://uql-orm.dev/entities/basic.md#what-is-not-supported). ## Upsert operations An upsert finds rows by its **conflict keys**, `$conflict`, the fields of a unique key. A found row is updated with the payload minus those keys, and its `.onUpdate()` fills, but keeps its own key: the payload’s key and its `.onInsert()` fills apply only to a row the upsert inserts. Otherwise the payload is inserted: ```ts title="You write" await pool.upsertMany(User, { $conflict: { email: true } }, [ { email: 'roger@uql-orm.dev', name: 'Roger' }, { email: 'ana@uql-orm.dev', name: 'Ana' }, ]); ``` PostgreSQL: ```sql INSERT INTO "User" ("email", "name") VALUES ($1, $2), ($3, $4) ON CONFLICT ("email") DO UPDATE SET "name" = EXCLUDED."name" RETURNING "id", "email" ``` MySQL: ```sql INSERT INTO `User` (`email`, `name`) VALUES (?, ?), (?, ?) AS `_uql_new` ON DUPLICATE KEY UPDATE `name` = `_uql_new`.`name` ``` MariaDB: ```sql INSERT INTO `User` (`email`, `name`) VALUES (?, ?), (?, ?) ON DUPLICATE KEY UPDATE `name` = VALUE(`name`) RETURNING `id`, `email` ``` SQLite: ```sql INSERT INTO `User` (`email`, `name`) VALUES (?, ?), (?, ?) ON CONFLICT (`email`) DO UPDATE SET `name` = EXCLUDED.`name` RETURNING `id`, `email` ``` SQL Server: ```sql DECLARE @_uql_output TABLE ("id" BIGINT, "email" NVARCHAR(255)); MERGE INTO "User" WITH (HOLDLOCK) USING (VALUES (@p1, @p2), (@p3, @p4)) AS "_uql_src" ("email", "name") ON "User"."email" = "_uql_src"."email" WHEN MATCHED THEN UPDATE SET "name" = "_uql_src"."name" WHEN NOT MATCHED THEN INSERT ("email", "name") VALUES ("_uql_src"."email", "_uql_src"."name") OUTPUT INSERTED."id", INSERTED."email" INTO @_uql_output ("id", "email"); SELECT "_uql_output"."id", "_uql_output"."email" FROM @_uql_output "_uql_output" ``` An upsert returns the IDs in payload order, inserted or updated, on every database, or the rows with [`returning`](#returning). A [versioned](https://uql-orm.dev/entities/optimistic-locking.md) row it finds must carry its version, as an update does. ### Updating a conflicting row its own way Give the query an `$update` to give a conflicting row something else, operators included. A new row still gets the payload, which makes a counter one call: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity() export class SearchQuery { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().unique()) term!: string; @Field(f.number().nullable()) uses?: number | null; } await pool.upsertOne( SearchQuery, { $conflict: { term: true }, $update: { uses: { $inc: 1 } } }, { term: 'shoes', uses: 1 }, ); ``` PostgreSQL: ```sql INSERT INTO "SearchQuery" ("term", "uses") VALUES ($1, $2) ON CONFLICT ("term") DO UPDATE SET "uses" = COALESCE("SearchQuery"."uses", 0) + $3 RETURNING "id", "term" ``` MySQL: ```sql INSERT INTO `SearchQuery` (`term`, `uses`) VALUES (?, ?) AS `_uql_new` ON DUPLICATE KEY UPDATE `SearchQuery`.`id` = LAST_INSERT_ID(`SearchQuery`.`id`), `uses` = COALESCE(`SearchQuery`.`uses`, 0) + ? ``` MariaDB: ```sql INSERT INTO `SearchQuery` (`term`, `uses`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `uses` = COALESCE(`SearchQuery`.`uses`, 0) + ? RETURNING `id`, `term` ``` SQLite: ```sql INSERT INTO `SearchQuery` (`term`, `uses`) VALUES (?, ?) ON CONFLICT (`term`) DO UPDATE SET `uses` = COALESCE(`SearchQuery`.`uses`, 0) + ? RETURNING `id`, `term` ``` SQL Server: ```sql DECLARE @_uql_output TABLE ("id" BIGINT, "term" NVARCHAR(255)); MERGE INTO "SearchQuery" WITH (HOLDLOCK) USING (VALUES (@p2, @p3)) AS "_uql_src" ("term", "uses") ON "SearchQuery"."term" = "_uql_src"."term" WHEN MATCHED THEN UPDATE SET "uses" = COALESCE("SearchQuery"."uses", 0) + @p1 WHEN NOT MATCHED THEN INSERT ("term", "uses") VALUES ("_uql_src"."term", "_uql_src"."uses") OUTPUT INSERTED."id", INSERTED."term" INTO @_uql_output ("id", "term"); SELECT "_uql_output"."id", "_uql_output"."term" FROM @_uql_output "_uql_output" ``` An `$update` value can be SQL reading the found row through [`refs(Entity)`](https://uql-orm.dev/querying/raw-sql.md), with no alias: ``{ uses: sql`GREATEST(${query.uses}, ${n})` }`` with `const query = refs(SearchQuery)` reads the row as it stands, under the naming strategy, on every SQL engine. An empty `$update` (`{}`) leaves a conflicting row untouched, `.onUpdate()` fields included, so the call only inserts. ### Updating only some conflicting rows A `$where` beside `$conflict` names which found rows take the update, the payload or its `$update`; the others stay as they are. Here a job is queued again only once its last run finished: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity() export class Job { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().unique()) key!: string; @Field(f.string()) status!: string; } await pool.upsertOne( Job, { $conflict: { key: true }, $where: { status: ['done', 'failed'] } }, { key: 'nightly', status: 'queued' }, ); ``` PostgreSQL: ```sql INSERT INTO "Job" ("key", "status") VALUES ($1, $2) ON CONFLICT ("key") DO UPDATE SET "status" = EXCLUDED."status" WHERE "Job"."status" = ANY($3) RETURNING "id", "key" ``` MySQL: ```sql INSERT INTO `Job` (`key`, `status`) VALUES (?, ?) AS `_uql_new` ON DUPLICATE KEY UPDATE `Job`.`id` = LAST_INSERT_ID(`Job`.`id`), `status` = CASE WHEN `Job`.`status` IN (?, ?) THEN `_uql_new`.`status` ELSE `Job`.`status` END ``` MariaDB: ```sql INSERT INTO `Job` (`key`, `status`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `status` = CASE WHEN `Job`.`status` IN (?, ?) THEN VALUE(`status`) ELSE `Job`.`status` END RETURNING `id`, `key` ``` SQLite: ```sql INSERT INTO `Job` (`key`, `status`) VALUES (?, ?) ON CONFLICT (`key`) DO UPDATE SET `status` = EXCLUDED.`status` WHERE `Job`.`status` IN (?, ?) RETURNING `id`, `key` ``` SQL Server: ```sql DECLARE @_uql_output TABLE ("id" BIGINT, "key" NVARCHAR(255)); MERGE INTO "Job" WITH (HOLDLOCK) USING (VALUES (@p3, @p4)) AS "_uql_src" ("key", "status") ON "Job"."key" = "_uql_src"."key" WHEN MATCHED AND "Job"."status" IN (@p1, @p2) THEN UPDATE SET "status" = "_uql_src"."status" WHEN NOT MATCHED THEN INSERT ("key", "status") VALUES ("_uql_src"."key", "_uql_src"."status") OUTPUT INSERTED."id", INSERTED."key" INTO @_uql_output ("id", "key"); SELECT "_uql_output"."id", "_uql_output"."key" FROM @_uql_output "_uql_output" ``` It is one statement on every SQL database: SQL Server matches with `WHEN MATCHED AND`, and MySQL and MariaDB, whose `ON DUPLICATE KEY UPDATE` takes no `WHERE`, guard each column, so there a `$where` may read only one column the update sets. On MongoDB, an upsert with an `$update` or a `$where` inserts the absent documents, then updates the found ones, as two batches; it needs no replica set. Run it in a [transaction](https://uql-orm.dev/querying/transactions.md) where a failure between the batches, or a document another writer inserts meanwhile, must not leave the result half applied. Any other `upsertMany`, like an `insertMany`, is one command, which MongoDB applies a document at a time; run it in a [transaction](https://uql-orm.dev/querying/transactions.md) for all or none. ### Relations in an upsert [Cascaded](https://uql-orm.dev/entities/relations.md) relations are written on both branches, so an updated row’s relations are replaced; with `$update`, only the relations it names. Such an upsert, like any upsert on an entity with a [security filter](https://uql-orm.dev/querying/filters.md), reads the matching rows before writing, so a row another writer inserts in between makes it fail on its key. # Deep Relations > Load related entities with $populate, and filter, sort and count across relations. Source: https://uql-orm.dev/querying/relations `$populate` loads related entities with the rows you query, in the same statement. Inside it, fields and operators are completed and type-checked against the related entity. A relation you do not populate is not loaded: nothing is lazy. You can also filter and sort parents by their relations without loading them. ## Loading a relation Name the relation in `$populate` and pick its fields there. `$select` stays for the entity’s own columns: ```ts title="You write" import { pool } from './uql.config.js'; import { User } from './shared/models/index.js'; const users = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { profile: { $select: { picture: true } }, }, }); ``` PostgreSQL: ```sql SELECT "User"."id", "User"."name", "profile"."id" "profile.id", "profile"."picture" "profile.picture" FROM "User" LEFT JOIN "Profile" "profile" ON "profile"."userId" = "User"."id" ``` MySQL: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` ``` MariaDB: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` ``` SQLite: ```sql SELECT `User`.`id`, `User`.`name`, `profile`.`id` `profile.id`, `profile`.`picture` `profile.picture` FROM `User` LEFT JOIN `Profile` `profile` ON `profile`.`userId` = `User`.`id` ``` SQL Server: ```sql SELECT "User"."id", "User"."name", "profile"."id" "profile.id", "profile"."picture" "profile.picture" FROM "User" LEFT JOIN "Profile" "profile" ON "profile"."userId" = "User"."id" ``` The relation’s primary key always comes back. A to-one relation is joined with a `LEFT JOIN`, so parents without a match are kept. `$required: true` makes it an `INNER JOIN`, which keeps only the parents that have one. A `$where` inside the relation goes into the join condition: ```ts const withBio = await pool.findMany(User, { $populate: { profile: { $select: { bio: true }, $where: { bio: { $ne: null } }, $required: true, }, }, }); ``` ## Filtering, sorting and paging a collection A populated one-to-many or many-to-many takes its own `$where`, `$sort`, `$limit` and `$skip`, applied per parent. This loads each author’s 5 newest posts about TypeScript: ```ts title="You write" const authors = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { posts: { $select: { title: true, createdAt: true }, $where: { title: { $iincludes: 'typescript' } }, $sort: { createdAt: 'desc' }, $limit: 5, }, }, $limit: 20, }); ``` PostgreSQL: ```sql SELECT "User"."id", "User"."name", (SELECT COALESCE(JSON_AGG("_uql_row" ORDER BY "posts"."_uql_sort_createdAt" DESC), '[]'::json) FROM (SELECT "posts"."title", "posts"."createdAt", "posts"."createdAt" "_uql_sort_createdAt" FROM "Post" "posts" WHERE "posts"."title" ILIKE $1 ESCAPE '\' AND "posts"."authorId" = "User"."id" ORDER BY "_uql_sort_createdAt" DESC LIMIT 5) "posts" CROSS JOIN LATERAL (SELECT "posts"."title", "posts"."createdAt") "_uql_row") "posts" FROM "User" LIMIT 20 ``` MySQL: ```sql SELECT /*+ SET_VAR(group_concat_max_len=18446744073709551615) */ `User`.`id`, `User`.`name`, (SELECT COALESCE(CONCAT('[', GROUP_CONCAT(JSON_OBJECT('title', `posts`.`title`, 'createdAt', `posts`.`createdAt`) ORDER BY `posts`.`_uql_sort_createdAt` DESC SEPARATOR ','), ']'), '[]') FROM (SELECT `posts`.`title`, `posts`.`createdAt`, `posts`.`createdAt` `_uql_sort_createdAt` FROM `Post` `posts` WHERE LOWER(`posts`.`title`) LIKE ? ESCAPE '\\' AND `posts`.`authorId` = `User`.`id` ORDER BY `_uql_sort_createdAt` DESC LIMIT 5) `posts`) `posts` FROM `User` LIMIT 20 ``` MariaDB: ```sql SET STATEMENT group_concat_max_len=18446744073709551615 FOR SELECT `User`.`id`, `User`.`name`, COALESCE((SELECT JSON_ARRAYAGG(JSON_OBJECT('title', `posts`.`title`, 'createdAt', `posts`.`createdAt`) ORDER BY `posts`.`createdAt` DESC LIMIT 5) FROM `Post` `posts` WHERE LOWER(`posts`.`title`) LIKE ? ESCAPE '\\' AND `posts`.`authorId` = `User`.`id`), JSON_ARRAY()) `posts` FROM `User` LIMIT 20 ``` SQLite: ```sql SELECT `User`.`id`, `User`.`name`, (SELECT json_group_array(json_object('title', `posts`.`title`, 'createdAt', `posts`.`createdAt`) ORDER BY `posts`.`_uql_sort_createdAt` DESC) FROM (SELECT `posts`.`title`, `posts`.`createdAt`, `posts`.`createdAt` `_uql_sort_createdAt` FROM `Post` `posts` WHERE `posts`.`title` LIKE ? ESCAPE '\' AND `posts`.`authorId` = `User`.`id` ORDER BY `_uql_sort_createdAt` DESC LIMIT 5) `posts`) `posts` FROM `User` LIMIT 20 ``` SQL Server: ```sql SELECT "User"."id", "User"."name", JSON_QUERY(COALESCE((SELECT "posts"."title", CONVERT(VARCHAR(33), CAST("posts"."createdAt" AS DATETIMEOFFSET), 127) "createdAt" FROM "Post" "posts" WHERE LOWER("posts"."title") LIKE @p1 ESCAPE N'\' AND "posts"."authorId" = "User"."id" ORDER BY "posts"."createdAt" DESC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY FOR JSON PATH, INCLUDE_NULL_VALUES), '[]')) "posts" FROM "User" ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY ``` It is still one statement. A parent with no matches gets `[]`, and the row types the relation as a list, so `author.posts.map(...)` needs no guard. `$limit: 1` with a `$sort` gives each parent its latest row. Limit the parents too, since the statement reads up to parents times `$limit` related rows. A to-one `$populate` rejects `$sort`, `$limit`, `$skip` and `$distinct`, since it joins one row per parent. `$select`, `$where` and `$required` work on both kinds. ## Sorting by related fields `$sort` can name a field on a to-one relation, populated or not. UQL adds the join the sort needs: ```ts title="You write" const items = await pool.findMany(Item, { $select: { id: true, name: true }, $populate: { tax: { $select: { name: true } } }, $sort: { tax: { name: 1 }, measureUnit: { name: 1 }, createdAt: 'desc' }, }); ``` PostgreSQL: ```sql SELECT "Item"."id", "Item"."name", "tax"."id" "tax.id", "tax"."name" "tax.name" FROM "Item" LEFT JOIN "Tax" "tax" ON "tax"."id" = "Item"."taxId" AND "tax"."deletedAt" IS NULL LEFT JOIN "MeasureUnit" "measureUnit" ON "measureUnit"."id" = "Item"."measureUnitId" AND "measureUnit"."deletedAt" IS NULL ORDER BY "tax"."name", "measureUnit"."name", "Item"."createdAt" DESC ``` MySQL: ```sql SELECT `Item`.`id`, `Item`.`name`, `tax`.`id` `tax.id`, `tax`.`name` `tax.name` FROM `Item` LEFT JOIN `Tax` `tax` ON `tax`.`id` = `Item`.`taxId` AND `tax`.`deletedAt` IS NULL LEFT JOIN `MeasureUnit` `measureUnit` ON `measureUnit`.`id` = `Item`.`measureUnitId` AND `measureUnit`.`deletedAt` IS NULL ORDER BY `tax`.`name`, `measureUnit`.`name`, `Item`.`createdAt` DESC ``` MariaDB: ```sql SELECT `Item`.`id`, `Item`.`name`, `tax`.`id` `tax.id`, `tax`.`name` `tax.name` FROM `Item` LEFT JOIN `Tax` `tax` ON `tax`.`id` = `Item`.`taxId` AND `tax`.`deletedAt` IS NULL LEFT JOIN `MeasureUnit` `measureUnit` ON `measureUnit`.`id` = `Item`.`measureUnitId` AND `measureUnit`.`deletedAt` IS NULL ORDER BY `tax`.`name`, `measureUnit`.`name`, `Item`.`createdAt` DESC ``` SQLite: ```sql SELECT `Item`.`id`, `Item`.`name`, `tax`.`id` `tax.id`, `tax`.`name` `tax.name` FROM `Item` LEFT JOIN `Tax` `tax` ON `tax`.`id` = `Item`.`taxId` AND `tax`.`deletedAt` IS NULL LEFT JOIN `MeasureUnit` `measureUnit` ON `measureUnit`.`id` = `Item`.`measureUnitId` AND `measureUnit`.`deletedAt` IS NULL ORDER BY `tax`.`name`, `measureUnit`.`name`, `Item`.`createdAt` DESC ``` SQL Server: ```sql SELECT "Item"."id", "Item"."name", "tax"."id" "tax.id", "tax"."name" "tax.name" FROM "Item" LEFT JOIN "Tax" "tax" ON "tax"."id" = "Item"."taxId" AND "tax"."deletedAt" IS NULL LEFT JOIN "MeasureUnit" "measureUnit" ON "measureUnit"."id" = "Item"."measureUnitId" AND "measureUnit"."deletedAt" IS NULL ORDER BY "tax"."name", "measureUnit"."name", "Item"."createdAt" DESC ``` `measureUnit` is only sorted by, so its join adds no columns. It is the join `$populate` would make, [filters](https://uql-orm.dev/querying/filters.md) and soft-delete included, so the sort never sees a row the query could not read. A nested path joins each level: `$sort: { measureUnit: { category: { name: 1 } } }`. A sort by a relation is rejected: - On a to-many relation’s fields: a parent has many such rows, so there is no single value to order by. Sort them inside `$populate`, or rank parents by the relation’s size, `{ posts: { $count: -1 } }` ([counting](https://uql-orm.dev/querying/counting.md#ordering-by-a-relations-size)), or by its row nearest a vector ([semantic search](https://uql-orm.dev/querying/semantic-search.md#ranking-by-a-related-row)). - In `updateMany`, `deleteMany` and `$group` aggregates, which do not join. - With `$distinct`, unless the relation is populated too, because `SELECT DISTINCT` orders only by selected columns. - On MongoDB, unless every level of the path is populated, since `$lookup` is what brings the fields in. ## Filtering by a relation A condition on a one-to-many or many-to-many relation keeps the parents that have a matching row. It compiles to an `EXISTS` subquery, so parent rows are never duplicated: ```ts title="You write" const users = await pool.findMany(User, { $select: { id: true, name: true }, $where: { name: { $istartsWith: 'a' }, posts: { title: { $iincludes: 'typescript' } }, }, }); ``` PostgreSQL: ```sql SELECT "id", "name" FROM "User" WHERE "name" ILIKE $1 ESCAPE '\' AND EXISTS ( SELECT 1 FROM "Post" "posts" WHERE "posts"."authorId" = "User"."id" AND "posts"."title" ILIKE $2 ESCAPE '\' ) ``` MySQL: ```sql SELECT `id`, `name` FROM `User` WHERE LOWER(`name`) LIKE ? ESCAPE '\\' AND EXISTS ( SELECT 1 FROM `Post` `posts` WHERE `posts`.`authorId` = `User`.`id` AND LOWER(`posts`.`title`) LIKE ? ESCAPE '\\' ) ``` MariaDB: ```sql SELECT `id`, `name` FROM `User` WHERE LOWER(`name`) LIKE ? ESCAPE '\\' AND EXISTS ( SELECT 1 FROM `Post` `posts` WHERE `posts`.`authorId` = `User`.`id` AND LOWER(`posts`.`title`) LIKE ? ESCAPE '\\' ) ``` SQLite: ```sql SELECT `id`, `name` FROM `User` WHERE `name` LIKE ? ESCAPE '\' AND EXISTS ( SELECT 1 FROM `Post` `posts` WHERE `posts`.`authorId` = `User`.`id` AND `posts`.`title` LIKE ? ESCAPE '\' ) ``` SQL Server: ```sql SELECT "id", "name" FROM "User" WHERE LOWER("name") LIKE @p1 ESCAPE N'\' AND EXISTS ( SELECT 1 FROM "Post" "posts" WHERE "posts"."authorId" = "User"."id" AND LOWER("posts"."title") LIKE @p2 ESCAPE N'\' ) ``` For a many-to-many, the subquery goes through the junction table. The [filters](https://uql-orm.dev/querying/filters.md) of the related entity and of the junction apply inside it, so a parent never matches through a soft-deleted child or one outside a `security` filter. On MongoDB the same conditions compile to correlated `$lookup` stages. ### Filtering by count (`$size`) `$size` filters parents by how many related rows they have. It takes a number for an exact match, or a [comparison operator](https://uql-orm.dev/querying/comparison-operators.md): ```ts title="You write" const categories = await pool.findMany(MeasureUnitCategory, { $select: { id: true, name: true }, $where: { measureUnits: { $size: { $gte: 2 } } }, }); const items = await pool.findMany(Item, { $where: { tags: { $size: { $between: [2, 10] } } }, }); ``` PostgreSQL: ```sql SELECT "id", "name" FROM "MeasureUnitCategory" WHERE (SELECT COUNT(*) FROM "MeasureUnit" "measureUnits" WHERE "measureUnits"."categoryId" = "MeasureUnitCategory"."id" AND "measureUnits"."deletedAt" IS NULL) >= $1 ``` MySQL: ```sql SELECT `id`, `name` FROM `MeasureUnitCategory` WHERE (SELECT COUNT(*) FROM `MeasureUnit` `measureUnits` WHERE `measureUnits`.`categoryId` = `MeasureUnitCategory`.`id` AND `measureUnits`.`deletedAt` IS NULL) >= ? ``` MariaDB: ```sql SELECT `id`, `name` FROM `MeasureUnitCategory` WHERE (SELECT COUNT(*) FROM `MeasureUnit` `measureUnits` WHERE `measureUnits`.`categoryId` = `MeasureUnitCategory`.`id` AND `measureUnits`.`deletedAt` IS NULL) >= ? ``` SQLite: ```sql SELECT `id`, `name` FROM `MeasureUnitCategory` WHERE (SELECT COUNT(*) FROM `MeasureUnit` `measureUnits` WHERE `measureUnits`.`categoryId` = `MeasureUnitCategory`.`id` AND `measureUnits`.`deletedAt` IS NULL) >= ? ``` SQL Server: ```sql SELECT "id", "name" FROM "MeasureUnitCategory" WHERE (SELECT COUNT(*) FROM "MeasureUnit" "measureUnits" WHERE "measureUnits"."categoryId" = "MeasureUnitCategory"."id" AND "measureUnits"."deletedAt" IS NULL) >= @p1 ``` The count applies the related entity’s filters, as `EXISTS` does. To return or sort by a relation’s size instead, see [counting relations](https://uql-orm.dev/querying/counting.md#counting-relations). ## Next steps - [Relation Mapping](https://uql-orm.dev/entities/relations.md): how the relations you query here are declared. - [Sub-Queries](https://uql-orm.dev/querying/sub-queries.md): correlated sub-queries when the built-in ones are not enough. - [Streaming](https://uql-orm.dev/querying/streaming.md): the same relations, row by row. # Counting > Count matching rows, test existence, page with a total, and count or rank by a relation's size, on every SQL dialect and MongoDB. Source: https://uql-orm.dev/querying/counting UQL has five ways to ask “how many”, each at a different cost: | You need | Use | Costs | | - | - | - | | How many match | `count(Entity, query?)` | one statement | | Whether *any* match | `exists(Entity, query?)` | one statement, stops at the first row | | A page **and** its total | `findManyAndCount(Entity, query)` | one statement on SQL in most cases, two on MongoDB | | How many rows a relation holds | `$count` on a read | part of the read’s own statement | | A rough size of a huge table | `estimatedCount(Entity)` | no scan at all | ## count ```ts await pool.count(User, { $where: { active: true } }); ``` With `$skip` or `$limit`, `count` counts that page only, which caps the work on a table too big to scan: ```ts await pool.count(User, { $limit: 1000 }); // "1,000+ matches" without counting the rest await pool.count(User, { $skip: 20 }); // how many remain after the first 20 ``` A paged count runs as `SELECT COUNT(*) FROM (SELECT ... LIMIT 1000)`, so no row leaves the database. `count` takes no `$sort`, since order never changes how many rows match. ## exists `exists` is a count capped at one row, so the engine stops at the first match. Prefer it to `count(...) > 0`: ```ts if (await pool.exists(User, { $where: { email } })) { throw new Error('email already registered'); } ``` ## findManyAndCount The page plus how many rows matched in total, which is what a paginated list needs: ```ts const [users, total] = await pool.findManyAndCount(User, { $where: { active: true }, $sort: { createdAt: -1 }, $skip: 40, $limit: 20, }); // users.length === 20, total === 1247 ``` On SQL the total rides in a column of the page itself (`COUNT(*) OVER ()`), so rows and total come from one statement and always agree. A second statement counts instead for an empty page, which has no row to carry the total, for a `$distinct` read, for a `$lock` on the Postgres family, and always on MongoDB. With `$distinct`, the total counts the distinct rows. ## Counting relations `$count` returns how many rows a to-many relation holds, without loading them. The tallies arrive under `_count`, and each can take a filter of its own: ```ts const users = await pool.findMany(User, { $select: { name: true }, $count: { posts: { $where: { published: true } } }, }); // [{ name: 'Ada', _count: { posts: 12 } }] ``` Counting and populating the same relation are independent, so you can load the newest five posts and still know how many there are: ```ts const [user] = await pool.findMany(User, { $select: { name: true }, $populate: { posts: { $sort: { createdAt: -1 }, $limit: 5 } }, $count: { posts: true }, }); user.posts.length; // 5 user._count.posts; // 128 ``` Each tally is a correlated count inside the read’s own statement, and it works with `$distinct` and a raw `$select`. For a tally you always want, or for `sum`, `min`, `max` and `avg`, declare a [relation aggregate](https://uql-orm.dev/entities/computed-fields.md#relation-aggregates) field instead, which `$where` and `$sort` can also use. ## Ordering by a relation’s size `$sort` can rank rows by a tally, for a top-N: ```ts const busiest = await pool.findMany(User, { $sort: { posts: { $count: -1 } }, $limit: 10, }); ``` To *filter* by a relation’s size instead, use [`$size`](https://uql-orm.dev/querying/relations.md#filtering-by-count-size) in `$where`: `{ posts: { $size: { $gte: 5 } } }`. ## estimatedCount ```ts await pool.estimatedCount(User); // 2_400_000, instantly ``` It reads the row count the engine already keeps, so it answers in constant time on any table: PostgreSQL’s `pg_class.reltuples`, CockroachDB’s table statistics, MySQL and MariaDB’s `information_schema.TABLES`, SQL Server’s `sys.partitions`, MongoDB’s `estimatedDocumentCount`. Use it only where an approximation is fine: - It is as stale as the engine’s last statistics refresh (`ANALYZE` on PostgreSQL). - It takes no filter, so soft-deleted rows and every [query filter](https://uql-orm.dev/querying/filters.md) are inside the number. - The SQLite family (SQLite, libSQL, Turso, D1) keeps no such statistic, so it throws there. - The [client](https://uql-orm.dev/browser.md) does not have it. # Sorting > Order rows with $sort, and choose where nulls land so the order is the same on every engine. Source: https://uql-orm.dev/querying/sorting `$sort` orders rows by fields of the entity, JSON paths inside them, or a joined relation’s fields, in the order you write the keys: ```ts const posts = await pool.findMany(Post, { $select: { title: true, publishedAt: true }, $sort: { publishedAt: 'desc', title: 'asc' }, }); ``` PostgreSQL: ```sql SELECT "title", "publishedAt" FROM "Post" ORDER BY "publishedAt" DESC, "title" ``` MySQL: ```sql SELECT `title`, `publishedAt` FROM `Post` ORDER BY `publishedAt` DESC, `title` ``` MariaDB: ```sql SELECT `title`, `publishedAt` FROM `Post` ORDER BY `publishedAt` DESC, `title` ``` SQLite: ```sql SELECT `title`, `publishedAt` FROM `Post` ORDER BY `publishedAt` DESC, `title` ``` SQL Server: ```sql SELECT "title", "publishedAt" FROM "Post" ORDER BY "publishedAt" DESC, "title" ``` A direction is `'asc'` or `1`, `'desc'` or `-1`, or a [null placement](#where-nulls-land). ## Where nulls land Engines disagree on where nulls go, and a plain direction keeps each engine’s answer: | Engine | Plain `asc` puts nulls | | - | - | | PostgreSQL, Neon, PGlite, Bun SQL on Postgres | last | | CockroachDB, SQLite, libSQL, Turso, D1, MySQL, MariaDB, SQL Server | first | | MongoDB | first (a missing field counts as null) | Name a placement and the order is the same everywhere: ```ts const posts = await pool.findMany(Post, { $sort: { publishedAt: 'descNullsLast' }, }); ``` The placements are `ascNullsFirst`, `ascNullsLast`, `descNullsFirst` and `descNullsLast`. They work wherever a direction does, including a populated relation’s `$sort` and an aggregate’s. Engines without `NULLS LAST` get an equivalent: PostgreSQL: ```sql SELECT ... FROM "Post" ORDER BY "publishedAt" DESC NULLS LAST ``` MySQL: ```sql SELECT ... FROM `Post` ORDER BY `publishedAt` IS NULL, `publishedAt` DESC ``` MariaDB: ```sql SELECT ... FROM `Post` ORDER BY `publishedAt` IS NULL, `publishedAt` DESC ``` SQLite: ```sql SELECT ... FROM `Post` ORDER BY `publishedAt` DESC NULLS LAST ``` SQL Server: ```sql SELECT ... FROM "Post" ORDER BY CASE WHEN "publishedAt" IS NULL THEN 1 ELSE 0 END, "publishedAt" DESC ``` On MongoDB, UQL sorts by a null flag first and strips it from the results. > **Use a placement only when you need one** > > On MySQL, MariaDB, SQL Server and MongoDB a placement adds an expression to the sort, which no index serves, so a sort that used an index becomes a sort of every matched row. That is why plain `asc` and `desc` keep the engine’s order. ## In generic code Where the entity is a type parameter, a key held in one cannot build the map: TypeScript widens `{ [key]: 'asc' }` to an index signature, which no entity’s `$sort` accepts. Take the member as a selector, read its name with `keyOf`, and build the sort with `sortOf`, which takes `[key, direction]` pairs in the order they sort: ```ts import { type FieldKeyOf, type KeyMap, keyOf, sortOf, type Type, } from 'uql-orm'; function oldestFirst>( entity: Type, since: (keys: KeyMap) => K, ) { const key = keyOf(since); return pool.findMany(entity, { $sort: sortOf([[key, 'asc']]), $limit: 20, }); } const oldest = await oldestFirst(Post, (post) => post.publishedAt); ``` The selector follows a rename of `publishedAt`, where a string key would be left behind, and `FieldKeyOf` refuses a member that is not a date. ## Next steps - [Relations](https://uql-orm.dev/querying/relations.md): sorting by a joined field, and a populated collection’s own `$sort`. - [Counting](https://uql-orm.dev/querying/counting.md#ordering-by-a-relations-size): ordering rows by how many related rows they have. - [Cursor pagination](https://uql-orm.dev/querying/pagination.md): paging through a sorted result. - [Full-text search](https://uql-orm.dev/querying/full-text.md) and [semantic search](https://uql-orm.dev/querying/semantic-search.md): ranking by relevance or vector distance. # Comparison Operators > Filter by equality, ranges, text patterns, lists and arrays with UQL comparison operators. Source: https://uql-orm.dev/querying/comparison-operators Comparison operators are the conditions you put on a field in `$where`: ```ts title="You write" const users = await pool.findMany(User, { $where: { name: { $istartsWith: 'Some', $ne: 'Something' }, age: { $gte: 18, $lte: 65 }, }, }); ``` PostgreSQL: ```sql SELECT ... FROM "User" WHERE ("name" ILIKE $1 ESCAPE '\' AND "name" <> $2) AND ("age" >= $3 AND "age" <= $4) -- values: ['Some%', 'Something', 18, 65] ``` MySQL: ```sql SELECT ... FROM `User` WHERE (LOWER(`name`) LIKE ? ESCAPE '\\' AND `name` <> ?) AND (`age` >= ? AND `age` <= ?) -- values: ['some%', 'Something', 18, 65] ``` MariaDB: ```sql SELECT ... FROM `User` WHERE (LOWER(`name`) LIKE ? ESCAPE '\\' AND `name` <> ?) AND (`age` >= ? AND `age` <= ?) -- values: ['some%', 'Something', 18, 65] ``` SQLite: ```sql SELECT ... FROM `User` WHERE (`name` LIKE ? ESCAPE '\' AND `name` <> ?) AND (`age` >= ? AND `age` <= ?) -- values: ['Some%', 'Something', 18, 65] ``` SQL Server: ```sql SELECT ... FROM "User" WHERE (LOWER("name") LIKE @p1 ESCAPE N'\' AND "name" <> @p2) AND ("age" >= @p3 AND "age" <= @p4) -- values: ['some%', 'Something', 18, 65] ``` Each field accepts only the operators that fit its type, so `{ age: { $like: '3%' } }` or `{ active: { $gt: false } }` is a compile error. | Operator | Fields | Matches | | - | - | - | | `$eq`, `$ne` | any | equal, not equal. `{ name: 'Ada' }` is shorthand for `$eq`. | | `$in`, `$nin` | any | any, or none, of the values. A bare array is an implicit `$in`. | | `$isNull`, `$isNotNull` | any | `{ deletedAt: { $isNull: true } }` | | `$not` | any | [the negation](https://uql-orm.dev/querying/logical-operators.md#not-and-nor-negate-a-condition) of the conditions inside it | | `$lt`, `$lte`, `$gt`, `$gte` | string, number, bigint, Date | less than, greater than, with or without equal | | `$between` | string, number, bigint, Date | between two bounds, both included: `{ $between: [18, 65] }` | | `$like`, `$ilike` | string | a `LIKE` pattern over the whole string | | `$startsWith`, `$endsWith`, `$includes` | string | the text at the start, at the end, or anywhere | | `$regex` | string | a regular expression, case-sensitive unless it opens with `(?i)` | | `$all` | array | holds every value | | `$size` | array | has that length: `3`, or `{ $gte: 2 }` | | `$elemMatch` | array | some element matches the condition | Each text operator has a case-insensitive `i` form: `$ilike`, `$istartsWith`, `$iendsWith`, `$iincludes`. Full-text search is `$text`, which goes at the top of `$where` rather than on a field; see [full-text search](https://uql-orm.dev/querying/full-text.md). A vector field takes `$near`; see [semantic search](https://uql-orm.dev/querying/semantic-search.md). ## Text matching `$like` patterns read the same on every engine: `%` is any run of characters, `_` is one character, and `\` makes the next character literal (`'50\%'` matches `50%`). A pattern ending in a lone `\` is refused. `$startsWith`, `$endsWith` and `$includes` take their text literally, so `%` and `_` are plain characters there. A leading `(?i)` makes `$regex` ignore case, as MongoDB’s `$options: 'i'` does. An embedded libSQL file refuses the flag, since its `REGEXP` is SQLite’s own; a libSQL or Turso server takes it. `$regex` needs SQL Server 2025 at compatibility level 170, and Bun 1.4.4 on `bun:sqlite`. The `i` operators match the same rows everywhere, by different means. PostgreSQL and CockroachDB use `ILIKE`. SQLite’s `LIKE` already ignores case, for ASCII letters only. MySQL, MariaDB and SQL Server lower both sides, as the MySQL tab above shows, so no plain index serves `$istartsWith`; on MySQL an [expression index](https://uql-orm.dev/entities/indexes.md) over `LOWER(column)` can. Their default collation already ignores case, though, so there `$startsWith` matches either case and keeps its plain index. On PostgreSQL it stays case-sensitive. ## Array matching `$all` compares scalars by JSON type, so `'5'` does not match `5`; an object or array value matches by what it holds. `$elemMatch` takes a value or operator map per key on object elements, as in `{ addresses: { $elemMatch: { city: 'NYC', zip: { $startsWith: '10' } } } }`. On scalar elements it takes an operator map, as in `{ tags: { $elemMatch: { $startsWith: 'ad' } } }`, where a single `$eq` or `$in` compares by JSON type, as `$all` does. `$size` also filters by a [relation’s size](https://uql-orm.dev/querying/relations.md#filtering-by-count-size). To return or sort by that size, see [counting](https://uql-orm.dev/querying/counting.md). ## Comparing with another column Wherever an operator takes a value, it takes a ref to another column of the same row in its place, `$between`, `$in` and `$ne` included, on every engine, MongoDB too: ```ts import { Entity, f, Field, refs } from 'uql-orm'; @Entity() export class Rate { @Field(f.number().autoIncrement()) id?: number; @Field(f.date()) effectiveFrom!: Date; @Field(f.date().nullable()) effectiveTo?: Date | null; } const rate = refs(Rate); await pool.findMany(Rate, { $where: { effectiveTo: { $gt: rate.effectiveFrom } }, }); ``` A [JSON path](https://uql-orm.dev/querying/json.md) compared with a ref reads as that column’s type. A ref names a column of the entity the query is on: one of another entity is refused, and is read off its own alias, `refs(Other, 'o')`, in [raw SQL](https://uql-orm.dev/querying/raw-sql.md#reading-another-table). ## `NULL` is compared as the engine compares it In SQL, `NULL <> 'a'` is neither true nor false, so every negation leaves a `NULL` row out. MongoDB compares a missing or `null` field as a value, and keeps it: | You write | SQL, `code` is `NULL` | MongoDB, `code` missing or `null` | | - | - | - | | `{ code: { $ne: 'a' } }` | left out | matches | | `{ code: { $nin: ['a'] } }` | left out | matches | | `{ code: { $in: ['a', null] } }` | left out | matches | | `{ code: { $not: { $eq: 'a' } } }`, `{ $nor: [{ code: 'a' }] }` | left out | matches | For the same rows everywhere, name `NULL` yourself: `{ $or: [{ code: { $ne: 'a' } }, { code: null }] }`. `{ code: null }` and `{ code: { $ne: null } }` mean “is null” and “is not null” on every engine. > **undefined throws** > > An `undefined` value anywhere in `$where` or `$having` throws, because `{ email: maybeEmail }` would otherwise match every row. Leave the key out, or pass `null`. ## JSONB dot-notation operators The operators also work on paths inside a JSON column, such as `'settings.isArchived': { $ne: true }`. See [JSON / JSONB](https://uql-orm.dev/querying/json.md). ## Next steps - [Logical operators](https://uql-orm.dev/querying/logical-operators.md): combine conditions with `$and`, `$or`, `$not` and `$nor`. - [Relations](https://uql-orm.dev/querying/relations.md): filter across related entities. # Logical Operators > Combine conditions with $and, $or, $not and $nor in UQL queries. Source: https://uql-orm.dev/querying/logical-operators Logical operators combine [comparison conditions](https://uql-orm.dev/querying/comparison-operators.md) in `$where`, nested to any depth: | Operator | Matches rows where | | - | - | | `$and` | every clause matches (the default) | | `$or` | at least one clause matches | | `$not` | the clauses do not all match | | `$nor` | no clause matches | ```ts title="You write" import { pool } from './uql.config.js'; import { User } from './shared/models/index.js'; const users = await pool.findMany(User, { $where: { $or: [ { name: { $istartsWith: 'A' } }, { status: 'pending', createdAt: { $lt: new Date('2025-01-01') } }, ], }, }); ``` PostgreSQL: ```sql SELECT ... FROM "User" WHERE "name" ILIKE $1 ESCAPE '\' OR ("status" = $2 AND "createdAt" < $3) ``` MySQL: ```sql SELECT ... FROM `User` WHERE LOWER(`name`) LIKE ? ESCAPE '\\' OR (`status` = ? AND `createdAt` < ?) ``` MariaDB: ```sql SELECT ... FROM `User` WHERE LOWER(`name`) LIKE ? ESCAPE '\\' OR (`status` = ? AND `createdAt` < ?) ``` SQLite: ```sql SELECT ... FROM `User` WHERE `name` LIKE ? ESCAPE '\' OR (`status` = ? AND `createdAt` < ?) ``` SQL Server: ```sql SELECT ... FROM "User" WHERE LOWER("name") LIKE @p1 ESCAPE N'\' OR ("status" = @p2 AND "createdAt" < @p3) ``` Fields in one object are joined with `AND`, as in the second clause above, so `$and: [{ name: 'roger' }, { status: 'active' }]` and `{ name: 'roger', status: 'active' }` are the same query. Write `$and` to combine two `$or` groups, or to add a [`sql`](https://uql-orm.dev/querying/sub-queries.md) condition. ## `$not` and `$nor`: negate a condition On a field, `$not` negates the conditions inside it: ```ts title="You write" const users = await pool.findMany(User, { $where: { status: 'active', name: { $not: { $startsWith: 'test' } } }, }); ``` PostgreSQL: ```sql SELECT ... FROM "User" WHERE "status" = $1 AND NOT ("name" LIKE $2 ESCAPE '\') ``` MySQL: ```sql SELECT ... FROM `User` WHERE `status` = ? AND NOT (`name` LIKE ? ESCAPE '\\') ``` MariaDB: ```sql SELECT ... FROM `User` WHERE `status` = ? AND NOT (`name` LIKE ? ESCAPE '\\') ``` SQLite: ```sql SELECT ... FROM `User` WHERE `status` = ? AND NOT (`name` LIKE ? ESCAPE '\') ``` SQL Server: ```sql SELECT ... FROM "User" WHERE "status" = @p1 AND NOT ("name" LIKE @p2 ESCAPE N'\') ``` At the top level, `$not` takes an array and negates its clauses joined with `AND`, so a row matches unless every clause does. `$nor` negates them joined with `OR`, so a row matches only if no clause does: ```ts title="You write" const users = await pool.findMany(User, { $where: { $nor: [{ name: 'admin' }, { status: 'banned' }] }, }); ``` PostgreSQL: ```sql SELECT ... FROM "User" WHERE NOT ("name" = $1 OR "status" = $2) -- with $not: WHERE NOT ("name" = $1 AND "status" = $2) ``` MySQL: ```sql SELECT ... FROM `User` WHERE NOT (`name` = ? OR `status` = ?) -- with $not: WHERE NOT (`name` = ? AND `status` = ?) ``` MariaDB: ```sql SELECT ... FROM `User` WHERE NOT (`name` = ? OR `status` = ?) -- with $not: WHERE NOT (`name` = ? AND `status` = ?) ``` SQLite: ```sql SELECT ... FROM `User` WHERE NOT (`name` = ? OR `status` = ?) -- with $not: WHERE NOT (`name` = ? AND `status` = ?) ``` SQL Server: ```sql SELECT ... FROM "User" WHERE NOT ("name" = @p1 OR "status" = @p2) -- with $not: WHERE NOT ("name" = @p1 AND "status" = @p2) ``` On SQL, a negation leaves out rows where the compared field is `NULL`; MongoDB keeps them. See [`NULL` per engine](https://uql-orm.dev/querying/comparison-operators.md#null-is-compared-as-the-engine-compares-it). # Sub-Queries > Add raw SQL conditions and correlated sub-queries to $where with the sql() helper. Source: https://uql-orm.dev/querying/sub-queries When no operator expresses a condition, write it as a [`sql`](https://uql-orm.dev/querying/raw-sql.md) fragment. Its values are still bound as parameters. SQL databases only. ## A raw condition in `$where` Put it in a `$and` or `$or` array beside ordinary conditions, naming columns with `refs()`: ```ts title="You write" import { pool } from './uql.config.js'; import { sql, refs } from 'uql-orm'; import { Item } from './shared/models/index.js'; const item = refs(Item); const items = await pool.findMany(Item, { $select: { id: true }, $where: { $and: [{ companyId: 1 }, sql`${item.price} * ${item.stock} > ${10000}`], }, }); ``` PostgreSQL: ```sql SELECT "id" FROM "Item" WHERE "companyId" = $1 AND "price" * "stock" > $2 ``` MySQL: ```sql SELECT `id` FROM `Item` WHERE `companyId` = ? AND `price` * `stock` > ? ``` MariaDB: ```sql SELECT `id` FROM `Item` WHERE `companyId` = ? AND `price` * `stock` > ? ``` SQLite: ```sql SELECT `id` FROM `Item` WHERE `companyId` = ? AND `price` * `stock` > ? ``` SQL Server: ```sql SELECT "id" FROM "Item" WHERE "companyId" = @p1 AND "price" * "stock" > @p2 ``` ## `$exists` / `$nexists` sub-queries Over a declared relation, use the built-in [relation filters](https://uql-orm.dev/querying/relations.md). Otherwise pass `$exists` or `$nexists` a `sql` callback, which receives the dialect to render a nested query: ```ts title="You write" import { sql } from 'uql-orm'; import { User, Item } from './shared/models/index.js'; const items = await pool.findMany(Item, { $select: { id: true }, $where: { $nexists: sql(({ ctx, dialect, escapedPrefix }) => { dialect.find( ctx, User, { $select: { id: true }, $where: { // escapedPrefix is the outer table's alias, with its trailing dot. companyId: sql(({ ctx }) => ctx.append(`${escapedPrefix}${dialect.escapeId('companyId')}`), ), }, }, { autoPrefix: true }, ); }), }, }); ``` PostgreSQL: ```sql SELECT "id" FROM "Item" WHERE NOT EXISTS (SELECT "User"."id" FROM "User" WHERE "User"."companyId" = "Item"."companyId") ``` MySQL: ```sql SELECT `id` FROM `Item` WHERE NOT EXISTS (SELECT `User`.`id` FROM `User` WHERE `User`.`companyId` = `Item`.`companyId`) ``` MariaDB: ```sql SELECT `id` FROM `Item` WHERE NOT EXISTS (SELECT `User`.`id` FROM `User` WHERE `User`.`companyId` = `Item`.`companyId`) ``` SQLite: ```sql SELECT `id` FROM `Item` WHERE NOT EXISTS (SELECT `User`.`id` FROM `User` WHERE `User`.`companyId` = `Item`.`companyId`) ``` SQL Server: ```sql SELECT "id" FROM "Item" WHERE NOT EXISTS (SELECT "User"."id" FROM "User" WHERE "User"."companyId" = "Item"."companyId") ``` Capture the outer table’s `escapedPrefix` as above, and escape the column with `dialect.escapeId`: a `refs()` column inside the nested query would resolve against the nested table. ## Understanding `sql` `sql` has two forms. The template form, ``sql`${item.price} > ${limit}` ``, covers most SQL: values are bound and refs become columns. A `sql` value interpolated into another template is inserted as SQL, not bound, so fragments compose. The callback form, `sql(({ ctx, dialect, escapedPrefix }) => { ... })`, is for SQL the dialect must render, such as a sub-query. The callback receives: - `ctx`: the query being built. `ctx.append(sql)` writes SQL as is; `ctx.addValue(value)` binds a value and writes its placeholder. - `dialect`: the current SQL dialect, for nested queries (`dialect.find(...)`). - `escapedPrefix`: the escaped alias of the table in scope, with its trailing dot. - `prefix`: the same alias, unescaped, and empty where there is none. Instead of writing to `ctx`, the callback can return a string or number, which is appended as SQL. `sql` also works as a computed column in `$select`; see [raw projections](https://uql-orm.dev/querying/querier.md#raw-projections-in-select). ## Next steps - [Raw SQL](https://uql-orm.dev/querying/raw-sql.md): the `sql` tag and running whole raw statements. - [Relations](https://uql-orm.dev/querying/relations.md): built-in `EXISTS` and `$size` relation filters. - [Logical operators](https://uql-orm.dev/querying/logical-operators.md): combining raw conditions with others. # Raw SQL > Run your own SQL with all() and run(), values bound and rows typed. Source: https://uql-orm.dev/querying/raw-sql When the query API does not cover what you need, write the SQL yourself. `all()` returns typed rows and `run()` executes a write. Both are tags: write the statement right after the method, and each interpolated value is bound as a parameter: ```ts import { pool } from './uql.config.js'; const stats = await pool.all<{ status: string; total: number }>` SELECT status, COUNT(*) AS total FROM "User" WHERE "deletedAt" IS NULL AND "createdAt" > ${since} GROUP BY status `; const { changes } = await pool.run`UPDATE "User" SET "status" = ${'active'} WHERE "id" = ${123}`; ``` `run()` returns a `QueryUpdateResult`: `changes` is the number of rows affected, and `ids` holds the inserted ids where the engine reports them. Use it for `INSERT`, `UPDATE`, `DELETE` and DDL. Each call runs one statement. Engines differ on several statements in one string, from running them all to refusing, so run a script as one call per statement. A column reads back as the query API reads it, and on Postgres each element of an array does too. > **Filters and tenant context do not apply** > > [Query filters](https://uql-orm.dev/querying/filters.md), including `security` filters and [soft-delete](https://uql-orm.dev/entities/soft-delete.md), and the [multi-tenancy](https://uql-orm.dev/multi-tenancy.md) context apply only to UQL’s query methods. Scope raw SQL yourself, as the `"deletedAt" IS NULL` above does, or back it with row-level security in the database. ## What `sql` interpolates A value is bound (`$1`, `?` or `@p1`, depending on the engine): a string, number, boolean, `bigint`, `Date`, bytes or `null`. On the Postgres family an array binds as one array value, `= ANY(${ids})`, and a trigger or check writes it as the same array; another engine has no array type and refuses one. `undefined` is refused, as in `$where`. Bind a JSON document as text: `${JSON.stringify(doc)}`. A field read off `refs(Entity)` becomes its column, and another `sql` is spliced in place. That makes `sql` useful inside typed queries too: ```ts import { sql, refs } from 'uql-orm'; const item = refs(Item); await pool.updateMany( Item, { $where: { id: 1 } }, { price: sql`ROUND(${item.price} * ${1.1}, 2)` }, ); sql`LOG10(${100})`.as('score'); // .as() names a $select projection ``` A ref renders its column the way a query would: through the [naming strategy](https://uql-orm.dev/naming-strategy.md) and a field’s `.name()`, escaped, and qualified by the table alias in scope. It follows a rename in your editor and carries the field’s type, so `{ price: item.price }` compiles where `{ price: item.name }` does not. The SQL around it is not type-checked. ### Reading another table SQL reading another table than its statement’s names it with `tableOf`, and its columns off refs read under an alias, so a rename or the naming strategy reaches both: ```ts import { aliasOf, refs, sql, tableOf } from 'uql-orm'; const author = refs(User, 'author'); sql`(SELECT ${author.name} FROM ${tableOf(author)} WHERE ${author.id} = ${1})`; ``` `tableOf(author)` renders the table and its alias, `tableOf(User)` the table alone. Two aliases read one table twice. For an entity declared later, a computed field’s SQL included, pass an arrow: `refs(() => User, 'author')`. `aliasOf(author)` renders the alias alone, for SQL reading the whole row or naming a derived table after it, so the name is never written by hand: ```ts sql`pdb.score(${aliasOf(author)})`; sql`LEFT JOIN LATERAL (SELECT ${author.name} FROM ${tableOf(author)} LIMIT 1) ${aliasOf(author)} ON TRUE`; ``` A name the statement makes up, read in two places, is `sql.id(name)`, quoted as the engine quotes one: ```ts const word = sql.id('word'); sql`SELECT ${word}, COUNT(*) FROM ${tableOf(author)} CROSS JOIN LATERAL UNNEST(STRING_TO_ARRAY(${author.name}, ' ')) AS ${word} GROUP BY ${word}`; ``` ### Building a statement from parts Compose a statement from smaller `sql` fragments, each binding its own values. A fragment you leave out can be an empty one: ```ts const byStatus = status ? sql`AND "status" = ${status}` : sql``; await pool.all`SELECT * FROM "User" WHERE "deletedAt" IS NULL ${byStatus}`; ``` `sql.join(fragments, separator)` puts a list of them together, a comma and a space apart unless you say otherwise: ```ts const conditions = [sql`"createdAt" > ${since}`]; if (status) conditions.push(sql`"status" = ${status}`); await pool.all`SELECT * FROM "User" WHERE ${sql.join(conditions, ' AND ')}`; ``` A value in the list binds, so `sql.join(values)` writes the list for an `IN`, one value each, on every engine: ```ts await pool.all`SELECT * FROM "User" WHERE "status" IN (${sql.join(['active', 'invited'])})`; ``` A piece of SQL held in a string, such as a shared `ORDER BY` clause, goes in the template as `sql.text(clause)`. A plain string is bound as a value. ## Trusted text and dialect-driven SQL `all()` and `run()` also take a statement built apart as a `sql` value. For SQL you hold in a string, such as a statement read from a file, that value is `sql.text(sql)`, which binds nothing: ```ts import { sql } from 'uql-orm'; await pool.run(sql.text(sqlFromFile)); ``` `sql(callback)` builds SQL that depends on the dialect. Whatever the callback writes is emitted as is, so bind input with `ctx.addValue()`: ```ts const byEmail = sql(({ dialect, ctx }) => { ctx.append(`LOWER(${dialect.escapeId('email')}) = `); ctx.addValue(email); }); ``` `sql(...)` called with a plain template literal does not compile, because it would splice the values into the text. > **Never concatenate input** > > Only `${value}` inside a `sql` template is bound. SQL built by string concatenation, or passed to `sql.text`, is open to injection, and nothing will catch it. ## Raw SQL on the pool `pool.all()` and `pool.run()` take a connection per call, like the pool’s [other methods](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx), so two of them in a `Promise.all` run in parallel. Inside a `pool.transaction()` callback they join the transaction. For statements that must share a connection, use the querier from `pool.withQuerier()` or `pool.transaction()`. `all()` and `run()` exist only on SQL queriers and pools (`SqlQuerier`, `SqlQuerierPool`), not on MongoDB; `isSqlQuerier(querier)` tells the two apart. ## Next steps - [Sub-Queries](https://uql-orm.dev/querying/sub-queries.md): `sql` fragments inside a typed query. - [Transactions](https://uql-orm.dev/querying/transactions.md): raw statements inside a unit of work. - [Logging & Monitoring](https://uql-orm.dev/logging.md): the SQL and timings your queries produce. # Aggregate Queries > Group rows and compute COUNT, SUM, AVG, MIN and MAX with HAVING, on every SQL engine and MongoDB. Source: https://uql-orm.dev/querying/aggregate `aggregate()` computes totals over the rows a query matches, or over each group of them, as SQL’s `GROUP BY` and `HAVING` do. The same query runs on every SQL engine and on MongoDB. ```ts title="You write" import { pool } from './uql.config.js'; import { Order } from './shared/models/index.js'; const results = await pool.aggregate(Order, { $where: { amount: { $gt: 0 } }, // filters rows before grouping $group: { status: true }, $select: { total: { $sum: { amount: true } }, count: { $count: '*' }, }, $having: { count: { $gt: 5 } }, // filters groups after aggregation $sort: { total: -1 }, $limit: 10, }); // [{ status: 'paid', total: 5400, count: 31 }, ...] ``` PostgreSQL: ```sql SELECT "status", SUM("amount") "total", COUNT(*) "count" FROM "Order" WHERE "amount" > $1 GROUP BY "status" HAVING COUNT(*) > $2 ORDER BY SUM("amount") DESC LIMIT 10 ``` MySQL: ```sql SELECT `status`, SUM(`amount`) `total`, COUNT(*) `count` FROM `Order` WHERE `amount` > ? GROUP BY `status` HAVING COUNT(*) > ? ORDER BY SUM(`amount`) DESC LIMIT 10 ``` MariaDB: ```sql SELECT `status`, SUM(`amount`) `total`, COUNT(*) `count` FROM `Order` WHERE `amount` > ? GROUP BY `status` HAVING COUNT(*) > ? ORDER BY SUM(`amount`) DESC LIMIT 10 ``` SQLite: ```sql SELECT `status`, SUM(`amount`) `total`, COUNT(*) `count` FROM `Order` WHERE `amount` > ? GROUP BY `status` HAVING COUNT(*) > ? ORDER BY SUM(`amount`) DESC LIMIT 10 ``` SQL Server: ```sql SELECT "status", SUM("amount") "total", COUNT(*) "count" FROM "Order" WHERE "amount" > @p1 GROUP BY "status" HAVING COUNT(*) > @p2 ORDER BY SUM("amount") DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` MongoDB: ```json [ { "$match": { "amount": { "$gt": 0 } } }, { "$group": { "_id": { "status": "$status" }, "total": { "$sum": "$amount" }, "_uql_count_total": { "$sum": { "$cond": [{ "$eq": [{ "$ifNull": ["$amount", null] }, null] }, 0, 1] } }, "count": { "$sum": 1 } } }, { "$project": { "_id": 0, "status": "$_id.status", "total": { "$cond": [{ "$eq": ["$_uql_count_total", 0] }, null, "$total"] }, "count": 1 } }, { "$match": { "count": { "$gt": 5 } } }, { "$sort": { "total": -1 } }, { "$limit": 10 } ] ``` Each result row holds the `$group` columns and the `$select` aliases. `$select` takes computed columns only: to return a plain column, group by it. Fields are named as keys, as in `findMany`, which makes a typo a compile error and lets an editor rename reach them. An alias cannot repeat a `$group` column, since both would come back under one name. `$group` and `$select` are both optional. `$select` alone gives a grand total: ```ts const [{ revenue }] = await pool.aggregate(Order, { $select: { revenue: { $sum: { amount: true } } }, }); ``` `$group` alone returns each distinct value once, as `SELECT DISTINCT` does. `aggregate()` takes no `$distinct` of its own; for distinct rows of an entity, use it on a `findMany`: ```ts const names = await pool.findMany(User, { $select: { name: true }, $distinct: true, }); ``` ## Aggregate functions | `$select` entry | SQL | Type | | - | - | - | | `{ $count: '*' }` | `COUNT(*)` | `number` | | `{ $count: { field: true } }` | `COUNT("field")` | `number` | | `{ $countDistinct: { field: true } }` | `COUNT(DISTINCT "field")` | `number` | | `{ $sum: { field: true } }` | `SUM("field")` | the column’s type, or `null` | | `{ $avg: { field: true } }` | `AVG("field")` | `number`, or `null` | | `{ $min: { field: true } }` | `MIN("field")` | the column’s type, or `null` | | `{ $max: { field: true } }` | `MAX("field")` | the column’s type, or `null` | `COUNT("field")` counts non-null values only. `$sum` and `$avg` take numeric columns, and a `$sum` over a `bigint` column is a `bigint`. Over no rows, the counts return `0` and the rest return `null`, hence the `| null`. MongoDB’s `$sum` answers `0` there, so UQL also counts the values it summed (`_uql_count_total` in the pipeline above) and returns `null` when there were none, as SQL does. Only counting has a distinct variant. ## Filtering and sorting groups `$where` filters rows before grouping. `$having` filters the groups afterwards, by any result column, with the [comparison operators](https://uql-orm.dev/querying/comparison-operators.md) that column’s type allows. `$sort` orders by a grouped column or a computed alias, and `$skip` and `$limit` page the groups. ## Counting only some rows A `$where` beside a function aggregates only the rows it matches, which pivots rows into columns in one query. Published posts, drafts and published points per author: ```ts title="You write" const byAuthor = await pool.aggregate(Post, { $group: { authorId: true }, $select: { published: { $count: '*', $where: { published: true } }, drafts: { $count: '*', $where: { published: false } }, publishedPoints: { $sum: { points: true }, $where: { published: true } }, }, }); ``` PostgreSQL: ```sql SELECT "authorId", COUNT("published") "published", COUNT("drafts") "drafts", SUM("publishedPoints") "publishedPoints" FROM ( SELECT "authorId", CASE WHEN "published" = $1 THEN 1 END "published", CASE WHEN "published" = $2 THEN 1 END "drafts", CASE WHEN "published" = $3 THEN "points" END "publishedPoints" FROM "Post" ) "_uql_rows" GROUP BY "authorId" ``` MySQL: ```sql SELECT `authorId`, COUNT(`published`) `published`, COUNT(`drafts`) `drafts`, SUM(`publishedPoints`) `publishedPoints` FROM ( SELECT `authorId`, CASE WHEN `published` = ? THEN 1 END `published`, CASE WHEN `published` = ? THEN 1 END `drafts`, CASE WHEN `published` = ? THEN `points` END `publishedPoints` FROM `Post` ) `_uql_rows` GROUP BY `authorId` ``` MariaDB: ```sql SELECT `authorId`, COUNT(`published`) `published`, COUNT(`drafts`) `drafts`, SUM(`publishedPoints`) `publishedPoints` FROM ( SELECT `authorId`, CASE WHEN `published` = ? THEN 1 END `published`, CASE WHEN `published` = ? THEN 1 END `drafts`, CASE WHEN `published` = ? THEN `points` END `publishedPoints` FROM `Post` ) `_uql_rows` GROUP BY `authorId` ``` SQLite: ```sql SELECT `authorId`, COUNT(`published`) `published`, COUNT(`drafts`) `drafts`, SUM(`publishedPoints`) `publishedPoints` FROM ( SELECT `authorId`, CASE WHEN `published` = ? THEN 1 END `published`, CASE WHEN `published` = ? THEN 1 END `drafts`, CASE WHEN `published` = ? THEN `points` END `publishedPoints` FROM `Post` ) `_uql_rows` GROUP BY `authorId` ``` SQL Server: ```sql SELECT "authorId", COUNT("published") "published", COUNT("drafts") "drafts", SUM("publishedPoints") "publishedPoints" FROM ( SELECT "authorId", CASE WHEN "published" = @p1 THEN 1 END "published", CASE WHEN "published" = @p2 THEN 1 END "drafts", CASE WHEN "published" = @p3 THEN "points" END "publishedPoints" FROM "Post" ) "_uql_rows" GROUP BY "authorId" ``` The function’s `$where` takes the entity’s fields and relations, as a query’s does, so `{ $count: '*', $where: { tags: { $size: { $gte: 2 } } } }` counts the posts with two tags or more; the query’s `$where` still applies first. On MongoDB it takes every operator but `$text`, which MongoDB runs only as a pipeline’s first stage. ## Grouping by a relation’s field A `$group` entry can reach a field on a to-one relation, at any depth, under an alias you choose. Posts per country of the author’s company: ```ts title="You write" const byCountry = await pool.aggregate(Post, { $group: { country: { author: { company: { country: true } } } }, $select: { posts: { $count: '*' }, points: { $sum: { points: true } } }, }); // [{ country: 'CO', posts: 12, points: 340 }, ...] ``` PostgreSQL: ```sql SELECT "author.company"."country" "country", COUNT(*) "posts", SUM("Post"."points") "points" FROM "Post" INNER JOIN "User" "author" ON "author"."id" = "Post"."authorId" INNER JOIN "Company" "author.company" ON "author.company"."id" = "author"."companyId" GROUP BY "author.company"."country" ``` MySQL: ```sql SELECT `author.company`.`country` `country`, COUNT(*) `posts`, SUM(`Post`.`points`) `points` FROM `Post` INNER JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` INNER JOIN `Company` `author.company` ON `author.company`.`id` = `author`.`companyId` GROUP BY `author.company`.`country` ``` MariaDB: ```sql SELECT `author.company`.`country` `country`, COUNT(*) `posts`, SUM(`Post`.`points`) `points` FROM `Post` INNER JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` INNER JOIN `Company` `author.company` ON `author.company`.`id` = `author`.`companyId` GROUP BY `author.company`.`country` ``` SQLite: ```sql SELECT `author.company`.`country` `country`, COUNT(*) `posts`, SUM(`Post`.`points`) `points` FROM `Post` INNER JOIN `User` `author` ON `author`.`id` = `Post`.`authorId` INNER JOIN `Company` `author.company` ON `author.company`.`id` = `author`.`companyId` GROUP BY `author.company`.`country` ``` SQL Server: ```sql SELECT "author.company"."country" "country", COUNT(*) "posts", SUM("Post"."points") "points" FROM "Post" INNER JOIN "User" "author" ON "author"."id" = "Post"."authorId" INNER JOIN "Company" "author.company" ON "author.company"."id" = "author"."companyId" GROUP BY "author.company"."country" ``` Rows stay flat, keyed by the alias, which `$having` and `$sort` can use. Only to-one relations are allowed, since a to-many would multiply the totals. The join is inner, so a row whose relation is missing is left out; group by the foreign key (`{ authorId: true }`) to count it. A [relation aggregate](https://uql-orm.dev/entities/computed-fields.md#relation-aggregates), such as an order’s item count, groups and totals like any other field. UQL reads it in a subquery and groups the result, so an `$avg` over it averages the per-order values, not the items. ## Next steps - [Querier](https://uql-orm.dev/querying/querier.md): reads and the rows they are typed as. - [Logical Operators](https://uql-orm.dev/querying/logical-operators.md): compose the `$where` that runs before grouping. - [Counting](https://uql-orm.dev/querying/counting.md): counting related rows from a find. # JSON / JSONB > Filter, update and sort by paths inside JSON columns, type-checked, on every SQL engine and MongoDB. Source: https://uql-orm.dev/querying/json UQL filters, sorts and updates by paths inside a JSON column, and type-checks those paths against the payload you declare, a `Json` type or a schema’s output. It works on every SQL engine and on MongoDB. ## Declaring a JSON field Wrap the field’s type in `Json`: ```ts import { f, Entity, Field, type Json } from 'uql-orm'; @Entity() export class Company { @Field(f.number().autoIncrement()) id?: number; @Field(f.jsonb().nullable()) settings?: Json<{ region?: string; isArchived?: boolean; seats?: number; tags?: string[]; billing?: { plan?: string; coupon?: string }; }> | null; } ``` `Json` is required. Without it, UQL reads a plain object type like `{ seats?: number }` as a relation, and `$where`, `$sort` and the update operators reject it. A column with no declared payload is a bare `Json`, which takes any value and any path. For a list of documents, use `Json[]`; its paths address the elements, so `'lines.sku'` matches any line with that SKU. On PostgreSQL, use `f.jsonb()` rather than `f.json()`: it can be indexed, and `$size`, `$all` and `$elemMatch` need it. ## A schema for the payload Pass a [Standard Schema](https://standardschema.dev) to the builder, and the property’s type is that schema’s output. Zod, Valibot and ArkType all implement it (UQL doesn’t depend on them): ```ts import { z } from 'zod'; import { f, Entity, Field, type Json } from 'uql-orm'; const Settings = z.object({ region: z.string().optional(), seats: z.number().optional(), }); @Entity() export class Company { @Field(f.number().autoIncrement()) id?: number; @Field(f.jsonb(Settings).nullable()) settings?: Json> | null; } ``` UQL reads the schema only for its type. It does not validate a payload on write or read, so validate input in your own code before it reaches the ORM. ## Filtering A dot-path in `$where` takes every [comparison operator](https://uql-orm.dev/querying/comparison-operators.md) its type allows: ```ts title="You write" const companies = await pool.findMany(Company, { $where: { 'settings.isArchived': { $ne: true }, 'settings.region': 'eu', }, }); ``` PostgreSQL: ```sql SELECT ... FROM "Company" WHERE ("settings"->'isArchived') <> $1::jsonb AND ("settings"->>'region') = $2 -- values: ['true', 'eu'] ``` MySQL: ```sql SELECT ... FROM `Company` WHERE `settings`->'$.isArchived' <> CAST(? AS JSON) AND (`settings`->>'$.region') = ? -- values: ['true', 'eu'] ``` MariaDB: ```sql SELECT ... FROM `Company` WHERE JSON_EXTRACT(`settings`, '$.isArchived') <> JSON_EXTRACT(?, '$') AND JSON_VALUE(`settings`, '$.region') = ? -- values: ['true', 'eu'] ``` SQLite: ```sql SELECT ... FROM `Company` WHERE (`settings` -> '$.isArchived') <> JSON(?) AND JSON_EXTRACT(`settings`, '$.region') = ? -- values: ['true', 'eu'] ``` SQL Server: ```sql SELECT ... FROM "Company" WHERE (SELECT "value" FROM OPENJSON("settings", '$') WHERE "key" = N'isArchived') <> @p1 AND (SELECT "value" FROM OPENJSON("settings", '$') WHERE "key" = N'region') = @p2 -- values: ['true', 'eu'] ``` A typo in the path, an operator the type does not allow (`$size` on a string) or a value of the wrong type is a compile error. A bare `Json` accepts any path made of identifier keys (letters, digits and `_`, not starting with a digit), and throws at run time on any other key. Numbers compare by value, so a stored `1.0` matches `1`, and a number comparison can use an index on the path. Booleans compare as JSON and strings as text. On PostgreSQL, a number comparison matches only where the path holds a number. `$not` and `$between` work on paths as they do on columns. > **A missing key is NULL** > > On SQL, a missing key reads as `NULL`, so `{ $ne: true }` leaves out a row with no `isArchived` key. See [how `NULL` compares](https://uql-orm.dev/querying/comparison-operators.md#null-is-compared-as-the-engine-compares-it). For arrays, `$size`, `$all` and `$elemMatch` work on paths too. An object or array in `$all`, or an object in `$elemMatch`, matches an element that contains everything it lists, whatever else the element holds; a key given an operator map inside it is compared as a path is. A path holding a scalar or an object instead of an array matches none of them on SQL. On MongoDB, `$all` also matches a scalar equal to its one value, and on MySQL and MariaDB, `$all: [3]` also matches `[[3]]`. ## Sorting `$sort` takes the same paths, and numbers sort by value on every engine: ```ts const companies = await pool.findMany(Company, { $sort: { 'settings.seats': 'desc' }, }); ``` ## Updating Five operators change part of the document in one atomic statement, leaving the rest alone. Starting from `{ region: 'eu', seats: 12, tags: ['legacy', 'stale'] }`: ```ts await pool.updateOneById(Company, id, { settings: { $set: { region: 'us' } }, // region: 'us' }); await pool.updateOneById(Company, id, { settings: { $unset: ['seats'] }, // seats removed }); await pool.updateOneById(Company, id, { settings: { $push: { tags: 'new' } }, // tags: ['legacy', 'stale', 'new'] }); await pool.updateOneById(Company, id, { settings: { $pull: { tags: 'stale' } }, // tags: ['legacy'] }); await pool.updateOneById(Company, id, { settings: { $addToSet: { tags: 'legacy' } }, // tags: ['legacy'], already there }); ``` Here is the `$set` above on each engine: PostgreSQL: ```sql UPDATE "Company" SET "settings" = JSONB_SET(COALESCE("settings", '{}'::jsonb), '{"region"}', $1::jsonb) WHERE "id" = $2 -- values: ['"us"', id] ``` MySQL: ```sql UPDATE `Company` SET `settings` = JSON_SET(COALESCE(`settings`, JSON_OBJECT()), '$.region', CAST(? AS JSON)) WHERE `id` = ? -- values: ['"us"', id] ``` MariaDB: ```sql UPDATE `Company` SET `settings` = JSON_SET(COALESCE(`settings`, JSON_OBJECT()), '$.region', JSON_EXTRACT(?, '$')) WHERE `id` = ? -- values: ['"us"', id] ``` SQLite: ```sql UPDATE `Company` SET `settings` = JSON_SET(COALESCE(`settings`, JSON_OBJECT()), '$.region', JSON(?)) WHERE `id` = ? -- values: ['"us"', id] ``` SQL Server: ```sql UPDATE "Company" SET "settings" = JSON_MODIFY(COALESCE("settings", '{}'), '$.region', @p1) WHERE "id" = @p2 -- values: ['us', id] ``` `$set`, `$push` and `$addToSet` on a `NULL` column write into an empty document. `$push` and `$addToSet` make a one-element array of a missing or `null` key; `$addToSet` appends a string, finite number or boolean only where the array lacks it. `$pull` removes every element equal to the value, `null` included, and leaves an empty array when it removes the last one. All three leave a value that is no array as it is, and `$pull` a missing key. For object elements, key order matters to `$pull` on SQLite, SQL Server and MongoDB, but not on PostgreSQL, MySQL or MariaDB. `$set` replaces each key you name, arrays included, so use `$push`, `$pull` and `$addToSet` to change an array’s elements. A dotted path writes one nested value and keeps its siblings, and `$unset` takes one too: ```ts await pool.updateOneById(Company, id, { settings: { $set: { 'billing.plan': 'pro' }, $unset: ['billing.coupon'] }, }); ``` Every parent the path passes through is created where it is missing, `NULL` or not an object, on every engine, a `NULL` column included. A path never steps into an array. One update can combine operators, on one key too. They apply in order, `$pull`, `$set`, `$push`, `$addToSet`, `$unset`, each seeing what the one before wrote: `$pull` and `$push` on one key replace an element, and `$set` of `billing` with `billing.plan` merges. MongoDB refuses two operators on one path, so UQL works the result out before the statement runs, the same on every engine. Only a value set by `sql` takes no other operator inside it. The operators are checked against `T`: `$push` and `$pull` accept only array keys and their element type, `$addToSet` only arrays of scalars, and a dotted path only a path of `T` with that path’s type. They work in update payloads (`updateOneById`, `updateMany`, and an upsert’s [`$update`](https://uql-orm.dev/querying/methods.md#updating-a-conflicting-row-its-own-way)). Inserts and the rows `upsertOne`, `upsertMany` and `saveOne` write take plain values only. A JSON array column (`Json` or `Json[]`) takes `$pull`, `$push` and `$addToSet`, each with a list of elements, in that order: every element equal to one pulled goes, each pushed one is appended, and each added one is appended only if the array lacks it. Elements compare by type as well as value, so `1`, `'1'` and `true` are three. A `NULL` column counts as an empty array, and a stored value that is no array stays as it is: ```ts import { f, Entity, Field, type Json } from 'uql-orm'; @Entity() export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.jsonb().nullable()) tags?: Json | null; } // tags: ['news', 'draft'] await pool.updateOneById(Article, id, { tags: { $pull: ['draft'], $addToSet: ['news', 'release'] }, }); // tags: ['news', 'release'] ``` ## Engine support What each operation compiles to: | Operation | PostgreSQL | MySQL | MariaDB | SQLite | SQL Server | | - | - | - | - | - | - | | Filter | `->>'key'` | `->>'key'` | `JSON_VALUE()` | `JSON_EXTRACT()` | `OPENJSON()` | | Sort | `->'key'` | `->'key'` | `CAST(JSON_VALUE())`, then text | `JSON_EXTRACT()` | `TRY_CAST(OPENJSON())`, then text | | `$set` | `JSONB_SET()` | `JSON_SET()` | `JSON_SET()` | `JSON_SET()` | `JSON_MODIFY()` | | `$unset` | `#-` | `JSON_REMOVE()` | `JSON_REMOVE()` | `JSON_REMOVE()` | `JSON_MODIFY(..., NULL)` | | `$push` | `JSONB_SET()` + `\|\|` | `JSON_ARRAY_APPEND()` | `JSON_ARRAY_APPEND()` | `JSON_INSERT()` | `JSON_MODIFY('append $')` | | `$pull` | `JSONB_AGG()` filter | `JSON_TABLE()` filter | `JSON_TABLE()` + `JSON_EQUALS()` | `JSON_EACH()` filter | `OPENJSON()` + `STRING_AGG()` | | `$addToSet` | `@>` + `JSONB_SET()` | `JSON_CONTAINS()` | `JSON_CONTAINS()` | `JSON_EACH()` | `OPENJSON()` + `JSON_MODIFY()` | | `$size` | `JSONB_ARRAY_LENGTH()` | `JSON_LENGTH()` | `JSON_LENGTH()` | `JSON_ARRAY_LENGTH()` | `OPENJSON()` + `COUNT(*)` | | `$all` | `@> ::jsonb` | `JSON_CONTAINS()` | `JSON_CONTAINS()` | `JSON_EACH()` | `OPENJSON()` | | `$elemMatch` | `JSONB_ARRAY_ELEMENTS` | `JSON_TABLE()`¹ | `JSON_TABLE()` | `JSON_EACH()` | `OPENJSON()` | ¹ A single `$eq` or `$in` on an element uses containment instead (`JSON_OVERLAPS()` for several), which an index can serve. CockroachDB and every Postgres pool emit the PostgreSQL SQL, except for binding: `BunSqlQuerierPool` writes `( $N::text )::jsonb` where Bun’s client needs it, the others `$N::jsonb`. MongoDB stores JSON natively and takes the same operators by the same rules. Minimum versions are PostgreSQL 16, MySQL 8.4, MariaDB 12.2, SQLite 3.45 and SQL Server 2017. `$pull` alone has older floors: MySQL 8.0.4 (`JSON_TABLE`), MariaDB 10.7 (`JSON_EQUALS`) and SQLite 3.38 (`->`). To index a filtered path, read it off the column’s ref, `index([company.settings.region])`: see [JSON indexes](https://uql-orm.dev/entities/indexes.md#json-indexes). For an array searched by `$all` or a scalar `$elemMatch`, index its elements with `{ column: company.settings.tags, type: [String] }`. ## Next steps - [Comparison Operators](https://uql-orm.dev/querying/comparison-operators.md): the operators a path takes. - [Decorators](https://uql-orm.dev/entities/basic.md): declaring `json` and `jsonb` fields. - [Full-Text Search](https://uql-orm.dev/querying/full-text.md): searching text columns instead. # Full-Text Search > Search and rank text with $text on PostgreSQL, CockroachDB, MySQL, MariaDB, SQLite and MongoDB, with one index declaration and per-column weights. Source: https://uql-orm.dev/querying/full-text `$text` runs a full-text search on each database’s own engine. Declare a fulltext index on the entity, and a query passes only the search text: ```ts title="You write" import { f, Entity, Field } from 'uql-orm'; import { pool } from './uql.config.js'; @Entity({ indexes: (listing, index) => [ index([{ column: listing.title, weight: 3 }, listing.description], { type: 'fulltext', config: 'spanish', }), ], }) export class Listing { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) description?: string | null; @Field(f.string().nullable()) status?: string | null; @Field(f.date().nullable()) createdAt?: Date | null; } const found = await pool.findMany(Listing, { $where: { status: 'active', $text: { $value: 'wireless keyboard' } }, $sort: { $text: 'desc', createdAt: 'desc' }, $limit: 20, }); ``` `$text` sits at the top level of `$where`, beside ordinary conditions, and searches the columns of the entity’s fulltext index in the index’s language. `$sort: { $text: 'desc' }` ranks by the same search, so this returns the most relevant listings first, and the newest among equals. A title match outranks the same word in the description, because the title has weight 3. To search other columns, pass `$fields`, keyed like `$select` so a typo does not compile. `$config` picks the language for this search. On SQL, an entity with no fulltext index, or more than one, must pass `$fields`. ```ts await pool.findMany(Item, { $where: { $text: { $fields: { name: true }, $value: 'running shoes', $config: 'english', }, }, }); ``` ## Ranking by relevance The sort uses each engine’s own score: `TS_RANK` on PostgreSQL and CockroachDB, `MATCH ... AGAINST` on MySQL and MariaDB, `BM25` on SQLite, `textScore` on MongoDB. It takes either direction, and later sort keys break ties. It needs a `$text` at the root of the same `$where`, and throws without one, since a search nested in `$or` or `$not` has no single score. To read the score, give it a name with `$project`, as a [vector search](https://uql-orm.dev/querying/semantic-search.md) does for its distance, and it is on each row as a number: ```ts const items = await pool.findMany(Item, { $where: { $text: { $value: 'wireless keyboard' } }, $sort: { $text: { $project: 'score' } }, }); // items[0].score is the highest relevance ``` The name must not clash with any field, column or relation of the entity. Pass `$order: 'asc'` to put the least relevant first. A populated relation searches and ranks its own rows the same way, `$populate: { reviews: { $where: { $text: { $value: 'quiet' } }, $sort: { $text: { $project: 'score' } } } }`. MongoDB throws there, since its `$text` runs only on the queried collection. ### Column weights A column without a `weight` has weight 1, and a match counts its column’s weight, as MongoDB’s `textScore` does. Weights are whole numbers from 1 to 99999. They only change the ranking, never which rows match. PostgreSQL and CockroachDB add each heavier column’s own `TS_RANK` to the score. MySQL and MariaDB add each heavier column’s own `MATCH`, which needs a `FULLTEXT` index over that column alone, so migrations create one per column heavier than the lightest. MongoDB stores the weights in its text index, and `drift:check` compares them. > **MySQL and MariaDB rebuild the table** > > InnoDB fills a fulltext index added to a table that already has one, and has rows, only once the table is optimized. Until then MariaDB scores it 0 and MySQL can fail the search. So a migration adding such an index follows it with `OPTIMIZE TABLE`, which rebuilds the table. ## Language The index’s `config` and a search’s `$config` set the language for stemming and stop words: `'english'`, `'spanish'`, or `'simple'` for none, which is the default on every engine. PostgreSQL and CockroachDB use it as the text-search configuration for both the index and the query. MongoDB uses the same names for `default_language` and `$language`, mapping `'simple'` to `'none'`, and `drift:check` reports an index built in another language. MySQL, MariaDB and SQLite ignore it and parse by their index. ## What each engine runs [Migrations](https://uql-orm.dev/migrations.md) create the index from the same declaration on every engine that has one. | Engine | Index | Query | | - | - | - | | PostgreSQL / CockroachDB | `GIN` over `TO_TSVECTOR(config, cols)` | `@@ WEBSEARCH_TO_TSQUERY($1)`; `PLAINTO_TSQUERY` on CockroachDB, which lacks the first | | MySQL / MariaDB | `FULLTEXT (cols)`, over exactly the columns searched, in order | `MATCH(cols) AGAINST(?)` | | MongoDB | a `text` index, which declares its own fields, so `$fields` is ignored | `{ $text: { $search } }` | | SQLite | none: you create an [FTS5](https://sqlite.org/fts5.html) virtual table yourself | `table MATCH ?`, each word quoted | | SQL Server | refused: it needs a [full-text catalog](https://uql-orm.dev/mssql.md) UQL does not create | refused | On PostgreSQL, `$text` reads input the way a search box does (quoted phrases, `or`, `-negation`) and never raises a syntax error. It also works without an index by scanning the table, so declare one for anything large. On MySQL and MariaDB, a search whose columns do not exactly match a `FULLTEXT` index fails with “Can’t find FULLTEXT index matching the column list”. > **Combining with semantic search** > > Full-text search finds matching terms; [vector search](https://uql-orm.dev/querying/semantic-search.md) finds similar meaning. Hybrid search runs both and fuses the rankings: MongoDB has `$rankFusion`, and on PostgreSQL you write a reciprocal-rank-fusion query over a `tsvector` match and a pgvector distance. ## Next steps - [Indexes](https://uql-orm.dev/entities/indexes.md): declaring `fulltext` indexes and their per-column options. - [Semantic Search](https://uql-orm.dev/querying/semantic-search.md): vector similarity when keywords are not enough. # Semantic Search > Reference for vector search with $vector, $near and $candidates: entity setup, operators, metrics, indexes and recall per engine. Source: https://uql-orm.dev/querying/semantic-search Semantic search finds rows by meaning: each row stores an embedding, and you sort or filter by its distance to a query embedding. This page is the reference. For a guided RAG example, see [AI & RAG](https://uql-orm.dev/ai-semantic-search.md). It runs on PostgreSQL and PGlite (pgvector), CockroachDB, MariaDB 11.7+, SQLite (sqlite-vec), libSQL, Turso, SQL Server 2025 and MongoDB Atlas. MySQL and Cloudflare D1 have no vector functions, so a vector query throws there; MySQL stores the field as `JSON` and D1 as text. On Cloudflare, use [Vectorize](https://developers.cloudflare.com/vectorize/). ## Entity setup A vector field is `f.vector(dimensions)`. A [vector index](#vector-indexes) makes search approximate and fast instead of exact and slow: ```ts title="You write" import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (article, index) => [ index([article.embedding], { type: 'hnsw', distance: 'cosine', m: 16, efConstruction: 64, }), ], }) export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) category?: string | null; @Field(f.vector(1536).nullable()) embedding?: number[] | null; } ``` Plain SQLite needs the [sqlite-vec](https://github.com/asg017/sqlite-vec) extension loaded through the pool: ```ts import { getLoadablePath } from 'sqlite-vec'; import { SqliteQuerierPool } from 'uql-orm/sqlite'; const pool = new SqliteQuerierPool('app.db', { extensions: [getLoadablePath()], }); ``` Other engine requirements are in [engine notes](#engine-notes). ## Query by similarity Sort by the field with `$vector`, optionally choosing a [metric](#distance-metrics) with `$distance`: ```ts title="You write" const results = await pool.findMany(Article, { $select: { id: true, title: true }, $sort: { embedding: { $vector: queryVec, $distance: 'cosine' } }, $limit: 10, }); ``` PostgreSQL: ```sql SELECT "id", "title" FROM "Article" ORDER BY "embedding" <=> $1::vector LIMIT 10 ``` MariaDB: ```sql SELECT `id`, `title` FROM `Article` ORDER BY VEC_DISTANCE_COSINE(`embedding`, ?) LIMIT 10 ``` SQLite: ```sql SELECT `id`, `title` FROM `Article` ORDER BY vec_distance_cosine(`embedding`, ?) LIMIT 10 ``` libSQL / Turso Cloud: ```sql SELECT `id`, `title` FROM `Article` WHERE `Article`.rowid IN (SELECT id FROM vector_top_k(?, ?, ?)) ORDER BY vector_distance_cos(`embedding`, ?) LIMIT 10 ``` SQL Server: ```sql SELECT "id", "title" FROM "Article" ORDER BY VECTOR_DISTANCE('cosine', "embedding", CAST(@p1 AS VECTOR(1536))) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` MongoDB Atlas: ```json [ { "$vectorSearch": { "index": "embedding_index", "path": "embedding", "queryVector": [/* queryVec */], "numCandidates": 100, "limit": 10 } } ] ``` ### Combined with filtering `$where` and other `$sort` keys work as usual. The other keys rank after the distance: ```ts await pool.findMany(Article, { $where: { category: 'science' }, $sort: { embedding: { $vector: queryVec }, title: 'asc' }, $limit: 10, }); ``` On MongoDB Atlas, `$where` becomes the `$vectorSearch` filter, so its fields must be in the Atlas index. ## Distance predicate `$near` in `$where` keeps only rows within a distance. Use it when a distant match is worse than none: RAG context, deduplication, match thresholds. It needs at least one of `$lt`, `$lte`, `$gt`, `$gte` or `$between`. There is no `$eq`, since exact equality on a float distance is a bug. ```ts title="You write" const results = await pool.findMany(Article, { $where: { embedding: { $near: { $vector: queryVec, $lt: 0.35 } } }, $limit: 10, }); ``` PostgreSQL: ```sql SELECT "id", "title", "category", "embedding" FROM "Article" WHERE "embedding" <=> $1::vector < $2 LIMIT 10 ``` MariaDB: ```sql SELECT `id`, `title`, `category`, CONCAT('\\x', HEX(`embedding`)) `embedding` FROM `Article` WHERE VEC_DISTANCE_COSINE(`embedding`, ?) < ? LIMIT 10 ``` SQLite: ```sql SELECT `id`, `title`, `category`, `embedding` FROM `Article` WHERE vec_distance_cosine(`embedding`, ?) < ? LIMIT 10 ``` SQL Server: ```sql SELECT "id", "title", "category", "embedding" FROM "Article" WHERE VECTOR_DISTANCE('cosine', "embedding", CAST(@p1 AS VECTOR(1536))) < @p2 ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` `$near` carries its own vector, so it works with any sort, or none, and in `exists`: ```ts const isDuplicate = await pool.exists(Article, { $where: { embedding: { $near: { $vector: queryVec, $lt: 0.05 } } }, }); ``` > **Not on MongoDB Atlas** > > Atlas cannot filter by distance, so `$near` throws there. [Project the distance](#distance-projection) and filter it in your app. ### Filter and rank together Pass the same vector to `$near` and `$sort` to keep close rows and rank them: ```ts const results = await pool.findMany(Article, { $where: { embedding: { $near: { $vector: queryVec, $lt: 0.35 } } }, $sort: { embedding: { $vector: queryVec, $project: 'score' } }, $limit: 30, }); ``` On an HNSW index, add [`$candidates`](#tuning-recall) too, or you may get fewer rows than qualify. ## Distance projection `$project` names a field that returns the distance, as in `$sort: { embedding: { $vector: queryVec, $project: 'distance' } }`. Each row has it as a `number`, beside what `$select` picked. The SQL sorts by the projected alias, so the distance is computed once. On MongoDB Atlas it is computed by the index’s metric over the documents Atlas found, so it reads the same as on the SQL engines. A populated relation’s `$sort` projects the same way, onto each of its rows: ```ts const guide = await pool.findOneById(Guide, id, { $populate: { passages: { $sort: { embedding: { $vector: queryVec, $project: 'distance' } }, $limit: 3, }, }, }); guide?.passages[0].distance; ``` Inside a relation the search is exact, with no vector index. MongoDB computes it over the relation’s documents, since Atlas cannot search inside a lookup. ## Distance metrics `cosine` suits text embeddings, `l2` images and spatial data, `inner` is maximum inner product, and `l1` is Manhattan distance. | Engine | `cosine` | `l2` | `inner` | `l1` | | - | - | - | - | - | | Postgres | `<=>` | `<->` | `<#>` | `<+>` | | CockroachDB | `<=>` | `<->` | `<#>` | no | | MariaDB | `VEC_DISTANCE_COSINE` | `VEC_DISTANCE_EUCLIDEAN` | no | no | | SQLite (sqlite-vec) | `vec_distance_cosine` | `vec_distance_L2` | no | `vec_distance_L1` | | libSQL | `vector_distance_cos` | `vector_distance_l2` | no | no | | Turso (local) | `vector_distance_cos` | `vector_distance_l2` | `vector_distance_dot` | no | | MSSQL | `VECTOR_DISTANCE('cosine')` | `VECTOR_DISTANCE('euclidean')` | `VECTOR_DISTANCE('dot')` | no | | MongoDB Atlas | set by the index | set by the index | set by the index | no | An unsupported metric throws when the query is built. `uql-orm/turso` refuses `inner`, since a Turso Cloud database may run libSQL. A field can set its default metric with `@Field(f.vector(1536).distance('l2'))`. A `$distance` overrides it; with neither, the field uses its index’s metric, or `cosine`. ## Ranking by a related row A `$vector` under a relation ranks each row by its closest related row, such as a guide by its best passage: ```ts const guides = await pool.findMany(Guide, { $where: { title: { $istartsWith: 'indexing' } }, $sort: { passages: { embedding: { $vector: queryVec } } }, $limit: 10, }); ``` PostgreSQL: ```sql SELECT "id", "title" FROM "Guide" WHERE "title" ILIKE $1 ESCAPE '\' ORDER BY (SELECT MIN("passages"."embedding" <=> $2::vector) FROM "Passage" "passages" WHERE "passages"."guideId" = "Guide"."id") LIMIT 10 ``` MariaDB: ```sql SELECT `id`, `title` FROM `Guide` WHERE LOWER(`title`) LIKE ? ESCAPE '\\' ORDER BY (SELECT MIN(VEC_DISTANCE_COSINE(`passages`.`embedding`, ?)) FROM `Passage` `passages` WHERE `passages`.`guideId` = `Guide`.`id`) LIMIT 10 ``` SQLite: ```sql SELECT `id`, `title` FROM `Guide` WHERE `title` LIKE ? ESCAPE '\' ORDER BY (SELECT MIN(vec_distance_cosine(`passages`.`embedding`, ?)) FROM `Passage` `passages` WHERE `passages`.`guideId` = `Guide`.`id`) LIMIT 10 ``` SQL Server: ```sql SELECT "id", "title" FROM "Guide" WHERE LOWER("title") LIKE @p1 ESCAPE N'\' ORDER BY (SELECT MIN(VECTOR_DISTANCE('cosine', "passages"."embedding", CAST(@p2 AS VECTOR(1536)))) FROM "Passage" "passages" WHERE "passages"."guideId" = "Guide"."id") OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` It works on any relation kind without `$populate`, ranks ahead of other `$sort` keys, and takes `$distance` but not `$project`. A row with no related rows sorts where the engine puts nulls. It skips the vector index, so narrow the rows with `$where`. MongoDB computes it exactly over direct relations, with no Atlas needed. ## Vector types | Type | Postgres type | Storage | Max dimensions | Use for | | - | - | - | - | - | | `f.vector(n)` | `VECTOR(n)` | 32-bit float | 2,000 | Standard embeddings | | `f.column('halfvec').dimensions(n)` | `HALFVEC(n)` | 16-bit float | 4,000 | Half the storage | | `f.column('sparsevec').dimensions(n)` | `SPARSEVEC(n)` | Sparse | 1,000,000 | SPLADE and sparse models | Other engines store all three as their own vector type. You always pass a dense `number[]`, `sparsevec` included. ## Vector indexes Declare them in [`indexes`](https://uql-orm.dev/entities/indexes.md): | `type` | Engines | Options | | - | - | - | | `hnsw` | Postgres, CockroachDB, libSQL, Turso Cloud | `m`, `efConstruction` | | `ivfflat` | Postgres (not with `sparsevec` or `l1`), libSQL, Turso Cloud | `lists` | | `vector` | CockroachDB, MariaDB, libSQL, Turso Cloud | `m` on MariaDB | | `vectorSearch` | MongoDB Atlas | `name` | ```ts @Entity({ indexes: (article, index) => [ index([article.embedding], { type: 'ivfflat', distance: 'l2', lists: 100 }), ], }) export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.vector(1536).nullable()) embedding?: number[] | null; } ``` MySQL and MSSQL refuse all of these in migrations. Plain SQLite, embedded Turso and D1 build a plain index instead, so a Postgres entity still migrates and search is exact. ## Tuning recall An approximate index can miss a closer row. `$candidates` widens the search for one query: ```ts title="You write" const results = await pool.findMany(Article, { $sort: { embedding: { $vector: queryVec } }, $limit: 10, $candidates: 200, }); ``` | Engine | Index | Becomes | Default | | - | - | - | - | | PostgreSQL | `hnsw` | `SET LOCAL hnsw.ef_search` | 40 | | PostgreSQL | `ivfflat` | `SET LOCAL ivfflat.probes` | 1 | | CockroachDB | `hnsw`/`vector` | `SET LOCAL vector_search_beam_size` | 32 | | MariaDB | `vector` | `SET STATEMENT mhnsw_ef_search=N FOR ...` | 20 | | libSQL / Turso Cloud | any | `k` of `vector_top_k` | the page | | MongoDB Atlas | `vectorSearch` | `numCandidates` | 10x `$limit` | It is ignored where search is exact, and applies to the whole statement, not a populated relation. On Postgres and CockroachDB, `SET LOCAL` applies only inside a transaction, so a tuned read outside one opens its own around the setting and the query: one request on Neon, a `BEGIN` and `COMMIT` more elsewhere. A tuned `findManyStream` is refused outside a transaction, which would stay open for the whole loop; run it inside `pool.transaction(...)`. ### Thresholds need it most On HNSW, `$near` filters only the candidates the index returns, so a threshold can return fewer rows than qualify. [Filter and rank together](#filter-and-rank-together) and add `$candidates`: on Postgres, UQL then also sets `hnsw.iterative_scan = strict_order`, so the index keeps scanning in distance order until the limit is filled. ## Engine notes - Postgres: migrations create the `vector` extension. PGlite loads it through its pool, `new PgliteQuerierPool(dataDir, { extensions: { vector } })`, with `vector` from `@electric-sql/pglite-pgvector`. - CockroachDB: `hnsw` maps to its native index, with `efConstruction` as `build_beam_size`; `m` is ignored and `ivfflat` refused. - MariaDB: the dimensions are required, and an indexed vector column is created `NOT NULL`. - libSQL and Turso Cloud: any index type builds `libsql_vector_idx` (DiskANN) on one column, for `cosine` or `l2`, with `m` as `max_neighbors` and `efConstruction` as `insert_l`. Index names allow only letters, digits and underscores. Vectors are `F32_BLOB(n)`, as on SQLite. - SQL Server: the dimensions are required and search is always exact. A query with no sort gets `ORDER BY (SELECT NULL)` to page. - MongoDB: migrations create the Atlas index (default name `_index`); extra fields in it can be pre-filtered with `$where`. Atlas builds it after the migration returns. The index sets the metric: its own `distance`, else the field’s, and a `$distance` naming another throws. To mix vector and keyword search, see [Full-text search](https://uql-orm.dev/querying/full-text.md). # Transactions > Run several writes all-or-nothing, nest them as savepoints, and pick an isolation level. Source: https://uql-orm.dev/querying/transactions A transaction runs a group of statements all-or-nothing. Pass a callback to `pool.transaction()`: UQL takes a connection, commits when the callback returns, rolls back when it throws, and releases the connection either way. ```ts import { Profile, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; const userId = await pool.transaction(async (querier) => { const id = await querier.insertOne(User, { name: 'Alice' }); await querier.insertOne(Profile, { userId: id, bio: '...' }); return id; }); ``` A pool call made inside the callback joins the transaction. `pool.insertOne(...)`, or a helper written against the pool or a [`UniversalQuerier`](https://uql-orm.dev/querying/querier.md#accept-a-universalquerier), runs on the callback’s querier, sees its uncommitted writes and rolls back with them. Helpers need no changes to take part: the caller decides what is atomic. To undo writes, throw. To give up before writing anything, return early: nothing is committed and any row locks are released. ## On a querier you already hold `querier.transaction()` makes part of a querier’s work atomic. It commits or rolls back, and releasing the connection stays with whoever acquired it: ```ts const userId = await pool.withQuerier(async (querier) => { if (await querier.count(User, { $where: { email } })) { return undefined; } return querier.transaction(async () => { const id = await querier.insertOne(User, { name: 'Alice' }); await querier.insertOne(Profile, { userId: id, bio: '...' }); return id; }); }); ``` If you acquire the querier yourself, `await using` releases it however the block exits, so an early return or a throw cannot leak the connection. Node 24+ and Bun run it natively, and TypeScript lowers it for an older target. A `try` / `finally` calling `querier.release()` does the same. ```ts await using querier = await pool.getQuerier(); await querier.transaction(async () => { /* ... */ }); ``` Releasing a querier with a transaction still open rolls it back and logs a warning. A connection whose rollback fails is discarded rather than reused. Releasing inside a `transaction()` callback makes that call reject, since nothing is left to commit. A released querier cannot be used again. ## Nesting A `transaction()` inside another runs as a savepoint. If it throws, only its own writes roll back, and the outermost call still owns the commit. A helper that is atomic on its own is therefore safe to call from a larger transaction: ```ts await pool.transaction(async (querier) => { await querier.insertOne(Order, order); await querier .transaction(() => querier.insertOne(Coupon, coupon)) .catch(() => undefined); // the coupon rolled back; the order still commits }); ``` An inner failure you do not catch reaches the outer callback and rolls back everything. > **MongoDB** > > MongoDB has no savepoints, so it refuses a `transaction()` inside another. Call the inner work directly as part of the outer transaction. ## After the commit: `onCommit` Some side effects cannot be rolled back, such as sending an email or queueing a job. `querier.onCommit(fn)` runs `fn` once the outermost transaction commits: ```ts await pool.transaction(async (querier) => { await querier.insertOne(User, user); await querier.onCommit(() => mailer.welcome(user.email)); }); ``` If the transaction rolls back, `fn` never runs, and a savepoint that rolls back drops the callbacks registered inside it. Outside a transaction, `fn` runs at once. If `fn` throws, the `transaction` call rejects, but the writes are already committed. [Lifecycle hooks](https://uql-orm.dev/entities/lifecycle-hooks.md) get `onCommit` in their context. ## Manual begin, commit and rollback When a transaction cannot be one callback, drive it yourself. A test that rolls back everything its body wrote is the usual case: ```ts import type { Querier } from 'uql-orm'; let querier: Querier; beforeEach(async () => { querier = await pool.getQuerier(); await querier.beginTransaction(); }); afterEach(async () => { await querier.rollbackTransaction(); await querier.release(); }); ``` `beginTransaction()` throws `pending transaction` if one is already open on that querier. `rollbackTransaction()` does nothing when none is open, so it is safe in a `catch` or `finally`. `commitTransaction()` throws when none is open, so you never mistake uncommitted work for committed. Pool calls do not join a transaction opened this way, so run its statements on the querier. ## Concurrency A transaction holds its connection until it ends. A statement from outside the callback waits for it instead of landing in it, whether it comes from another request sharing the querier or, on SQLite, PGlite, libSQL and embedded Turso, from another querier on the one shared connection. Transactions on one querier run one after another. ## Isolation levels Every form takes an `isolationLevel`: `read uncommitted`, `read committed` (the default on most databases), `repeatable read` or `serializable`. ```ts await pool.transaction( async (querier) => { /* ... */ }, { isolationLevel: 'serializable' }, ); ``` PostgreSQL, MySQL, MariaDB and SQL Server take all four, and so does Bun SQL on PostgreSQL, MySQL and MariaDB. CockroachDB takes the option too, and runs a level it lacks at a stricter one. SQLite, libSQL, Turso and MongoDB ignore it; SQLite is already serializable. Cloudflare D1 has no transactions at all, so `transaction()` and `beginTransaction()` throw there: write the change as one statement, or make it idempotent. At stricter levels, conflicting transactions fail with a serialization error or a deadlock instead of waiting. [`queryErrorKind`](https://uql-orm.dev/querying/errors.md#retrying-a-transaction) names both `retryable` on every engine, so you can run the whole transaction again. Set the level on every transaction that needs it. On MySQL and MariaDB it is sent as its own statement before `START TRANSACTION`, so if `START TRANSACTION` fails, the level carries over to the next transaction on that pooled connection. For a read-modify-write at the default level, lock the rows you read with `$lock`, or one update can be lost. See [Row Locking](https://uql-orm.dev/querying/locking.md). ## Read-only transactions `{ readOnly: true }` opens a transaction that only reads, alone or beside an `isolationLevel`: ```ts const users = await pool.transaction( (querier) => querier.findMany(User, { $select: { id: true } }), { readOnly: true }, ); ``` PostgreSQL, CockroachDB, MySQL, MariaDB and libSQL refuse a write inside it. libSQL and Turso open every other transaction with the write lock taken, so a read-only one is what lets a long read run beside the writers. SQLite, SQL Server and MongoDB have no such mode and run it as any other. ## Next steps - [Pool vs. Querier](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx): which entry point a unit of work needs. - [Error Handling](https://uql-orm.dev/querying/errors.md): retrying a transaction that failed on a conflict. - [Row Locking](https://uql-orm.dev/querying/locking.md): locking rows inside a transaction. # Error Handling > Tell a duplicate, a missing parent or a deadlock apart with one function, on every engine. Source: https://uql-orm.dev/querying/errors A failed query throws the driver’s own error, and each engine names the same failure differently. A duplicate key is `23505` on PostgreSQL, `1062` on MySQL, `2627` on SQL Server, `11000` on MongoDB, and only a message on SQLite. `queryErrorKind(err)` reads whichever one the error carries and gives it one name: ```ts import { queryErrorKind, UqlRequestError } from 'uql-orm'; import { User } from './shared/models/index.js'; import { pool } from './uql.config.js'; export async function signUp(email: string, password: string) { try { return await pool.insertOne(User, { email, password }); } catch (err) { if (queryErrorKind(err) === 'uniqueViolation') { throw new UqlRequestError('That email is taken', 409, { cause: err }); } throw err; } } ``` It works on any driver error, whether or not a querier threw it. It only reads the error, so `instanceof` and the driver’s own `code` still work. ## Kinds | Kind | What happened | | - | - | | `uniqueViolation` | A primary key or unique index already holds the value. | | `foreignKeyViolation` | The referenced row is missing, or a row still referenced was deleted. | | `notNullViolation` | A required column got no value. | | `checkViolation` | A check constraint, or MongoDB schema validation, rejected the row. | | `retryable` | A deadlock, serialization failure, lock timeout or busy database: run it again. | | `optimisticLock` | An update carried a version the row has moved past, or the row is gone. | | `usage` | The call itself is wrong, such as a `$lock` outside a transaction. | | `security` | A `security` filter refused: its context is missing, or a write would leave its scope. | | `undefined` | Anything else: a syntax error, a lost connection, an error from outside the database. | `optimisticLock`, `usage` and `security` come from UQL itself, as a `UqlOptimisticLockError`, `UqlUsageError` or `UqlSecurityError`. Each extends `UqlError` and carries `kind` and an HTTP `status` (`409`, `400` and `403`). An API call naming what a member’s `wire` refuses is a `UqlSecurityError`: `'password' cannot be read through this API`. A request the [API](https://uql-orm.dev/http.md) refuses before any call runs is a `UqlRequestError` of kind `usage`: a `404` for an entity or op it does not serve, a `405` for a method the op does not take, a `415` for a body that is not JSON. A refusal names the value at fault in `path`, a querier’s within its query (`['$limit']`), which the API answers within the call (`['query', '$limit']`). Check them by kind; reach for `instanceof UqlOptimisticLockError` only to read its `expected` and `actual` version. ## Retrying a transaction By the time a `retryable` error leaves `transaction()`, the transaction has rolled back, so the whole callback can run again. Retry the transaction, never one statement inside it: ```ts import { queryErrorKind } from 'uql-orm'; import { Item } from './shared/models/index.js'; import { pool } from './uql.config.js'; async function withRetry(work: () => Promise, attempts = 3): Promise { for (let attempt = 1; ; attempt++) { try { return await work(); } catch (err) { if (attempt === attempts || queryErrorKind(err) !== 'retryable') { throw err; } } } } export function takeOne(id: number) { return withRetry(() => pool.transaction( async (querier) => { const item = await querier.findOneById(Item, id, { $select: { stock: true }, }); await querier.updateOneById(Item, id, { stock: item!.stock! - 1 }); }, { isolationLevel: 'serializable' }, ), ); } ``` ## Over the API The [API](https://uql-orm.dev/http.md) answers a `UqlError` with its own status and message: UQL’s, and the `UqlRequestError` a middleware or a lifecycle hook throws to refuse a client, `new UqlRequestError('unauthorized', 401)`. Any other error is answered by its kind alone, with a generic message and whatever `status` it carries ignored, since a driver’s message names your tables, PostgreSQL’s echoes the value, and an HTTP driver’s (libSQL’s) status is not the client’s: a `uniqueViolation` or `foreignKeyViolation` is `409 Conflict`, a `notNullViolation` or `checkViolation` `400 Bad Request`, a `retryable` failure `503 Service Unavailable`, and anything else `500 Internal Server Error`. The [error envelope](https://uql-orm.dev/http.md#wire-protocol) is `{ error: { message, status, kind, path } }`, which the [client](https://uql-orm.dev/browser.md#the-client) throws as a `RequestError` carrying the same fields. ## Per engine `queryErrorKind` reads the SQLSTATE on the Postgres family (`code`, or `errno` on Bun SQL), `errno` on MySQL and MariaDB, `number` on SQL Server, `code` and `errorLabels` on MongoDB, and the message on the SQLite family: | Engine | unique | foreign key | not null | check | retryable | | - | - | - | - | - | - | | PostgreSQL, CockroachDB, Neon, PGlite, Bun SQL | `23505` | `23503` | `23502` | `23514` | `40P01`, `40001`, `55P03` | | MySQL, MariaDB | `1062` | `1451`, `1452` | `1048`, `1364` | `3819`, `4025` | `1213`, `1205`, `3572` | | SQL Server | `2627`, `2601` | `547` naming a FOREIGN KEY | `515` | `547` naming a CHECK | `1205`, `1222`, `3960` | | MongoDB | `11000` | | | `121` | `112`, `TransientTransactionError` | | SQLite, LibSQL, Turso, Cloudflare D1 | `UNIQUE constraint failed` | `FOREIGN KEY constraint failed` | `NOT NULL constraint failed` | `CHECK constraint failed` | `database is locked` | ## Next steps - [Transactions](https://uql-orm.dev/querying/transactions.md): isolation levels and who owns the commit. - [Optimistic Locking](https://uql-orm.dev/entities/optimistic-locking.md): where `optimisticLock` comes from. - [HTTP](https://uql-orm.dev/http.md): the error envelope the API answers. # Row Locking > Lock rows with $lock so a read-modify-write cannot lose an update, and build a work queue with SKIP LOCKED. Source: https://uql-orm.dev/querying/locking Reading a row and writing it back are two statements, and another transaction can read the same row in between. Both then write, and the first update is lost without a word. `$lock` locks the rows a query returns until the transaction ends: ```ts await pool.transaction(async (querier) => { const item = await querier.findOneById(Item, id, { $select: { stock: true }, $lock: true, }); await querier.updateOneById(Item, id, { stock: item!.stock! - 1 }); }); ``` Without the lock, two overlapping callers both read `5` and both write `4`. With it, the second waits for the first to commit, then reads `4` and writes `3`. `$lock` needs an open transaction. Outside one, a pool call included, the lock would be released as the statement commits, so UQL throws a `UqlUsageError` instead. ## When the row is already locked By default the query waits. `$wait` picks something else: | `$lock` | A row another transaction holds | | - | - | | `true` | wait for it | | `{ $wait: 'nowait' }` | fail at once | | `{ $wait: 'skip' }` | leave it out of the result | | `false` | no lock, handy in a conditional query | A `nowait` failure rolls back the transaction unless you catch it. [`queryErrorKind`](https://uql-orm.dev/querying/errors.md) names it `retryable` on every engine, as it does a deadlock: run the transaction again. `skip` turns a table into a work queue. Each worker takes only rows nobody else holds, so no two workers get the same job: ```ts await pool.transaction(async (querier) => { const batch = await querier.findMany(Item, { $select: { id: true }, $where: { isActive: true }, $sort: { createdAt: 'asc' }, $limit: 10, $lock: { $wait: 'skip' }, }); for (const item of batch) { await querier.updateOneById(Item, item.id, { isActive: false }); } }); ``` PostgreSQL: ```sql SELECT "id" FROM "Item" WHERE "isActive" = $1 ORDER BY "createdAt" LIMIT 10 FOR UPDATE SKIP LOCKED ``` MySQL: ```sql SELECT `id` FROM `Item` WHERE `isActive` = ? ORDER BY `createdAt` LIMIT 10 FOR UPDATE SKIP LOCKED ``` MariaDB: ```sql SELECT `id` FROM `Item` WHERE `isActive` = ? ORDER BY `createdAt` LIMIT 10 FOR UPDATE SKIP LOCKED ``` SQL Server: ```sql SELECT "id" FROM "Item" WITH (UPDLOCK, ROWLOCK, READPAST) WHERE "isActive" = @p1 ORDER BY "createdAt" OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY ``` Expect fewer rows than `$limit` when other workers hold some. ## What gets locked Only rows of the queried entity. Relations loaded with `$populate` are not locked: a to-many is read in a subquery, and for a joined to-one UQL narrows the lock to the queried table (`FOR UPDATE OF "Item"`). To lock a related row, query it directly. `count`, `updateMany`, `deleteMany` and a nested `$populate` query take no `$lock`. ## Engine support | Engine | `$lock` and `$wait` | With a joined relation | | - | - | - | | PostgreSQL, CockroachDB, PGlite | ✅ | ✅ | | MySQL, MSSQL | ✅ | ✅ | | MariaDB | ✅ | ❌ rejected: without `FOR ... OF`, the lock would cover joined rows | | SQLite, libSQL, Turso, D1 | ❌ | ❌ | | MongoDB | ❌ | ❌ | SQLite locks the whole database rather than rows, and MongoDB has no row locks, so both reject `$lock` rather than ignore it. There the transaction is your concurrency control, and on MongoDB an atomic update such as `$inc` with a guard in `$where` is the usual tool. PGlite has a single connection, so its locks never block (see [PGlite](https://uql-orm.dev/pglite.md#one-connection-and-what-follows-from-it)). [`createApi`](https://uql-orm.dev/http.md) refuses `$lock` in a client’s query with a `400`, because each call commits on its own. ## Across requests A lock lasts only as long as its transaction. When a user loads a form and saves it a minute later, or on an engine without row locks, guard the write with a version column instead: see [Optimistic Locking](https://uql-orm.dev/entities/optimistic-locking.md). The two work together, since a versioned row read under `$lock` cannot change before you write it. # Cursor Pagination > Page through rows past a cursor instead of an offset, as fast on page 10,000 as on page one, on every engine. Source: https://uql-orm.dev/querying/pagination `findManyPage()` reads one page of rows past a cursor. With an offset (`$skip`) the engine reads and discards every earlier row, so page 10,000 of 50 reads 500,000 rows, and an insert shifts every later page. A cursor page costs the same at any depth, and inserts shift nothing. ```ts import { Post } from './shared/models/index.js'; import { pool } from './uql.config.js'; const query = { $select: { title: true }, $sort: { createdAt: 'desc', id: 'asc' }, $limit: 20, } as const; const first = await pool.findManyPage(Post, query); // { items, startCursor, endCursor, hasNextPage, hasPrevPage } const next = await pool.findManyPage(Post, { ...query, $after: first.endCursor, }); const back = await pool.findManyPage(Post, { ...query, $before: next.startCursor, }); ``` It takes the same query as `findMany` and types the items the same way, with these differences: - `$limit` is the page size, a positive whole number. - `$after` or `$before` names the cursor, never both. - `$skip` and `$distinct` are refused. A query breaking these rules, or the [sort rule](#the-sort-must-be-total), throws a `UqlUsageError` whose `path` names the clause at fault (`['$limit']`). The flag in the reading direction is exact; the other only says whether the page was read past a cursor (`hasPrevPage` after `$after`, `hasNextPage` after `$before`). Nothing is counted: call [`count`](https://uql-orm.dev/querying/counting.md) with the same `$where` for a total. ## The sort must be total Two rows that tie on every sort value can be skipped or read twice, so `$sort` must include something unique: the primary key, a `.unique()` field not declared `.nullable()`, or every column of a unique, non-partial index over such fields. `{ createdAt: 'desc' }` alone throws and names the fix; `{ createdAt: 'desc', id: 'asc' }` works. Directions can be mixed. Only the entity’s own fields can be sort keys. A relation’s field, a JSON path, a relevance, a vector distance, an aggregate, and a JSON, vector or binary column are refused. So is a raw `$select`, since the cursor is read off the selected fields. ## Page or stream? | | `findManyPage` | [`findManyStream`](https://uql-orm.dev/querying/streaming.md) | | - | - | - | | Reads | one page per call, one statement each | every row, from one statement | | Between reads | holds nothing: the cursor is a string you keep | holds a connection for the whole loop | | Consistency | per page; a row whose sort value changes may repeat or be missed | one snapshot of the whole result | | Query | a total sort, on the entity’s own fields | any query | | Resumes | yes, from any cursor, in another request | no | | Over HTTP | yes (`findManyPage`) | no | Both run `@AfterLoad` on each row. Page what a person scrolls or an API client requests; stream what one process reads once, such as an export. On libSQL, D1, and Bun SQL on MySQL or MariaDB a stream buffers the whole result, so page there when it does not fit in memory. ## Nullable sort keys A nullable sort key pages correctly wherever the engine or a [placement](https://uql-orm.dev/querying/sorting.md#where-nulls-land) puts its nulls, but it loses the index: a deep page reads as much as an offset would. On Postgres with 200,000 rows, a mid-table page took 15.4 ms with a nullable leading key and 0.05 ms with the same key NOT NULL. Leave `.nullable()` off sort keys that never hold null, the leading one above all. On MySQL, MariaDB and SQL Server, also leave out the placement, since it is an expression no index serves. ## The cursor A cursor is an opaque string holding the page’s sort values exactly, `Date` and `bigint` included, plus a fingerprint of the sort: passed to a query sorted another way, it throws. A cursor holds a timestamp to the millisecond, as a `Date` does, so a field declared with a higher `precision` cannot be a key. A cursor survives inserts and deletes, but a row whose sort value changes between two pages can appear twice or not at all. > **Cursors are encoded, not signed** > > Anyone holding a cursor can decode its sort values, so a client sorting by a field reads that field’s values from the cursor. An [API](https://uql-orm.dev/http.md#what-a-client-may-do) refuses a `$sort` on a field it may not read, so hide that field with `.wire(false)`. ## Over HTTP The [API](https://uql-orm.dev/http.md) serves pages as `findManyPage` (`GET /api/v1/post/findManyPage`), and the [client](https://uql-orm.dev/browser.md) returns the page as the pool does: ```ts import { createClientQuerier, httpTransport } from 'uql-orm/browser'; const querier = createClientQuerier(httpTransport('/api/v1')); const query = { $sort: { id: 'asc' }, $limit: 20 } as const; const first = await querier.findManyPage(Post, query); const next = await querier.findManyPage(Post, { ...query, $after: first.endCursor, }); ``` # Cursor Streaming > Process millions of rows in flat memory with findManyStream and the driver's own cursor. Source: https://uql-orm.dev/querying/streaming `findManyStream()` reads a result too large to hold in memory. It takes the same query as `findMany` and returns an `AsyncIterable` that yields each row as the database sends it: ```ts import { User } from './shared/models/index.js'; import { pool } from './uql.config.js'; for await (const user of pool.findManyStream(User, { $select: { id: true, email: true }, $where: { status: 'active' }, })) { console.log(user.email); } ``` Memory stays flat, your loop starts on the first row before the database has read the last, and rows arrive only as fast as the loop reads them. Populated relations and `$count` work, and `@AfterLoad` runs on each row before your loop sees it. > **The stream holds a connection** > > On the pool, `findManyStream` keeps its connection for the whole loop and releases it when the loop ends or a `break` or `throw` closes the iterator. An iterator you abandon without closing leaks the connection, so always consume it in a `for await`, and keep the loop body fast. ## One statement at a time on the querier While a stream is open on a querier, any other statement on that querier throws a `UqlUsageError`. Most drivers would queue it behind the open read, which never finishes while your loop waits on it. Run the other statement after the loop, or on another connection, as a pool call does: ```ts for await (const user of pool.findManyStream(User, { $where: { status: 'active' }, })) { await pool.updateOneById(User, user.id, { status: 'notified' }); // a second connection } ``` That fails in two cases: on SQLite and PGlite, whose one connection the stream holds, and inside a transaction, where the pool call joins the transaction and so runs on the streaming querier. There, collect what the loop decides and write it afterwards. A hook that queries through its `querier`, such as an `@AfterLoad`, is refused the same way while the stream is open. `release()` closes a stream left open. The statement is [logged](https://uql-orm.dev/logging.md) when the loop ends, with its duration measured to the first row, since the time after that is your loop’s. ## How each driver streams | Driver | How | | - | - | | PostgreSQL (`pg`), CockroachDB, Neon | Client cursor via `pg-query-stream` | | Bun SQL on Postgres or CockroachDB, PGlite | Server-side cursor: `DECLARE` / `FETCH FORWARD` / `CLOSE` | | MySQL (`mysql2`) | `.stream()` | | MariaDB (`mariadb`) | `queryStream()` | | MSSQL (`mssql`) | The driver’s stream, paused while the loop is behind | | SQLite (`better-sqlite3`, `node:sqlite`, `bun:sqlite`) | `.iterate()` | | MongoDB | Native `Cursor` | | Turso Cloud (`@tursodatabase/serverless`) | The statement’s cursor, as the server steps it | | Bun SQL on MySQL or MariaDB, LibSQL, D1 | Buffered: the whole result, then yielded row by row | Neither `bun:sql` ([oven-sh/bun#17181](https://github.com/oven-sh/bun/issues/17181)) nor PGlite’s client exposes a cursor, so UQL declares one in SQL and fetches 100 rows at a time. `DECLARE` needs a transaction: with none open, the stream opens one and ends it with the loop; inside yours, it leaves your transaction alone. The buffered drivers expose no cursor, so the whole result sits in memory before the first row arrives. To walk a large result there, use [`findManyPage`](https://uql-orm.dev/querying/pagination.md#page-or-stream), which reads one page at a time. ## Next steps - [Pagination](https://uql-orm.dev/querying/pagination.md): reading a large result a page at a time. - [Transactions](https://uql-orm.dev/querying/transactions.md): how a stream interacts with an open transaction. - [Aggregate Queries](https://uql-orm.dev/querying/aggregate.md): let the database reduce the rows instead. # Query Filters > Named $where fragments applied to every query of an entity, for soft-delete, multi-tenancy and row-level security. Source: https://uql-orm.dev/querying/filters A filter is a named `$where` fragment attached to an entity and applied to every query on it unless bypassed. [Soft-delete](https://uql-orm.dev/entities/soft-delete.md) is a built-in one; define your own for visibility flags, tenants and the like. ## Defining a filter Declare one in `@Entity({ filters })`, or in [`defineEntity`](https://uql-orm.dev/entities/define-entity.md)’s `.filters()` section: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ filters: { active: { where: { status: 'active' }, default: false } }, }) export class Task { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; } ``` ```ts import { defineEntity, f } from 'uql-orm'; export const Task = defineEntity({ name: 'Task', fields: { id: f.number().autoIncrement(), status: f.string().nullable() }, }).filters({ active: { where: { status: 'active' }, default: false } }); ``` A filter reads through relations as a `$where` does, at any depth, each key typed. `defineEntity` declares one after `.relations()`, where its row is complete: ```ts export const Project = defineEntity({ name: 'Project', fields: { id: f.number().autoIncrement(), archived: f.boolean() }, }); export const Task = defineEntity({ name: 'Task', fields: { id: f.number().autoIncrement(), status: f.string().nullable(), projectId: f.number(), }, }) .relations((rel) => ({ project: () => rel.manyToOne(Project, { references: (task) => task.projectId }), })) .filters({ live: { where: { project: { archived: false } } } }); ``` `where` is a `$where` fragment, or a function of the [context](#parameterized-filters--context) that returns one. `default` (`true` unless set) says whether the filter applies without being asked for; set it `false` for an opt-in filter like `active`. When a `where` function returns `undefined`, `onMissing` decides: `'skip'` (the default) leaves the filter out, and `'throw'` fails the query. A filter that is not a [security filter](#security-filters-row-level-security) yields to your query: if your `$where` names the same field, your condition wins. ## Bypassing filters Every read, update and delete takes `filters` in its options: ```ts pool.findMany(Task, {}, { filters: false }); // disable all filters pool.findMany(Task, {}, { filters: { softDelete: false } }); // disable one pool.findMany(Task, {}, { filters: { active: true } }); // enable an opt-in filter ``` ## Parameterized filters & context A `where` function receives the current context, such as the tenant. Declare its keys once, so `ctx.tenantId` is typed rather than `unknown`; keep them optional, since a background job may know only some: ```ts declare module 'uql-orm' { interface UqlContext { tenantId?: number; userId?: number; } } ``` Set it for a block of code with `withContext`, and read it anywhere with `getContext()`: ```ts import { f, withContext } from 'uql-orm'; @Entity({ filters: { tenant: { // undefined makes the query throw UqlSecurityError instead of running unscoped where: (ctx) => ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined, security: true, }, }, }) export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) companyId?: number | null; } await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {})); // ... WHERE (companyId = 42) ``` The context follows `await`, `Promise.all` and transactions, but not event callbacks such as emitters, timers and queues; see [event-driven pipelines](https://uql-orm.dev/multi-tenancy.md#event-driven-pipelines-emitters-timers-queues). ## Security filters (row-level security) A filter with `security: true` enforces isolation: - It always applies, ignoring `filters: false` and a bypass by name. - It is AND-merged, so a `$where` on the same field cannot widen it. - It fails closed: when its `where` returns `undefined`, as with no context the query throws `UqlSecurityError`. A call over [HTTP](https://uql-orm.dev/http.md) carries no `filters` and no context, so a client can neither bypass a filter nor set its own tenant. ### Per statement: read all, write only your own A security filter holds every statement unless `ops` names the ones it holds: `'read'`, `'insert'`, `'update'` and `'delete'`. Here anyone in a tenant reads every post, and only its author writes one, with `tenantId` and `userId` typed by the `UqlContext` [declared above](#parameterized-filters--context): ```ts @Entity({ filters: { tenant: { where: (ctx) => ctx?.tenantId != null ? { tenantId: ctx.tenantId } : undefined, security: true, }, author: { where: (ctx) => ctx?.userId != null ? { authorId: ctx.userId } : undefined, security: true, ops: ['insert', 'update', 'delete'], }, }, }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.number()) tenantId?: number; @Field(f.number()) authorId?: number; @Field(f.string()) title?: string; } ``` - A read is scoped by the filters holding `read`: `tenant` here. - An update or a delete reads the rows it changes, so it is scoped by its own filters and the read ones, as Postgres RLS scopes it: another author’s post matches no row, and the write reports `0`. - An insert, and what an update writes, are held to the filters holding that statement: a new post gets `authorId` from the context, and one naming another author is refused. - A save naming another author’s post finds no row it may update, so it inserts and fails on the key. [Multi-tenancy](https://uql-orm.dev/multi-tenancy.md) covers setting the context per request, the `{}` escape hatch for trusted cross-tenant jobs, and how security filters guard writes. # Pool > Build the connection pool every query runs on, size it, and close it. Source: https://uql-orm.dev/pool Every query runs on a pool, which owns the connections and lends one to each unit of work. It is the only part of UQL tied to your database: entities, queries and [migrations](https://uql-orm.dev/migrations.md) stay the same whichever pool you build. ## One per process Build the pool once, at module scope, in the `uql.config.ts` the [`uql-migrate`](https://uql-orm.dev/migrations.md) CLI also reads, and import it everywhere: ```ts title="uql.config.ts" import type { Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; import { Post, User } from './shared/models/index.js'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, max: 10, connectionTimeoutMillis: 5_000, }); export default { pool, entities: [User, Post] } satisfies Config; ``` The first argument is the driver’s own config, passed through as is. The second holds UQL’s options: [`logger`, `logValues` and `slowQuery`](https://uql-orm.dev/logging.md), [`namingStrategy`](https://uql-orm.dev/naming-strategy.md), a default [`schema`](https://uql-orm.dev/multiple-schemas.md) and `listeners`. A second pool doubles the connections without adding capacity. The exceptions are dev servers that re-run modules on hot reload, which cache the pool on `globalThis` (see [Next.js](https://uql-orm.dev/nextjs.md)), and [serverless functions](https://uql-orm.dev/serverless.md). Building a pool opens no connection, so a wrong password shows up at the first query. To fail at boot instead, run one there: ```ts await pool.all`SELECT 1`; ``` ## Which pool | Entry point | Class | First argument | | - | - | - | | `uql-orm/postgres` | `PgQuerierPool` | `pg`’s `PoolConfig` | | `uql-orm/neon` | `NeonQuerierPool` | `@neondatabase/serverless`’s `ClientConfig` | | `uql-orm/cockroachdb` | `CrdbQuerierPool` | `pg`’s `PoolConfig` | | `uql-orm/mysql` | `MySql2QuerierPool` | `mysql2`’s `PoolOptions` | | `uql-orm/mariadb` | `MariadbQuerierPool` | `mariadb`’s pool config | | `uql-orm/mssql` | `MsSqlQuerierPool` | `mssql`’s `config` | | `uql-orm/bun-sql` | `BunSqlQuerierPool` | Bun’s `SQL.Options` | | `uql-orm/sqlite` | `SqliteQuerierPool`, `NodeSqliteQuerierPool` | file path, then the driver’s options | | `uql-orm/pglite` | `PgliteQuerierPool` | data directory, then PGlite’s options | | `uql-orm/libsql` | `LibsqlQuerierPool` | `@libsql/client`’s `Config`, or a client you built | | `uql-orm/turso` | `TursoQuerierPool` | Turso Cloud settings | | `uql-orm/turso/local` | `TursoLocalQuerierPool` | file path, then the engine’s options | | `uql-orm/d1` | `D1QuerierPool` | the Worker’s D1 binding, or a session from it | | `uql-orm/mongodb` | `MongodbQuerierPool` | connection URI, then `MongoClientOptions` | SQLite, PGlite and embedded Turso keep one connection that every querier shares: the methods are the same, but queries run one at a time and two queriers cannot hold separate transactions. D1, Turso Cloud and Neon hold no connection and talk over `fetch()`; Turso Cloud gives each querier a server session of its own, and Neon a WebSocket for a transaction or a stream. ## How big `max` (`connectionLimit` on `mysql2` and `mariadb`, `maxPoolSize` on MongoDB) caps one process’s connections. Use the smallest of: the server’s limit (`max_connections`) divided by the processes that connect, the queries the process actually runs at once, and what the database can do in parallel (roughly its cores). An HTTP server handling 40 requests at a time wants tens; a worker taking one job at a time wants two or three. Always set an acquire timeout (`connectionTimeoutMillis` on the `pg` family, `connectTimeout` on `mysql2`, `acquireTimeout` on `mariadb`). The `pg` family waits forever without one, so an unreachable or exhausted database hangs every request. Pool calls inside `pool.transaction` reuse the transaction’s connection, so even `max: 1` cannot deadlock. See [Transactions](https://uql-orm.dev/querying/transactions.md). When the processes alone can exhaust the server, put a pooler in front instead of shrinking `max`: PgBouncer or RDS Proxy, [Supavisor](https://uql-orm.dev/supabase.md) on Supabase, [Hyperdrive](https://uql-orm.dev/postgres.md#cloudflare-hyperdrive) on Workers. They run in transaction mode, so keep `SET LOCAL`, advisory locks and temp tables inside one [`transaction`](https://uql-orm.dev/querying/transactions.md), and run migrations against the direct endpoint. ## Closing it `pool.end()` closes idle connections and waits for borrowed ones. Call it after the server stops accepting requests: ```ts process.on('SIGTERM', async () => { await server.close(); await pool.end(); }); ``` [NestJS](https://uql-orm.dev/nestjs.md) does this when `app.enableShutdownHooks()` is on. Skip it in [serverless functions](https://uql-orm.dev/serverless.md): the platform freezes the process before the close finishes. On D1 and Turso Cloud it does nothing, and a [libSQL](https://uql-orm.dev/turso.md#libsql) pool leaves a client you passed in open. Once ended, the `pg`, `mysql2` and SQL Server pools refuse new connections; the single-connection pools reopen on the next query. ## When a connection dies while idle A NAT, load balancer or `idle_session_timeout` can drop an idle connection. On the `pg`, CockroachDB, MariaDB and SQL Server pools, UQL logs the drop through the pool’s [`logger`](https://uql-orm.dev/logging.md), even with logging off, and discards the connection instead of letting the driver’s `'error'` event crash the process. The `pg` and CockroachDB pools also turn on `keepAlive` by default. The query that was running is yours to retry, on connection errors only and never for a non-idempotent write outside a [transaction](https://uql-orm.dev/querying/transactions.md). A querier released with a transaction still open is rolled back and logged; if that rollback fails, the connection is discarded. ## More than one pool A read replica or a database per tenant needs its own pool. Write functions against a [`UniversalQuerier`](https://uql-orm.dev/querying/querier.md#accept-a-universalquerier), which takes a pool or a querier, so the caller picks: ```ts import type { UniversalQuerier } from 'uql-orm'; const unpaid = (db: UniversalQuerier, companyId: number) => db.findMany(Invoice, { $where: { companyId, paid: false } }); await unpaid(replica, 42); await primary.transaction((querier) => unpaid(querier, 42)); ``` For tenants, build pools on demand in a capped map and `end()` the ones you evict. The [API](https://uql-orm.dev/http.md#the-pool) can pick a pool per call. Entities are registered once for the whole process, and a pool serves any of them. Migrations are not per pool, though: a `Migrator` with no `entities` list migrates every entity in the process. With a database per pool, give each migrator its own list: ```ts import { Migrator } from 'uql-orm/migrate'; await new Migrator(billing, { entities: [Invoice] }).sync(); await new Migrator(support, { entities: [Ticket] }).sync(); ``` The [two-pools test](https://github.com/rogerpadilla/uql/blob/main/packages/orm/src/sqlite/twoPools.test.ts) runs this setup. ## Reaching the driver `pool.pool` is the driver’s pool on the `pg`, CockroachDB, `mysql2`, `mariadb` and SQL Server pools, for libraries such as `attachDatabasePool` from `@vercel/functions` or `connect-pg-simple`. Bun’s pool has a `pg`-compatible shim there and its `SQL` instance at `pool.sql`; D1’s binding is `pool.db`. `pool.dialect.dialectName` names the backend (`'postgres'`, `'cockroachdb'`, `'mysql'`, `'mariadb'`, `'mssql'`, `'sqlite'` or `'mongodb'`). ## In tests Swap in a pool with no server behind it: [PGlite](https://uql-orm.dev/pglite.md) is Postgres in WASM, and `new SqliteQuerierPool(':memory:')` gives each pool a fresh database. ```ts title="test/db.ts" import { PgliteQuerierPool } from 'uql-orm/pglite'; export const pool = new PgliteQuerierPool(); ``` Build one per suite and `end()` it afterwards, or the runner may not exit. Both hold one connection, so a test that needs its own transaction needs its own pool. # Migrations > Keep your entities and your database schema in sync with the uql-migrate CLI. Source: https://uql-orm.dev/migrations Migrations carry schema changes from your entities to the database. Edit an entity, let UQL diff it against the database, review the file it writes, then apply it: ```bash npx uql-migrate generate:entities add_user_nickname npx uql-migrate up ``` If the database came first, UQL can [write the entities from it](#from-a-database-to-entities). ## Configuration The CLI reads the same `uql.config.ts` as your app (or the file given with `-c`). The engine comes from the pool, and the [naming strategy](https://uql-orm.dev/naming-strategy.md) applies to migrations too. ```typescript title="uql.config.ts" import type { Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; import { User, Post } from './entities'; export default { pool: new PgQuerierPool({ connectionString: process.env.DATABASE_URL }), entities: [User, Post], migrationsPath: './migrations', } satisfies Config; ``` ### Running the CLI On Node, install `tsx` so the CLI can load a TypeScript config with decorators. On Bun, pass `--bun` so Bun’s own drivers ([`BunSqlQuerierPool`](https://uql-orm.dev/bun-sql.md), `bun:sqlite`) work. A `uql.config.js` needs neither. ```bash npm install -D tsx && npx uql-migrate up # Node bun run --bun uql-migrate up # Bun ``` | Command | What it does | | - | - | | `generate:entities ` | Writes a migration from the diff between your entities and the database. | | `generate ` | Creates an empty migration (alias `create`). | | `generate:from-db` | Writes `@Entity` classes from the database. | | `up` / `down` | Applies all pending migrations / reverts the last one. | | `status` / `pending` | Lists run and pending migrations / only pending ones. | | `sync` | Applies the diff [with no migration file](#syncing-without-a-migration-file). | | `drift:check` | Reports where [the database and the entities disagree](#drift-detection). | | `types` | Writes a `.d.ts` for an [entity defined at runtime](https://uql-orm.dev/entities/runtime.md#typing). | `npx uql-migrate --help` lists the flags (`up --step`, `down --to`, `down --all`, `generate:from-db -o`). A failed migration exits with code 1. ## From entities to the database `generate:entities` lists every column it drops or retypes, so read the file before `up`. On MongoDB it writes collections, indexes and validators (from checks and enums); see [MongoDB migrations](https://uql-orm.dev/mongodb.md#migrations). ### Renames, retypes and what loses data A column is renamed only when the names differ by case and underscores (`firstName` and `first_name`), as a change of naming strategy makes them; data, indexes and foreign keys survive. Any other rename is a drop and an add. When the two columns match but for their names, `generate:entities` warns and prints the line to write instead, `renameColumn('posts', 'title', 'headline')`. A new table matching one no entity names gets a `renameTable('articles', 'posts')` hint the same way. A property whose column is pinned (`@Field(f.string().name('title'))`) can be renamed freely. On Postgres-family engines a retyped column converts its values (`USING "code"::INTEGER`). Making a column required fills its nulls with its default. With no default and rows present, `generate:entities` and `sync` stop and report how many rows lack a value: add a default, or add the column as nullable, fill it, then require it. The rollback of a drop can’t count rows, so it adds a required column with no default back as nullable, and `generate:entities` warns: fill it and require it in `down` if the rollback must restore it. ### Syncing without a migration file For a database whose data you can lose (a prototype, a test database), `sync` applies the diff directly: ```bash npx uql-migrate sync --dry-run # print the DDL only npx uql-migrate sync ``` `sync` only adds, so it is safe to rerun. `--unsafe` also drops and alters, and `--force` drops and recreates every mapped table. `--dry-run` writes only SQL to stdout, so you can append it to a migration file another tool applies, as on [Cloudflare D1](https://uql-orm.dev/cloudflare-d1.md#schema-changes). From code, for a dev server or test suite: ```ts import { Migrator } from 'uql-orm/migrate'; await new Migrator(pool, { entities: [User, Post] }).sync({ logging: true }); ``` `planSync()` returns the statements instead, and `sync({ entity })` applies one entity, for a [runtime entity](https://uql-orm.dev/entities/runtime.md). ## Hand-written migrations `generate ` creates an empty migration for backfills, views and anything else a diff cannot express. Write it with the [migration builder](https://uql-orm.dev/migrations/builder.md), which runs on every engine and supports [backfills](https://uql-orm.dev/migrations/builder.md#data-backfills), or in plain SQL. Every `.ts`, `.js` or `.mjs` file in `migrationsPath` is a migration named after its file. Keep shared helpers outside that directory and import them with their extension. ### Plain SQL A migration exports `up` and `down`, one statement per `run`: ```typescript title="migrations/20260731120000_add_articles.ts" import type { SqlQuerier } from 'uql-orm'; export default { async up(querier: SqlQuerier): Promise { await querier.run /*sql*/ ` CREATE TABLE "articles" ( "id" BIGSERIAL PRIMARY KEY, "title" VARCHAR(200) ) `; }, async down(querier: SqlQuerier): Promise { await querier.run /*sql*/ `DROP TABLE "articles"`; }, }; ``` A `${value}` in the template is bound, as anywhere else. The `/*sql*/` comment is what [es6-string-html](https://marketplace.visualstudio.com/items?itemName=Tobermory.es6-string-html) highlights as SQL, and generated migrations carry it too; ``sql`...` ``is highlighted without it. Add `transaction: false` beside `up` and `down` for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`. On MongoDB the module takes a `MongoQuerier`. ## Applying migrations from code An app can migrate before it starts serving: ```ts import { Migrator } from 'uql-orm/migrate'; await new Migrator(pool, { migrationsPath: './migrations' }).up(); ``` `up()` resolves with what it ran (`{ name, direction, duration }`) and takes `{ step }` or `{ to: name }`. `down()` reverts the last migration and takes the same options; `{ step: Infinity }` reverts all. `status()` resolves with `{ pending, executed }`. Every file a run needs loads before any of them runs, so an import error leaves the database untouched, and `down` refuses a recorded migration whose file is gone. Each migration runs in its own transaction with its journal record. If one fails, the call rejects: earlier migrations stay applied, and the rest stay pending. > **Some engines keep half a migration** > > MySQL, MariaDB and CockroachDB commit schema changes as they run, and MongoDB and `transaction: false` migrations run outside a transaction. A failure there keeps the earlier statements but records nothing. Keep a data change and the schema change it needs in separate migrations, or make them safe to rerun. ### Several instances at once `up` and `down` hold a lock named after the journal table, so when several instances start together one migrates and the rest wait, then find nothing to do. `status` never waits. The wait is capped by `lockTimeout` (milliseconds, 5 minutes by default). Postgres, MySQL, MariaDB and SQL Server lock natively, and a dropped connection releases the lock. The other engines write a `uql/lock` record into the journal instead. A process killed mid-run leaves that record behind and later runs time out on it; delete it once you are sure nothing is migrating. ## From a database to entities ```bash npx uql-migrate generate:from-db --output ./src/entities npx uql-migrate drift:check ``` Set the [naming strategy](https://uql-orm.dev/naming-strategy.md) first if your columns are `snake_case`. Fields follow [the entity docs](https://uql-orm.dev/entities/basic.md#required-fields): `id?` for a key the database generates and `id!` for one you supply, `title!` for `NOT NULL`, `status?` for a column with a default, `note?: string | null` for a nullable one. A default the database computes becomes `currentTimestamp` or `sql`. To move off another ORM gradually, see [switching to UQL](https://uql-orm.dev/switching-to-uql.md). ### Relations, when scaffolding A foreign key becomes a `@ManyToOne` and its `@OneToMany`, or a one-to-one when it is unique. Tables without foreign key constraints get no relations. ## Drift detection `drift:check` reports missing tables, columns, checks and triggers, and type mismatches that could truncate data, as critical. Missing or changed indexes, extra columns, stale checks or triggers, and differing `ON DELETE`/`ON UPDATE` actions are warnings. It does not run on MongoDB; use `sync --dry-run` there. ## How the diff works The diff touches only the tables your entities name, so other apps sharing the database are safe. It treats equivalent types (`INT`, `INTEGER`) as equal. `f.number().autoIncrement()` is a `BIGINT`, a foreign key column takes its target key’s exact type, and `sync` never alters a primary key. ### Indexes Indexes are diffed like columns. A removed index is dropped only if UQL named it or the entity still claims its name, so hand-made indexes survive. See [Indexes](https://uql-orm.dev/entities/indexes.md#synchronization). ### SQLite rebuilds the table SQLite, libSQL, Turso and D1 cannot alter a column’s type, nullability or default, a key, a foreign key or a check, so the migration rebuilds the table, keeping its rows, indexes, triggers and checks. Where foreign keys cannot be turned off (D1, remote libSQL or Turso), rebuilding a referenced table fails with `turn foreign keys off to rebuild
` instead of losing rows. # Migration builder > Write hand-made migrations once, as tables and columns, and run them on every engine. Source: https://uql-orm.dev/migrations/builder The migration builder describes a hand-written migration as tables and columns instead of [SQL strings](https://uql-orm.dev/migrations.md#plain-sql), and writes each engine’s own SQL, so one file runs on Postgres and SQLite alike. A column chains the methods an entity’s [`f` column](https://uql-orm.dev/entities/basic.md) does, read by the same rules. Its types (`MigrationBuilder`, `TableBuilder`, `AlterTableBuilder`, `TableColumnBuilder`, `TableColumnFactory`) are exported from `uql-orm/migrate`. ```typescript import { currentTimestamp } from 'uql-orm'; import { defineBuilderMigration } from 'uql-orm/migrate'; export default defineBuilderMigration({ async up(m) { await m.createTable('articles', (t) => { t.id(); t.string('title').length(200); t.boolean('published').default(false); t.timestamptz('created_at').default(currentTimestamp); t.integer('author_id').references('users').onDelete('CASCADE'); t.index(['published', 'created_at']); }); }, async down(m) { await m.dropTable('articles'); }, }); ``` On MongoDB the builder handles collections and indexes only; see [MongoDB migrations](https://uql-orm.dev/mongodb.md#migrations). ## Column types Each column method takes the name, then chains its [settings](#column-settings). `integer`, `smallint`, `float`, `double`, `text`, `boolean`, `date`, `time`, `json` and `blob` map to the type they name, `text` unbounded as `f.text()` is. The others: | Method | Notes | | - | - | | `id()` | Auto-increment `BIGINT` primary key, named `id` unless you pass a name | | `bigint` | Takes `BigInt` defaults (`0n`) | | `decimal` | Takes `precision` and `scale`: `t.decimal('price', 12, 2)` | | `string` | `VARCHAR`; `length()` defaults to 255 | | `char` | `CHAR`; `length()` defaults to 1 | | `timestamp` | No zone: UQL reads and writes UTC, but the database’s clock uses the session’s zone | | `timestamptz` | An instant | | `jsonb` | Binary JSON on Postgres, `json` elsewhere | | `uuid` | Pair with a [`uuid` default](#default-expressions) | | `vector` | Takes its dimensions, for [semantic search](https://uql-orm.dev/querying/semantic-search.md) | Both timestamp types hold milliseconds. `createdAt()`, `updatedAt()` and `timestamps()` add `timestamptz` columns defaulting to `currentTimestamp`, named exactly `createdAt` and `updatedAt`: [naming strategies](https://uql-orm.dev/naming-strategy.md) do not apply to the builder. Composite keys and constraints sit beside the columns: ```typescript await m.createTable('accounts', (t) => { t.string('tenant_id').length(40); t.string('username').length(50); t.primaryKey(['tenant_id', 'username']); t.foreignKey(['tenant_id']).references('tenants', ['id']).onDelete('CASCADE'); t.unique(['username']); t.comment('Customer accounts'); }); ``` ## Column settings | Method | Meaning | | - | - | | `nullable()` | Allow `NULL`; a column is `NOT NULL` otherwise, as an entity’s is | | `default(value)` | A literal or an [expression](#default-expressions) | | `id()` | Primary key; it auto-increments only with `autoIncrement()` | | `autoIncrement()` | Primary key the database generates (integers) | | `unique()` | Unique index on the column | | `index(name?)` | An index, auto-named unless given one | | `length(n)` | A string’s length | | `precision(n)`, `scale(n)` | A decimal’s digits, or a timestamp’s fractional-second digits | | `enum(values)` | A `CHECK (col IN (...))` | | `as('price * qty')` | A generated column, `GENERATED ALWAYS AS (...) STORED`, its SQL as text | | `unsigned()` | Unsigned number, on MySQL and MariaDB | | `comment(text)` | Column comment | | `references(table, column?)` | Foreign key to `column` (default `id`), then `onDelete()` and `onUpdate()` | ### Default expressions A literal default (string, number, boolean, `null`, `Date`, JSON) is quoted for you. For a value the database computes, use the same constants as entities ([`currentTimestamp`, `currentDate`, `currentTime`, `uuid`, `uuidv7`](https://uql-orm.dev/entities/basic.md#values-the-database-computes)) or [`sql`](https://uql-orm.dev/querying/raw-sql.md) SQL: ```typescript import { sql, uuid } from 'uql-orm'; t.uuid('id').id().default(uuid); t.bigint('seq').default(sql`nextval('orders_seq')`); ``` A migration’s SQL is DDL, which binds nothing, so a `sql` default or `as()` interpolates no value. Each engine gets its own spelling. On an engine without the function, the migration throws before any SQL is sent. UQL does not check server versions, so `uuidv7` on Postgres older than 18 fails on the server. ## Altering a table ```typescript await m.alterTable('users', (t) => { t.addColumn((c) => c.string('nickname').length(100).nullable()); t.renameColumn('full_name', 'name'); t.alterColumn((c) => c.string('email').length(300)); t.dropColumn('legacy_field'); t.addIndex(['nickname']); t.dropIndex('users__old_name_idx'); t.addForeignKey(['profile_id'], { table: 'profiles', columns: ['id'] }); t.dropForeignKey('users__legacy_fk'); }); ``` Each of these also exists on `m` with the table first, such as `m.addColumn('users', (c) => c.text('bio'))`, alongside `m.renameTable(from, to)`, `m.dropTable(name, { ifExists, cascade })` and `m.raw(sql)` for anything the builder does not model. ## Data backfills `up` and `down` get the querier as a second argument, in the same transaction as the builder: ```typescript import { defineBuilderMigration } from 'uql-orm/migrate'; export default defineBuilderMigration({ async up(m, querier) { await m.addColumn('users', (c) => c.string('slug').nullable()); const users = await querier.all<{ id: number; name: string; }>`SELECT "id", "name" FROM "users"`; for (const { id, name } of users) { await querier.run`UPDATE "users" SET "slug" = ${name.toLowerCase()} WHERE "id" = ${id}`; } await m.alterColumn('users', (c) => c.string('slug')); }, async down(m) { await m.dropColumn('users', 'slug'); }, }); ``` Query tables by name, not through your entities: the entities will change after the migration is written, and the migration must keep working. ## Index options `t.index`, `t.unique`, `t.addIndex` and `m.createIndex` take the same entries and options as an entity’s [`indexes`](https://uql-orm.dev/entities/indexes.md): column names, ``sql`...` ``expressions, per-column modifiers, `type`, `where`, `include` and vector tuning. `where` must be `sql`, since there is no entity to check it against. ```typescript t.unique([sql`lower("email")`], { name: 'notes__email_uk', where: sql`"deleted_at" IS NULL`, }); t.index([{ column: 'body', prefixLength: 64 }]); // MySQL and MariaDB need a prefix length on TEXT ``` An option the engine cannot express throws when the migration runs, naming the index. # Multi-tenancy > Scope every query and write to the current tenant with a security filter and a per-request context. Source: https://uql-orm.dev/multi-tenancy A `security` [filter](https://uql-orm.dev/querying/filters.md) scopes every query to the current tenant, read from a per-request context. Reads, writes, relations and cascades are all scoped, so you never write `WHERE tenantId = ...` or set the tenant on a new row by hand. This page covers tenants sharing a table, kept apart by a column. To give each tenant its own schema instead, see [Multiple Schemas](https://uql-orm.dev/multiple-schemas.md). ## 1. Add a security filter The filter’s `where` is a function of the context: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ filters: { tenant: { where: (ctx) => ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined, security: true, }, }, }) export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) companyId?: number | null; @Field(f.number().nullable()) total?: number | null; } ``` With no tenant, return `undefined`, never `{ companyId: undefined }`, so the query throws instead of running unscoped. To type `ctx.tenantId`, declare the context once. Keep the keys optional, since a background job may know only some of them: ```ts declare module 'uql-orm' { interface UqlContext { tenantId?: number; system?: boolean; } } ``` ## 2. Set the context `withContext` sets the context for a unit of work. It follows `await`, `Promise.all`, transactions and [pool calls](https://uql-orm.dev/querying/querier.md#choosing-poolx-vs-querierx): ```ts import { withContext } from 'uql-orm'; await withContext({ tenantId: 42 }, async () => { await pool.findMany(Invoice, { $where: { total: { $gt: 100 } } }); // SELECT ... FROM "Invoice" WHERE ("total" > $1) AND ("companyId" = $2) -- $2 = 42 }); ``` At your [API](https://uql-orm.dev/http.md), `contextOf` does this for every call. Read the tenant from a verified source such as a session or a decoded JWT, never from client input: ```ts import { createApi } from 'uql-orm/http'; createApi<{ user: { tenantId: number } }>({ pool, include: [Invoice], contextOf: (req) => ({ tenantId: req.user.tenantId }), }); ``` [NestJS](https://uql-orm.dev/nestjs.md) takes the same option: `UqlModule.forRoot({ pool, contextOf })`. ## What `security: true` guarantees A security filter is always applied, to every statement unless its [`ops`](https://uql-orm.dev/querying/filters.md#per-statement-read-all-write-only-your-own) names the ones it holds: `{ filters: false }` and bypassing by name are ignored, and the API reads only query keys from a call, so a client cannot send `filters` or `context`. Its condition is ANDed on its own, so a request sending `$where: { companyId: 999 }` becomes `companyId = 999 AND companyId = 42` and matches nothing. It fails closed. When the condition returns `undefined`, the query throws `UqlSecurityError`, and `onMissing: 'skip'` is refused on a security filter. It follows relations. `$populate: { company: true }` enforces `company`’s security filter on every driver, MongoDB included, and so do [relation filters and `$size` counts](https://uql-orm.dev/querying/relations.md). It guards writes: - An insert gets the filter’s fields from the context, and naming another value is refused. - An update cannot change them. - A save or upsert naming another tenant’s row fails on its key (a `409` over HTTP) instead of overwriting it. - A condition returning `{}` writes freely. One that is not plain field equalities (`$in`, `$or`) refuses writes, since there is no single value to check. A refused write throws `UqlSecurityError`, a `403` over HTTP. Security filters combine with other filters. An `Invoice` that is also [soft-deletable](https://uql-orm.dev/entities/soft-delete.md) gets both conditions, `WHERE ("companyId" = $1) AND ("deletedAt" IS NULL)`, and `withDeleted()` lifts only the soft-delete one. ## Jobs, scripts and tests Outside an HTTP request, wrap the work in `withContext({ tenantId }, () => runNightlyBilling(tenantId))`. For trusted work across all tenants, such as startup recovery, give the filter’s `where` a system branch that returns `{}` and run those jobs under a system context. A query with no context at all still fails closed. Annotate the function’s return type: typing the const as `FilterWhere` instead lets a mistyped column through. ```ts import type { QueryWhere, UqlContext } from 'uql-orm'; // the filter's `where` const tenantScope = (ctx?: UqlContext): QueryWhere | undefined => ctx?.system ? {} : ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined; await withContext({ system: true }, () => recoverStaleJobs()); ``` ## Event-driven pipelines (emitters, timers, queues) `withContext` uses `AsyncLocalStorage`, which follows `await` but not event callbacks. An emitter listener, a timer or a queued job runs outside the scope that registered it. `captureContext()` captures the context and replays it when the callback fires: ```ts import { captureContext } from 'uql-orm'; const scoped = captureContext(); // inside the scoped request deepgram.on('transcript', (t) => scoped(() => saveTranscript(t))); ``` When the code already knows its tenant, pass `{ context }` to `withQuerier` or `transaction` instead: ```ts await pool.withQuerier( (q) => q.updateMany(Resource, { $where: { id } }, patch), { context: { tenantId } }, ); ``` Wrap your app’s few chokepoints (event bus, queue runners, socket dispatch), not every function. > **Adopt it fully** > > The filter replaces passing `tenantId` through every `$where` and insert by hand. Remove the manual scoping when you adopt it, or you keep two sources of truth for one rule. ## Security filters and database RLS Security filters hold only inside UQL. Raw SQL (`querier.all`) is yours to scope, and other services on the same database bypass them. For the strongest isolation, add the database’s own row-level security, such as [Postgres RLS](https://uql-orm.dev/postgres.md#row-level-security), as a backstop. # Multiple Schemas > Put entities in different schemas, or give each tenant a schema of its own, with the same entity classes. Source: https://uql-orm.dev/multiple-schemas A schema is a namespace inside one database (in MySQL and MariaDB, a database). Set one on an entity to pin its table, or on the pool as the default for entities that name none; the entity’s wins. With neither, tables stay unqualified and resolve through the connection’s default, such as Postgres’s `search_path`. Schemas work on Postgres, CockroachDB, MySQL, MariaDB and SQL Server. The SQLite family and MongoDB ignore `schema`. ## A fixed layout: `schema` on the entity Entities in different schemas still join in one statement: ```ts import { f, Entity, Field, ManyToOne } from 'uql-orm'; @Entity({ schema: 'crm' }) export class Customer { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; } @Entity({ schema: 'sales' }) export class Order { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().nullable()) total?: number | null; @Field(f.references(() => Customer).nullable()) customerId?: number | null; @ManyToOne(() => Customer, { references: (order) => order.customerId, }) customer?: Customer; } ``` ```ts title="You write" const orders = await pool.findMany(Order, { $select: { id: true, total: true }, $populate: { customer: { $select: { name: true } } }, }); ``` PostgreSQL: ```sql SELECT "Order"."id", "Order"."total", "customer"."id" "customer.id", "customer"."name" "customer.name" FROM "sales"."Order" "Order" LEFT JOIN "crm"."Customer" "customer" ON "customer"."id" = "Order"."customerId" ``` MySQL: ```sql SELECT `Order`.`id`, `Order`.`total`, `customer`.`id` `customer.id`, `customer`.`name` `customer.name` FROM `sales`.`Order` `Order` LEFT JOIN `crm`.`Customer` `customer` ON `customer`.`id` = `Order`.`customerId` ``` MariaDB: ```sql SELECT `Order`.`id`, `Order`.`total`, `customer`.`id` `customer.id`, `customer`.`name` `customer.name` FROM `sales`.`Order` `Order` LEFT JOIN `crm`.`Customer` `customer` ON `customer`.`id` = `Order`.`customerId` ``` SQLite: ```sql SELECT `Order`.`id`, `Order`.`total`, `customer`.`id` `customer.id`, `customer`.`name` `customer.name` FROM `Order` LEFT JOIN `Customer` `customer` ON `customer`.`id` = `Order`.`customerId` ``` SQL Server: ```sql SELECT "Order"."id", "Order"."total", "customer"."id" "customer.id", "customer"."name" "customer.name" FROM "sales"."Order" "Order" LEFT JOIN "crm"."Customer" "customer" ON "customer"."id" = "Order"."customerId" ``` > **Put the schema in schema, not in name** > > `name: 'sales.Order'` is refused when the entity is defined, because `name` is escaped as a single identifier. To map a table name that exists in two schemas, declare two classes, such as `CrmCompany` with `@Entity({ schema: 'crm', name: 'Company' })` and `BillingCompany` with `@Entity({ schema: 'billing', name: 'Company' })`. Over [HTTP](https://uql-orm.dev/http.md) an entity’s path is its kebab-cased class name (`/crm-company`), and two classes on one path make `createApi` throw. ## A schema per tenant: `schema` on the pool Give each tenant a pool with its own schema. Entities that name a schema keep it, so shared reference data can sit beside per-tenant tables: ```ts import { PgQuerierPool } from 'uql-orm/postgres'; const tenantA = new PgQuerierPool( { connectionString: process.env.DATABASE_URL }, { schema: 'tenant_a' }, ); @Entity() export class Invoice {} // wherever the pool points @Entity({ schema: 'public' }) export class Country {} // always public ``` UQL writes the schema into each statement instead of setting `search_path`, so it works behind a pooler that hands out a different session per transaction. Over HTTP, pick the pool from the verified caller, never from the URL, or any signed-in caller can read any tenant by editing it: ```ts import { createApi, toFetchHandler } from 'uql-orm/http'; const handler = toFetchHandler( createApi({ include: [Invoice], pool: (request) => poolFor(tenantOf(request)), }), ); ``` For tenants sharing one schema, use a [security filter](https://uql-orm.dev/multi-tenancy.md) on a tenant column instead. ## Migrations `uql-migrate generate:entities` creates each schema before its tables (`CREATE SCHEMA IF NOT EXISTS`, a database on MySQL and MariaDB). `drift:check` and `sync` read back the schemas your entities name, so a qualified table diffs like any other. # Serverless > Run UQL in functions that freeze and thaw: pool placement, connection limits, and per-platform setup. Source: https://uql-orm.dev/serverless A serverless function is a normal process that is frozen between invocations, killed without warning, and multiplied by traffic. Entities and queries do not change; only where you build the [pool](https://uql-orm.dev/pool.md) and how you size it. ## Put the pool at module scope Platforms reuse a warm instance for consecutive requests, and module scope runs once per instance: ```ts title="db.ts" import { PgQuerierPool } from 'uql-orm/postgres'; import './entities.js'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, max: 2, connectionTimeoutMillis: 5_000, }); ``` A pool built inside the handler pays a handshake on every request. Nothing connects until the first query, so an unused pool costs nothing. Always set `connectionTimeoutMillis`. Without it, a database that is asleep, unreachable or full keeps the request waiting (and billed) until the platform kills it; with it, the query throws in time to return a 503. A framework dev server re-runs the module on every hot reload, so cache the pool on `globalThis` in development (see [Next.js](https://uql-orm.dev/nextjs.md)). ## Size `max` per instance `max: 10` on a platform that scales to 200 instances asks for 2,000 connections, and a small Postgres accepts about 100. Size `max` for the concurrency inside one instance. Lambda runs one invocation per environment, so `1` or `2` is right unless your handler runs queries in parallel (a `Promise.all` over three wants `3`). Runtimes that share an instance across requests, such as Vercel Fluid compute, want a handful. Even `max: 1` is safe with transactions, since [pool calls inside one reuse its connection](https://uql-orm.dev/pool.md#how-big). When instance count alone can exhaust the server, put a [pooler](https://uql-orm.dev/pool.md#how-big) in front of the database rather than shrinking `max`, and run [migrations](https://uql-orm.dev/migrations.md) against the direct endpoint. ## The first query after a thaw can fail A frozen instance runs no timers, so it cannot notice a connection going away. Meanwhile a database `idle_session_timeout`, a NAT or a pooler drops the socket, and the next invocation’s first query fails with `ECONNRESET` or `Connection terminated unexpectedly`. UQL [discards the dead client](https://uql-orm.dev/pool.md#when-a-connection-dies-while-idle) and the next acquire opens a fresh one. Retry that request yourself, on connection errors only, and never a non-idempotent write outside a [transaction](https://uql-orm.dev/querying/transactions.md). ## AWS Lambda The module-scope pool above is the whole setup: ```ts import type { APIGatewayProxyHandlerV2 } from 'aws-lambda'; import { pool } from './db.js'; import { Invoice } from './entities.js'; export const handler: APIGatewayProxyHandlerV2 = async () => { const invoices = await pool.findMany(Invoice, { $where: { paid: false }, $limit: 20, }); return { statusCode: 200, body: JSON.stringify(invoices) }; }; ``` Do not call `pool.end()` per invocation: Lambda freezes the process once the handler settles, so it would not finish, and the database reclaims connections when the environment dies. A callback-style handler needs `context.callbackWaitsForEmptyEventLoop = false`, or the idle socket keeps the invocation open until it times out. In a VPC, put RDS Proxy next to RDS, or instance count becomes connection count. ## Vercel On Fluid compute an instance serves several requests and then suspends. `attachDatabasePool` releases idle clients before that, so connections follow traffic rather than instance count: ```ts title="db.ts" import { attachDatabasePool } from '@vercel/functions'; import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, max: 5, }); attachDatabasePool(pool.pool); ``` [`pool.pool`](https://uql-orm.dev/pool.md#reaching-the-driver) is the driver’s pool. Keep the Node.js runtime, since `pg` needs TCP. An [Astro](https://uql-orm.dev/astro.md#caching) app can also cache responses at the edge with `cacheVercel()`, so repeat requests never reach a function. ## Neon `uql-orm/neon` swaps `pg` for `@neondatabase/serverless`, over HTTP first: each statement is one `fetch`, and a split write is one request Neon runs as a transaction, so it runs wherever `fetch` does and holds no connection between queries. It takes Neon’s `ClientConfig`: ```ts title="db.ts" import { NeonQuerierPool } from 'uql-orm/neon'; import './entities.js'; export const pool = new NeonQuerierPool({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 5_000, }); ``` A transaction, a stream and a migration need a session, so for those a querier opens a WebSocket of its own and its release closes it. The pool holds no connection, so one at module scope serves every request, on Cloudflare Workers too, where a socket cannot outlive its request. It uses the runtime’s global `WebSocket`, which Node 22 and newer have. On a long-running server, prefer `PgQuerierPool` over TCP, which reuses its connections. Neon’s HTTP endpoint binds at most 32,767 values a statement, and UQL splits a write within that. A Neon compute scaled to zero wakes on the first query, so set the connection timeout here too. Each HTTP request is a session of its own, so a `SET` lasts for that statement alone. Put a setting for one unit of work in a transaction as `SET LOCAL`, and one for every query on the role or database, which each new session starts with: `ALTER ROLE app SET search_path = app, public`. ## Cloudflare Workers and Vercel Edge These run isolates, not processes, and a socket opened for one request cannot serve the next; Workers throws if you try. Turn on `nodejs_compat`, which transactions and `withContext` need. A pool holding sockets, such as `PgQuerierPool` on Hyperdrive, is built inside the handler; [Neon](#neon), [D1](https://uql-orm.dev/cloudflare-d1.md) and [Turso](https://uql-orm.dev/turso.md) hold none, so theirs stays at module scope: ```ts title="src/index.ts" import { PgQuerierPool } from 'uql-orm/postgres'; import { Invoice } from './entities.js'; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const pool = new PgQuerierPool({ connectionString: env.HYPERDRIVE.connectionString, max: 5, }); try { return Response.json( await pool.findMany(Invoice, { $where: { paid: false }, $limit: 20 }), ); } finally { ctx.waitUntil(pool.end()); } }, }; ``` `ctx.waitUntil` closes the pool without delaying the response. The [API](https://uql-orm.dev/http.md) takes its `pool` as an option, or a function that picks one per call, so a database per tenant needs nothing special. ## Cold starts To keep module loading small, import the entry point you use (`uql-orm/postgres`, not a barrel that pulls every dialect) and register only the entities the function needs. # Logging & Monitoring > Log queries, catch slow ones, and send UQL's logs to your own logger. Source: https://uql-orm.dev/logging UQL can log every query with its duration, flag slow queries, and report migration and schema activity. You set it per pool, in the pool’s options. ## Configuration `logger: true` turns on every level through the built-in `DefaultLogger`, which prints colored lines to the console: ```ts import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool( { connectionString: process.env.DATABASE_URL }, { logger: true, slowQuery: 200, // log any query taking 200ms or more as slow }, ); ``` An array turns on only the levels you list: ```ts import type { ExtraOptions } from 'uql-orm'; const options: ExtraOptions = { logger: ['error', 'warn', 'migration'], slowQuery: 1000, }; ``` `slowQuery` works on its own: setting it logs slow queries whatever levels `logger` lists, even with no `logger` at all. The example above is a common production setup: quiet, except for problems and queries past a second. ### Bound values Bound values are not logged unless you set `logValues: true`, since query parameters may hold personal data. It applies to query logs and slow-query logs alike. ```ts const options: ExtraOptions = { logger: true, logValues: true, }; ``` ## Log levels | Level | What it logs | | - | - | | `query` | Each statement or command, with its duration (and values if on). | | `error` / `warn` | Errors and warnings. | | `migration` | Each migration as it runs and finishes. | | `skippedMigration` | Destructive schema changes that `sync` held back in safe mode. | | `schema` / `info` | Schema sync steps and other events. | A dropped idle connection on a driver pool is always logged through the pool’s `logger`, even when the `error` level is not listed or logging is off. See [when a connection dies while idle](https://uql-orm.dev/pool.md#when-a-connection-dies-while-idle). ## Output format `DefaultLogger` writes lines like these (values appear only with `logValues: true`): ```text query: SELECT * FROM "user" WHERE "id" = $1 -- [123] [2ms] slow query: UPDATE "post" SET "title" = $1 -- ["New Title"] [1250ms] skipped migration: [AutoSync] Skipped 1 column drops in table 'user': old_field (drop: false. Use { drop: true } to apply). ``` ## Custom logger A function receives everything. Queries arrive as `(query, values, duration)`, other messages as `(message)` or `(message, error)`: ```ts const options: ExtraOptions = { logger: (message, ...args) => myLogger.debug(message, ...args), }; ``` A `Logger` object gets one method per level: `logQuery`, `logSlowQuery`, `logWarn`, `logError`, `logInfo`, `logSchema`, `logMigration` and `logSkippedMigration`. Each is optional, so you can send slow queries somewhere regular ones do not go: ```ts import type { ExtraOptions, Logger } from 'uql-orm'; const logger: Logger = { logSlowQuery(query, values, duration) { pagerduty.alert(`Slow query (${duration}ms): ${query}`); }, logError(message, error) { sentry.captureException(error ?? new Error(message)); }, }; const options: ExtraOptions = { logger, slowQuery: 500 }; ``` To keep the console output and add alerting, extend `DefaultLogger` and override one method: ```ts import { DefaultLogger } from 'uql-orm'; class AlertingLogger extends DefaultLogger { override logSlowQuery( query: string, values?: readonly unknown[], duration?: number, ) { super.logSlowQuery(query, values, duration); pagerduty.alert(`Slow query (${duration}ms): ${query}`); } } ``` [Migrations](https://uql-orm.dev/migrations.md#applying-migrations-from-code) take the same `logger`, `logValues` and `slowQuery` options: `new Migrator(pool, { logger: true })`. # Naming Strategy > Map camelCase class and property names to the table and column names your database uses. Source: https://uql-orm.dev/naming-strategy A naming strategy turns your TypeScript names into database names, so code stays `camelCase` while the schema stays `snake_case`. Set it on the pool your app and `uql.config.ts` use: ```ts import { SnakeCaseNamingStrategy } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool( { host: 'localhost', database: 'my_db' }, { namingStrategy: new SnakeCaseNamingStrategy() }, ); ``` The entity `UserAccount` then maps to the table `user_account`, and the fields `createdAt` and `authorId` to the columns `created_at` and `author_id`. Without a strategy, or with `DefaultNamingStrategy`, names are used as written. The strategy applies to queries and [migrations](https://uql-orm.dev/migrations.md) alike. Set it before you [scaffold entities from an existing database](https://uql-orm.dev/migrations.md#from-a-database-to-entities), so the generated classes use the same mapping. A name you write yourself skips the strategy: `@Entity({ name: 'Users' })`, a [`schema`](https://uql-orm.dev/multiple-schemas.md), and a `.name()` on a field that differs from its property are used as written. ## Custom strategy Implement `NamingStrategy`, or extend `DefaultNamingStrategy` and override what you need: ```ts import { DefaultNamingStrategy } from 'uql-orm'; export class PrefixedNamingStrategy extends DefaultNamingStrategy { override tableName(entityName: string): string { return `tbl_${super.tableName(entityName)}`; } } ``` # Bun Native SQL > Drive Bun's built-in SQL client with UQL, one pool for Postgres, MySQL, MariaDB and CockroachDB. Source: https://uql-orm.dev/bun-sql Under Bun, `uql-orm/bun-sql` drives Bun’s own SQL client, so you install no `pg` or `mysql2`. Entities, queries and [migrations](https://uql-orm.dev/migrations.md) stay the same. ```sh bun add uql-orm ``` ## Connect `BunSqlQuerierPool` takes Bun’s `SQL.Options` and picks the dialect from them: ```ts import { BunSqlQuerierPool } from 'uql-orm/bun-sql'; export const pool = new BunSqlQuerierPool({ url: 'postgres://localhost:5432/app', }); ``` | URL scheme or `adapter` | Dialect UQL emits | | - | - | | `postgres://`, `postgresql://` | PostgreSQL | | `mysql://`, `mysql2://` | MySQL | | `mariadb://` | MariaDB | | `cockroachdb://` | CockroachDB | UQL emits each engine’s own SQL; only parameter binding is adapted for Bun. CockroachDB connects through Bun’s Postgres adapter while UQL keeps emitting [CockroachDB SQL](https://uql-orm.dev/cockroachdb.md). > **Name the engine** > > Bun falls back to Postgres for any scheme it does not recognize, so a MySQL server reached through an unknown scheme would receive Postgres SQL. Use one of the schemes above, or set `adapter`. A SQL Server or SQLite URL throws and names the pool to use instead. ## Connections and raw SQL Each querier reserves a dedicated connection from Bun’s pool and releases it when the querier is released. Raw SQL runs through [`all` and `run`](https://uql-orm.dev/querying/raw-sql.md) on the pool or a querier, as on any SQL pool, and `pool.sql` is Bun’s own client. ## SQLite This pool does not drive SQLite. Use [`SqliteQuerierPool`](https://uql-orm.dev/sqlite.md), which uses `bun:sqlite` under Bun with nothing to install, and also streams, loads extensions and prepares statements: ```ts import { SqliteQuerierPool } from 'uql-orm/sqlite'; const pool = new SqliteQuerierPool(':memory:'); ``` ## Streaming Bun’s client has no cursor API, so on Postgres and CockroachDB `findManyStream` pages rows through a SQL cursor (`DECLARE` / `FETCH`). Memory stays flat, and the cursor closes when the loop ends, breaks or throws. A cursor needs a transaction, so a stream outside one opens its own. On MySQL and MariaDB there is no cursor to reach, so the whole result is fetched first and then yielded row by row. To stream a large table there, use [`mysql2` or `mariadb`](https://uql-orm.dev/mysql.md). See [Streaming](https://uql-orm.dev/querying/streaming.md). # Cloudflare D1 > Run UQL on Cloudflare Workers with D1, including its limits and the transactions it does not have. Source: https://uql-orm.dev/cloudflare-d1 D1 is SQLite at the edge, so entities and queries are the ones you would run on [SQLite](https://uql-orm.dev/sqlite.md). What changes is the runtime: the database arrives as a binding on `env`, and D1 has hard limits. A runnable Worker with everything on this page is in [examples/cloudflare-d1](https://github.com/rogerpadilla/uql/tree/main/examples/cloudflare-d1). ## Query from a Worker ```jsonc title="wrangler.jsonc" { "name": "my-app", "main": "src/index.ts", "compatibility_date": "2026-08-01", "d1_databases": [ { "binding": "DB", "database_name": "my-app", "database_id": "" }, ], } ``` The binding exists only inside a request, so build the pool there. It wraps `env.DB`, with nothing to connect, and `end()` does nothing. Import your entities module so the entities are registered: ```ts title="src/index.ts" import { D1QuerierPool } from 'uql-orm/d1'; import { Todo } from './models'; export default { async fetch(request: Request, env: Env) { const pool = new D1QuerierPool(env.DB); return Response.json( await pool.findMany(Todo, { $where: { completed: false }, $limit: 50 }), ); }, }; ``` For a read-replicated database, pass a [session](https://developers.cloudflare.com/d1/best-practices/read-replication/) instead of `env.DB`; otherwise every query goes to the primary. A bookmark carries consistency across requests: ```ts const session = env.DB.withSession( request.headers.get('x-d1-bookmark') ?? 'first-unconstrained', ); const pool = new D1QuerierPool(session); const response = Response.json(await pool.findMany(Todo, { $limit: 50 })); response.headers.set('x-d1-bookmark', session.getBookmark() ?? ''); ``` ## No transactions D1 rejects `BEGIN`, so UQL refuses `pool.transaction(...)` before sending anything, and so do the writes of the [HTTP API](https://uql-orm.dev/http.md). A write UQL splits on its own, such as an `insertMany` past the 100-parameter cap or an `upsertMany` of rows of different shapes, goes as one `batch()`, which D1 runs as one transaction: it lands whole or not at all. When writes of your own must land together, make them one statement, make them idempotent, or move that work to a [Durable Object](https://developers.cloudflare.com/durable-objects/). ## Limits | Limit | Value | | - | - | | Bound parameters per query | 100 (`insertMany` chunks to fit) | | Arguments per function call | 32 (wide calls are split to fit) | | Value or row size | 2 MB, a populated relation included | | SQL statement length | 100 KB | | Query duration | 30 s | | Database size | 10 GB on the paid plan | D1 loads no extensions. [Full-text search](https://uql-orm.dev/querying/full-text.md) works through FTS5, but a `$vector` sort throws; use [Vectorize](https://developers.cloudflare.com/vectorize/) for vectors. ## Schema changes UQL writes the SQL and wrangler applies it, since the binding exists only in a Worker and D1 refuses the transaction `uql-migrate up` opens. Point the CLI at wrangler’s local copy of the database: ```ts title="uql.config.ts" import { existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import type { Config } from 'uql-orm'; import { NodeSqliteQuerierPool } from 'uql-orm/sqlite'; import { Todo } from './src/models'; function localD1File(): string { const dir = '.wrangler/state/v3/d1/miniflare-D1DatabaseObject'; const files = existsSync(dir) ? readdirSync(dir).filter( (name) => name.endsWith('.sqlite') && name !== 'metadata.sqlite', ) : []; if (files.length > 1) throw new Error( `Expected one local D1 database in ${dir}: delete the stale ones.`, ); return files[0] ? join(dir, files[0]) : ':memory:'; } export default { pool: new NodeSqliteQuerierPool(localD1File()), entities: [Todo], } satisfies Config; ``` Then, for each entity change (with `tsx` installed, as [the CLI needs on Node](https://uql-orm.dev/migrations.md#running-the-cli)): ```sh npx wrangler d1 migrations create my-app add_todos npx uql-migrate sync --dry-run >> migrations/0001_add_todos.sql npx wrangler d1 migrations apply my-app --local # then --remote ``` `sync --dry-run` prints only SQL on stdout, with notes on stderr, so the file gets only SQL. D1 keeps foreign keys on. A change SQLite makes by [rebuilding the table](https://uql-orm.dev/migrations.md#sqlite-rebuilds-the-table) fails when another table references it, so write that migration by hand, rebuilding the referencing tables too. ## Serving reads over HTTP `toFetchHandler` mounts in a Worker. Build it per request, since the binding arrives with the request, and serve reads alone: the API runs each write in a transaction, which D1 refuses. ```ts import { UqlRequestError } from 'uql-orm'; import { API_OPS, type ApiMiddleware, createApi, toFetchHandler, } from 'uql-orm/http'; const readsOnly: ApiMiddleware = async (call, _context, next) => { if (API_OPS[call.op].access !== 'read') { throw new UqlRequestError( 'D1 runs no transaction: write through your own routes', 405, ); } return next(call); }; export default { fetch(request: Request, env: Env) { const api = createApi({ pool: new D1QuerierPool(env.DB), include: [Todo], use: [readsOnly], }); return toFetchHandler(api)(request); }, }; ``` For SQLite with transactions on the same runtime, use [Turso](https://uql-orm.dev/turso.md); for Postgres, [Hyperdrive](https://uql-orm.dev/postgres.md#cloudflare-hyperdrive). # CockroachDB > Run UQL on CockroachDB over the Postgres wire protocol, and what differs from PostgreSQL. Source: https://uql-orm.dev/cockroachdb CockroachDB speaks the Postgres wire protocol, so UQL drives it with `pg` and shares most of its SQL with [PostgreSQL](https://uql-orm.dev/postgres.md). Native arrays, JSONB, `RETURNING` ids and [streaming](https://uql-orm.dev/querying/streaming.md) work the same. ## Install and connect ```sh npm install uql-orm pg ``` ```ts import { CrdbQuerierPool } from 'uql-orm/cockroachdb'; export const pool = new CrdbQuerierPool({ connectionString: process.env.DATABASE_URL, max: 10, }); ``` Under Bun, [`bun:sql`](https://uql-orm.dev/bun-sql.md) connects through its Postgres adapter and UQL still emits CockroachDB SQL. ## Retry transactions The default isolation is `serializable`, so contention fails transactions with `40001`, which [`queryErrorKind`](https://uql-orm.dev/querying/errors.md) reports as `'retryable'`. [Retry the whole callback](https://uql-orm.dev/querying/errors.md#retrying-a-transaction). `read committed` avoids most retries, with a weaker guarantee: ```ts await pool.transaction(run, { isolationLevel: 'read committed' }); ``` ## Primary keys A generated `BIGINT` identity key works, but increasing keys send every insert to one range. For a write-heavy table, use a random UUID; a UUIDv7 sorts by time and brings the hotspot back: ```ts import { Field, f } from 'uql-orm'; @Field(f.uuid().id().onInsert(() => crypto.randomUUID())) id?: string; ``` ## What differs from PostgreSQL Vector search is built in: no extension, and `CREATE VECTOR INDEX` for the index. `cosine`, `l2` and `inner` work; `l1` does not. Indexes support expressions and `INCLUDE`, but not `NULLS FIRST/LAST` or `jsonb_path_ops`. [Full-text search](https://uql-orm.dev/querying/full-text.md) reads the search as plain words, with no `WEBSEARCH_TO_TSQUERY`. [Migrations](https://uql-orm.dev/migrations.md) commit each schema change as it runs (`autocommit_before_ddl`), so a failed migration keeps the statements before the failure. With no advisory locks, a run [holds its lock](https://uql-orm.dev/migrations.md#several-instances-at-once) as a `uql/lock` row. # MongoDB > Run UQL on MongoDB with the same entities and queries you use on SQL, and where the two differ. Source: https://uql-orm.dev/mongodb Your entities and queries run on MongoDB unchanged. This page covers only what works differently there. ## Install and connect ```sh npm install uql-orm mongodb ``` ```ts import { MongodbQuerierPool } from 'uql-orm/mongodb'; export const pool = new MongodbQuerierPool(process.env.MONGO_URL!, { maxPoolSize: 10, }); ``` The second argument takes the driver’s `MongoClientOptions`, and the third takes UQL’s [options](https://uql-orm.dev/pool.md#one-per-process). Call `pool.end()` to close the client. ## Ids Your key field (`.id()`) is MongoDB’s `_id`. An `ObjectId` reaches your code as a hex string; any other id, such as a UUID, is stored as you give it. A foreign key works the same way, whether `f.references()` or a relation declares it. Composite keys are not supported. ### Generated keys MongoDB can only generate `ObjectId`s, so a key you leave to the database must be a `String`: | Declaration | On MongoDB | | - | - | | `f.string().id()` | MongoDB generates an `ObjectId` | | `f.string().id().onInsert(uuidv7)` | your code generates it, on every engine | | `f.number().id()` | yours to supply, or an `onInsert` | ## Relations [`$populate`](https://uql-orm.dev/querying/relations.md) runs as a `$lookup`. A query on the entity’s own fields is a plain `find`; filtering on a relation, a [relation aggregate](https://uql-orm.dev/entities/computed-fields.md#relation-aggregates) or sorting by a related field makes it an aggregation pipeline instead. To [sort by a related field](https://uql-orm.dev/querying/relations.md#sorting-by-related-fields), `$populate` every relation along its path: UQL never adds a `$lookup` you didn’t ask for. Some `updateMany` and `deleteMany` calls read the matching ids first, or write a cascade: those filtered through a relation, paged, cascading, running hooks, or using `returning`. They run as their steps; open a [transaction](https://uql-orm.dev/querying/transactions.md) where the whole must land or none of it, which needs a [replica set](#transactions-need-a-replica-set). A [`@Computed`](https://uql-orm.dev/entities/computed-fields.md) field written in SQL can’t run on MongoDB. Naming it in `$select`, `$where` or `$sort` throws; anywhere else it is skipped. ## Transactions need a replica set MongoDB runs transactions only on a replica set or a sharded cluster. For development, one node is enough: ```sh docker run -p 27017:27017 mongo --replSet rs0 --bind_ip_all # then, once: mongosh --eval 'rs.initiate()' ``` There are no savepoints, so a [nested `transaction()`](https://uql-orm.dev/querying/transactions.md#nesting) throws, and `isolationLevel` is ignored. To make a raw driver call part of the transaction, pass it the querier’s session: ```ts await pool.transaction(async (querier) => { await querier.insertOne(Order, order); await querier.db .collection('audit') .insertOne({ order: order.id }, { session: querier.session }); }); ``` ## Search and streaming **Full-text search** needs a `text` index, which a `fulltext` index creates. The index sets the fields, weights and language, so `$text` ignores `$fields`. `$sort: { $text }` ranks by `textScore`. **Vector search** runs Atlas `$vectorSearch` over a `type: 'vectorSearch'` index, which migrations create, and `$candidates` sets `numCandidates`. Atlas cannot filter by distance, so `$near` throws: project the distance with the `$sort`’s `$project` (lower is nearer, as on SQL) and filter on it instead. Ranking by a [related row’s vector](https://uql-orm.dev/querying/semantic-search.md#ranking-by-a-related-row) works without Atlas. **`findManyStream`** reads through the same cursor as `findMany`, populated relations included. ## Checks and enums [Checks and enums](https://uql-orm.dev/entities/enum-checks.md) become the collection’s validator: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ checks: (task, check) => [check({ priority: { $gte: 0 } })] }) class Task { @Field(f.string().id()) id?: string; @Field(f.enum(['open', 'closed']).nullable()) status?: | 'open' | 'closed' | null; @Field(f.number().nullable()) priority?: number | null; } // validator: { $and: [{ priority: { $gte: 0 } }, { status: { $in: ['open', 'closed', null] } }] } ``` An enum lets a field be missing or `null`; a check doesn’t. The check above rejects a document with no `priority`, so where the field is optional, write `$or: [{ priority: null }, { priority: { $gte: 0 } }]`. A check can’t use `sql` or compare a `Date`, `bigint` or `ObjectId`. A rejected write throws a `checkViolation` [error](https://uql-orm.dev/querying/errors.md). UQL owns the validator: `generate:entities` and `sync` with `safe: false` replace or remove it, while safe mode only adds one. It applies to new writes, not to documents already stored. ## Migrations [Migrations](https://uql-orm.dev/migrations.md) use the same commands, written against the database handle: - `generate` scaffolds a migration typed on `MongoQuerier`. `generate:entities` writes collections, validators and indexes as driver calls, a [partial index’s](https://uql-orm.dev/entities/indexes.md#partial-indexes) `where` becoming its `partialFilterExpression`. - History is kept in the `uql_migrations` collection (set by `tableName`), which also [holds the lock](https://uql-orm.dev/migrations.md#several-instances-at-once). - Migrations don’t run in a transaction. One that fails halfway keeps what it did and is not recorded, so write each step to be safe to rerun. - The [migration builder](https://uql-orm.dev/migrations/builder.md) supports `createTable` (indexes only), `dropTable`, `renameTable`, `createIndex` and `dropIndex`. Columns, foreign keys and `sql` throw. - `drift:check` isn’t supported; `sync --dry-run` prints the index and validator changes instead. ```ts import { defineBuilderMigration } from 'uql-orm/migrate'; import type { MongoQuerier } from 'uql-orm/mongodb'; export default defineBuilderMigration({ async up(m) { await m.renameTable('users', 'members'); await m.createIndex('members', ['email'], { unique: true }); }, async down(m) { await m.dropIndex('members', 'members__email_idx'); await m.renameTable('members', 'users'); }, }); ``` To change field data, write the migration with the driver: ```ts import { defineMigration } from 'uql-orm/migrate'; import type { MongoQuerier } from 'uql-orm/mongodb'; export default defineMigration({ async up(querier) { await querier.db .collection('users') .updateMany({ active: { $exists: false } }, { $set: { active: true } }); }, async down(querier) { await querier.db .collection('users') .updateMany({}, { $unset: { active: '' } }); }, }); ``` ## Moving to SQL The same entities and queries run on a SQL pool, and moving off MongoDB changes no query. You mirror the writes, copy the data, compare the reads, then switch. [The walkthrough](https://uql-orm.dev/blog/mongodb-to-postgresql.md) does it for a Mongoose app. Declare the entities over the documents as they are stored. A Mongoose `ref` keeps its stored name on the reference field beside the relation, so the documents need no rewrite: ```ts import { ObjectId } from 'mongodb'; import { f, Entity, Field, ManyToOne } from 'uql-orm'; @Entity({ name: 'users' }) export class User { @Field( f .string() .id() .onInsert(() => new ObjectId().toHexString()), ) id?: string; @Field(f.string().nullable()) name?: string | null; } @Entity({ name: 'posts' }) export class Post { @Field( f .string() .id() .onInsert(() => new ObjectId().toHexString()), ) id?: string; @Field( f .references(() => User) .nullable() .name('author'), ) authorId?: string | null; @ManyToOne(() => User, { references: (post) => post.authorId }) author?: User; } ``` Create the tables with [`sync` or a migration](https://uql-orm.dev/migrations.md), then send every write to both databases. MongoDB stays the source of truth, and a failure on SQL is only logged: ```ts import type { QuerierPool } from 'uql-orm'; import { MongodbQuerierPool } from 'uql-orm/mongodb'; import { PgQuerierPool } from 'uql-orm/postgres'; import { Post, User } from './entities.js'; const mongo = new MongodbQuerierPool(process.env.MONGO_URL!); const pg = new PgQuerierPool({ connectionString: process.env.DATABASE_URL }); async function mirror(write: (pool: QuerierPool) => Promise): Promise { const result = await write(mongo); await write(pg).catch((error) => console.warn('mirror failed', error)); return result; } await mirror((pool) => pool.insertOne(User, { id: new ObjectId().toHexString(), name: 'Ada' }), ); ``` Inserts name their id up front, and both databases store that id. Port a collection’s writes before mirroring it, since a mirror only sees writes that go through UQL. Then copy each collection, parents before the collections that reference them. `saveMany` upserts each row by its id, which makes the copy safe to run again at any time. Each run repairs whatever a failed mirror missed. ```ts async function copy(entity: new () => E, batchSize = 1000) { let batch: E[] = []; for await (const row of mongo.findManyStream(entity, {})) { batch.push(row); if (batch.length === batchSize) { await pg.saveMany(entity, batch); batch = []; } } if (batch.length) { await pg.saveMany(entity, batch); } } await copy(User); await copy(Post); ``` Ids keep their `ObjectId` hex text, so references and URLs still work, and the key’s `onInsert` gives a row written on SQL an id of the same form. Before moving reads, run each one on both databases and compare the results: ```ts import { isDeepStrictEqual } from 'node:util'; // MongoDB omits a missing field and SQL returns null: drop both. const plain = (rows: unknown) => JSON.parse(JSON.stringify(rows, (_key, value) => value ?? undefined)); async function shadow(read: (pool: QuerierPool) => Promise): Promise { const [served, shadowed] = await Promise.all([read(mongo), read(pg)]); if (!isDeepStrictEqual(plain(served), plain(shadowed))) { console.warn('shadow read differs', { served, shadowed }); } return served; } const posts = await shadow((pool) => pool.findMany(Post, { $select: { id: true, title: true }, $populate: { author: { $select: { name: true } } }, $where: { title: { $startsWith: 'Launch' } }, $sort: { id: 'asc' }, }), ); ``` Sort every compared read: neither database guarantees an order otherwise. Once the results agree under real traffic, serve reads from SQL. Then swap the two pools in `mirror`. SQL takes each write first, and MongoDB stays current in case you need to roll back. Retire the collections once nothing reads them. Expect two differences along the way: [`null` comparisons](https://uql-orm.dev/querying/comparison-operators.md#null-is-compared-as-the-engine-compares-it), and SQL foreign keys rejecting references MongoDB left dangling. # Microsoft SQL Server > Run UQL on SQL Server 2017 and up with the mssql driver, and what behaves differently there. Source: https://uql-orm.dev/mssql UQL runs on SQL Server 2017 and up through the pure-JavaScript [`mssql`](https://www.npmjs.com/package/mssql) driver. ## Install and connect ```sh npm install uql-orm mssql ``` ```ts import { MsSqlQuerierPool } from 'uql-orm/mssql'; export const pool = new MsSqlQuerierPool({ server: 'localhost', database: 'app', user: 'app', password: process.env.DB_PASSWORD, options: { encrypt: true, trustServerCertificate: false }, }); ``` The pool takes `mssql`’s own `config`. See [Pool](https://uql-orm.dev/pool.md) for sizing and shutdown. > **Turn on snapshot isolation** > > SQL Server’s default `READ COMMITTED` takes shared read locks, so concurrent ORM work deadlocks where other engines would not. Run this once per database: > > ```sql title="SQL Server" > ALTER DATABASE app SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE; > ``` ## What differs Strings are always `NVARCHAR`, and comparisons follow the database collation, case-insensitive by default. `$regex` is case-sensitive and needs SQL Server 2025 at compatibility level 170 (`REGEXP_LIKE`). `$text` throws, since `CONTAINS` needs a full-text catalog UQL does not create. Vector search needs SQL Server 2025 and a declared `dimensions`. It is exact, computing every distance with `VECTOR_DISTANCE`, because the DiskANN index is still in preview. `OUTPUT INSERTED` returns one id per row, so `insertMany` ids are exact. Writing an explicit value into an identity column works too; UQL wraps that insert in `SET IDENTITY_INSERT`. The server refuses two cascade paths to one table (error 1785) and has no `RESTRICT`; the default `NO ACTION` avoids both. The `uuidv7()` SQL value throws, so generate v7 ids in code with `onInsert`. [Streaming](https://uql-orm.dev/querying/streaming.md) uses the driver’s own row stream. ## Migrations [Migrations](https://uql-orm.dev/migrations.md) diff the schema like on any other engine. SQL Server names column defaults, `CHECK` and `UNIQUE` constraints itself, so UQL drops them before dropping a column and restores the default after a retype. Renames use `sp_rename`, and creates are guarded by catalog lookups in place of `IF NOT EXISTS`. # MySQL & MariaDB > Run UQL on MySQL with mysql2 or on MariaDB with its own driver, and the differences between them. Source: https://uql-orm.dev/mysql MySQL and MariaDB have separate entry points, because the SQL each needs differs. Pick the one that matches your server. | Server | Entry point | Driver | | - | - | - | | MySQL 8.0.19+ | `uql-orm/mysql` | `mysql2` | | MariaDB 10.5+ | `uql-orm/mariadb` | `mariadb` | | Either, under Bun | [`uql-orm/bun-sql`](https://uql-orm.dev/bun-sql.md) | built in | ## Install and connect ```sh npm install uql-orm mysql2 # or: mariadb ``` ```ts import { MySql2QuerierPool } from 'uql-orm/mysql'; // MariaDB: import { MariadbQuerierPool } from 'uql-orm/mariadb'; export const pool = new MySql2QuerierPool({ host: 'localhost', user: 'app', password: process.env.DB_PASSWORD, database: 'app', connectionLimit: 10, }); ``` Both pools take their driver’s own config and [stream](https://uql-orm.dev/querying/streaming.md) natively. UQL sets the session time zone to UTC, so dates read back as the instant they hold. ## Ids after a multi-row insert MariaDB has `INSERT ... RETURNING`, so `insertMany` returns exact ids. MySQL reports only the first id, and UQL infers the rest from `auto_increment_increment`. > **Inferred ids on MySQL** > > The inference holds under `innodb_autoinc_lock_mode` 0 or 1. MySQL 8 defaults to 2, where a concurrent insert into the same table can leave gaps in your ids. On a hot table, set lock mode 1 or insert row by row. ## Schema and writes All four isolation levels work; the default is `repeatable read`. Upserts compile to `INSERT ... ON DUPLICATE KEY UPDATE` (or `INSERT IGNORE` when there is nothing to update). The server matches on any unique index, not only the conflict keys you passed, and an upsert’s `$where` guards each column the update sets, so it may read at most one of the columns the update sets. A query binds at most 65,535 values, so UQL splits a large `insertMany` into chunks. A populated to-many is aggregated in the parent’s statement, which raises `group_concat_max_len` for itself so long relations are not cut off. ## JSON and arrays Arrays are stored as JSON and queried with the [JSON operators](https://uql-orm.dev/querying/json.md). Paths compile to `->` / `->>` on MySQL and `JSON_VALUE()` / `JSON_EXTRACT()` on MariaDB. A JSON number compares as a `DOUBLE`. On MySQL a [JSON path index](https://uql-orm.dev/entities/indexes.md#json-indexes) can serve that; MariaDB has no expression indexes. Sorting by a JSON path orders numbers by value on both, MariaDB breaking ties by text. `$elemMatch` on one value, or one of several, compiles to `JSON_CONTAINS()` (or `JSON_OVERLAPS()` on MySQL), which an index over the array’s elements, `type: [String]`, serves. Anything more uses `JSON_TABLE`. ## Full-text search `$text` compiles to `MATCH(...) AGAINST(...)`, which needs a `FULLTEXT` index over exactly the searched columns, in order: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (post, index) => [ index([post.title, post.body], { type: 'fulltext' }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) body?: string | null; } ``` [Migrations](https://uql-orm.dev/migrations.md) create it, running `OPTIMIZE TABLE` on a table that has rows. A [weighted index](https://uql-orm.dev/querying/full-text.md#column-weights) also gets one `FULLTEXT` index per heavier column, since `MATCH` scores a column only through its own index. ## Vector search MariaDB 11.7+ has native `VECTOR(n)` columns and `VECTOR INDEX`, so [semantic search](https://uql-orm.dev/querying/semantic-search.md) works with no extension. MySQL has no distance function outside HeatWave, so UQL stores vectors there as JSON and cannot search them. # PGlite > Run UQL on PGlite, Postgres compiled to WASM and running inside your process. Source: https://uql-orm.dev/pglite [PGlite](https://pglite.dev) is Postgres compiled to WebAssembly, running inside your process with no server, container or port. UQL treats it as Postgres. Use it for tests, where each file gets a fresh database in milliseconds, and for local development on your production dialect. ## Install and connect ```sh npm install uql-orm @electric-sql/pglite ``` UQL needs PGlite 0.5.10 or later. ```ts import { PgliteQuerierPool } from 'uql-orm/pglite'; export const pool = new PgliteQuerierPool(); // in memory ``` Pass a directory to keep the data, and PGlite’s own options second. On disk, `relaxedDurability` stops PGlite from waiting on a flush after every statement inside a transaction; the data is still written: ```ts const pool = new PgliteQuerierPool('file://./pgdata', { relaxedDurability: true, }); ``` ## Vector search pgvector is a separate bundle that PGlite loads at startup: ```sh npm install @electric-sql/pglite-pgvector ``` ```ts import { vector } from '@electric-sql/pglite-pgvector'; const pool = new PgliteQuerierPool('memory://', { extensions: { vector } }); ``` [Vector search](https://uql-orm.dev/querying/semantic-search.md) then works as on a server, `halfvec` and `sparsevec` included. The extension pins an exact `@electric-sql/pglite` version, so upgrade both together. ## One connection, and what follows from it PGlite has a single connection that every querier shares. A transaction holds the whole database, and other queriers wait until it ends. Give work that must run concurrently its own pool, and so its own database; a test suite or a single-user dev session is unaffected. `$lock` emits `SELECT ... FOR UPDATE`, but no second transaction can contend with it, so test row-locking behaviour on a Postgres server. `findManyStream` pages through a `DECLARE`/`FETCH` cursor, inside a transaction of its own if you have none, which blocks the database until the loop ends. ## Differences from `uql-orm/postgres` A `BYTEA` column reads back as a `Uint8Array`, not a `Buffer`, so `instanceof Buffer` fails. Migration runs [hold their lock](https://uql-orm.dev/migrations.md#several-instances-at-once) as a `uql/lock` record, since queriers share a session. Otherwise the two are interchangeable: both report the `postgres` dialect, so migrations and [`drift:check`](https://uql-orm.dev/migrations.md#drift-detection) carry across. # PostgreSQL > Run UQL on PostgreSQL with node-postgres, including RLS, streaming and Cloudflare Hyperdrive. Source: https://uql-orm.dev/postgres PostgreSQL is UQL’s most complete backend, with native arrays, [JSON operators](https://uql-orm.dev/querying/json.md), [full-text](https://uql-orm.dev/querying/full-text.md) and pgvector [semantic search](https://uql-orm.dev/querying/semantic-search.md), and `RETURNING` for generated ids. ## Install and connect ```sh npm install uql-orm pg ``` ```ts import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, max: 10, }); ``` The pool takes node-postgres’ `PoolConfig`, with `keepAlive: true` by default. See [Pool](https://uql-orm.dev/pool.md) for sizing and shutdown, and [PGlite](https://uql-orm.dev/pglite.md) for the same dialect in-process, for tests. [Streaming](https://uql-orm.dev/querying/streaming.md) also needs `npm install pg-query-stream`, which UQL loads on first use. ## Transactions All four isolation levels work. `serializable` and `repeatable read` can fail with `40001`; [retry the whole transaction](https://uql-orm.dev/querying/errors.md#retrying-a-transaction), never a statement inside it. ```ts await pool.transaction(run, { isolationLevel: 'serializable' }); ``` Behind PgBouncer or another transaction-mode pooler, session state does not carry between statements, so keep `SET LOCAL`, advisory locks and temp tables inside one [`transaction`](https://uql-orm.dev/querying/transactions.md) callback. ## Row-level security RLS backs up UQL’s [`security` filters](https://uql-orm.dev/multi-tenancy.md) and also covers raw SQL. Set the tenant inside the transaction: ```ts await pool.transaction(async (querier) => { await querier.run`SELECT set_config('app.tenant_id', ${tenantId}, true)`; return querier.findMany(Invoice, { $limit: 50 }); }); ``` > **Keep the true** > > It makes the setting local to the transaction. Without it the tenant stays on the pooled connection, and the next request to borrow it inherits it. ## Cloudflare Hyperdrive Hyperdrive keeps a warm Postgres pool at the edge for Workers, and `pg` runs on it unchanged. It needs `nodejs_compat` and a compatibility date of `2024-09-23` or later: ```jsonc title="wrangler.jsonc" { "compatibility_date": "2026-08-01", "compatibility_flags": ["nodejs_compat"], "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "" }], } ``` The binding exists only inside a request, so build the pool there, with a small `max` since Hyperdrive does the real pooling: ```ts title="src/index.ts" import { PgQuerierPool } from 'uql-orm/postgres'; import { Item } from './models'; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const pool = new PgQuerierPool({ connectionString: env.HYPERDRIVE.connectionString, max: 5, }); try { return Response.json(await pool.findMany(Item, { $limit: 20 })); } finally { ctx.waitUntil(pool.end()); } }, }; ``` Run [migrations](https://uql-orm.dev/migrations.md) from CI against the database’s own hostname, not through the binding. ## Related pages [Bun SQL](https://uql-orm.dev/bun-sql.md) drops `pg` under Bun. See also [CockroachDB](https://uql-orm.dev/cockroachdb.md), [Supabase](https://uql-orm.dev/supabase.md), [Neon](https://uql-orm.dev/serverless.md#neon) and [Serverless](https://uql-orm.dev/serverless.md). # SQLite > Run UQL on SQLite with Node's built-in node:sqlite, better-sqlite3, or bun:sqlite. Source: https://uql-orm.dev/sqlite UQL runs on a local SQLite file through two pools that produce the same SQL and results. For a remote database, see [Turso & libSQL](https://uql-orm.dev/turso.md) or [Cloudflare D1](https://uql-orm.dev/cloudflare-d1.md). If SQLite stands in for a production Postgres, [PGlite](https://uql-orm.dev/pglite.md) is real Postgres with no server. | Pool | Driver | Install | | - | - | - | | `NodeSqliteQuerierPool` | Node’s built-in `node:sqlite` | nothing | | `SqliteQuerierPool` | `better-sqlite3`, or `bun:sqlite` under Bun | `npm i better-sqlite3` (Bun needs nothing) | ## Install and connect `NodeSqliteQuerierPool` needs no package and no native build, which helps in slim images and CI: ```ts import { NodeSqliteQuerierPool } from 'uql-orm/sqlite'; export const pool = new NodeSqliteQuerierPool('app.db'); ``` `SqliteQuerierPool` is faster on reads (about 1.3x on point reads in our tests, though `node:sqlite` inserts about 20% faster), so prefer it when throughput matters. The same code uses `bun:sqlite` under Bun: ```ts import { SqliteQuerierPool } from 'uql-orm/sqlite'; export const pool = new SqliteQuerierPool('app.db'); ``` Both default to `':memory:'` and take the driver’s options second. Each connection opens with `journal_mode = WAL` and `foreign_keys = ON`, so `onDelete: 'CASCADE'` works. Runnable apps: [Node](https://github.com/rogerpadilla/uql/tree/main/examples/node) and [Bun](https://github.com/rogerpadilla/uql/tree/main/examples/bun). ## Vector and full-text search SQLite has no vector functions, so [semantic search](https://uql-orm.dev/querying/semantic-search.md) needs the `sqlite-vec` extension, loaded through `extensions`: ```ts import { getLoadablePath } from 'sqlite-vec'; const pool = new NodeSqliteQuerierPool('app.db', { extensions: [getLoadablePath()], }); ``` `$text` matches an [FTS5](https://sqlite.org/fts5.html) virtual table. Migrations do not create one: create it yourself and declare an entity over it, and `$text` and `$sort: { $text }` (ranked by `BM25`) work as on other engines. See [Full-text search](https://uql-orm.dev/querying/full-text.md). ## What is not supported SQLite in the browser, such as `sql.js`. Run Postgres in the tab with [PGlite](https://uql-orm.dev/browser.md#postgres-in-the-tab) instead. ## Good to know A pool holds one connection, so a transaction locks the whole database and other queriers wait until it ends. Give work that must run concurrently its own pool. `$regex` compiles to `REGEXP`, which UQL defines on `better-sqlite3`, `node:sqlite` and, from Bun 1.4.4, `bun:sqlite`. Ordering a populated to-many needs SQLite 3.44. A populated `float` keeps 15 significant digits on SQLite 3.51 and 17 on 3.53. Changing a column’s type, nullability or default [rebuilds the table](https://uql-orm.dev/migrations.md#sqlite-rebuilds-the-table). # Supabase > Run UQL on Supabase Postgres, pick the right connection endpoint, and layer UQL security filters over RLS. Source: https://uql-orm.dev/supabase Supabase is Postgres, so the [PostgreSQL](https://uql-orm.dev/postgres.md) page applies unchanged. What is specific to Supabase is which endpoint you connect to and how tenant scoping meets RLS. ```sh npm install uql-orm pg ``` ## Which connection string | Endpoint | Port | Use it for | | - | - | - | | `db..supabase.co` | 5432 | Migrations, `pg_dump`, long-lived servers with IPv6 | | `aws-.pooler.supabase.com` (session mode) | 5432 | The same, from an IPv4-only network | | `aws-.pooler.supabase.com` (transaction mode) | 6543 | Serverless and many short-lived connections | The direct hostname is IPv6-only unless you buy the IPv4 add-on, which is the usual cause of `ENETUNREACH` from CI or a container. ```ts import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, max: 10, }); ``` Transaction mode hands you a different backend connection between statements, so session state does not survive and prepared statements fail. UQL prepares none of its own; if you enable them in `pg`, turn them off for that endpoint. Run [migrations](https://uql-orm.dev/migrations.md) on the direct endpoint: ```ts title="uql.config.ts" import type { Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; import { Company, Invoice } from './entities.js'; export default { pool: new PgQuerierPool({ connectionString: process.env.DIRECT_DATABASE_URL, }), entities: [Company, Invoice], migrationsPath: './migrations', } satisfies Config; ``` ## Row-level security RLS policies read `auth.uid()` and `auth.jwt()`, which Supabase’s API layer fills. Connecting with `pg` skips that layer: as the `postgres` role, no policy applies. Two layers restore scoping, and they stack. A UQL [security filter](https://uql-orm.dev/multi-tenancy.md) is AND-merged into every query the ORM builds, cannot be turned off by a client, and fails closed when the context is missing: ```ts import { Entity, f, Field } from 'uql-orm'; declare module 'uql-orm' { interface UqlContext { orgId?: string; } } @Entity({ filters: { tenant: { where: (ctx) => ctx?.orgId != null ? { organizationId: ctx.orgId } : undefined, security: true, }, }, }) export class Invoice { @Field(f.number().autoIncrement()) id?: number; @Field(f.uuid()) organizationId?: string; } ``` RLS is the backstop for raw SQL and anything else that skips the ORM. Connect as a role the policies apply to, and set the claims inside the transaction: ```ts await pool.transaction(async (querier) => { await querier.run`SELECT set_config('request.jwt.claims', ${JSON.stringify(claims)}, true)`; return querier.findMany(Invoice, { $limit: 50 }); }); ``` > **Keep the true** > > It scopes the setting to the transaction. Without it the claims stay on the pooled connection, and the next request inherits the previous caller’s identity. ## The rest of Supabase UQL replaces `supabase-js` for data access only; Auth, Storage and Realtime keep working, and verified Auth claims can become the UQL context. pgvector is installed on every project, so [semantic search](https://uql-orm.dev/querying/semantic-search.md) needs only the [index](https://uql-orm.dev/entities/indexes.md) your migration creates. Edge Functions run on Deno without TCP, so `pg` cannot connect there. For functions that freeze between invocations, see [Serverless](https://uql-orm.dev/serverless.md). # Turso & LibSQL > Run UQL on Turso Cloud from edge runtimes, on the embedded Turso engine, or on libSQL. Source: https://uql-orm.dev/turso Turso Cloud, the embedded Turso engine and libSQL are all SQLite underneath, so entities, queries and [migrations](https://uql-orm.dev/migrations.md) are the same on each. Only the pool changes. | Package | Entry point | Use it for | | - | - | - | | `@tursodatabase/serverless` | `uql-orm/turso` | Turso Cloud over `fetch()`, including Cloudflare Workers and Vercel Edge | | `@tursodatabase/database` | `uql-orm/turso/local` | The embedded Rust engine, for local-first and desktop apps | | `@libsql/client` | `uql-orm/libsql` | libSQL and sqld databases, embedded replicas, and edge clients | A Turso Cloud database runs libSQL (a fork of SQLite’s C source) unless it was created as `tursodb`, which runs the Rust engine, so `uql-orm/turso` emits only SQL both accept. ## Turso Cloud ```sh npm install uql-orm @tursodatabase/serverless ``` ```ts import { TursoQuerierPool } from 'uql-orm/turso'; const pool = new TursoQuerierPool({ url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN, }); ``` The driver uses `fetch()`, has no native binary and loads on the first query, so the pool can sit at module scope in a Worker. Keep `uql-orm/turso/local` out of edge bundles. Each querier gets its own server session, so queriers never wait on each other, and [streaming](https://uql-orm.dev/querying/streaming.md) reads rows as the server produces them. Driver options such as `requestHeaders` pass through. ## Embedded Turso ```sh npm install uql-orm @tursodatabase/database ``` ```ts import { TursoLocalQuerierPool } from 'uql-orm/turso/local'; const pool = new TursoLocalQuerierPool('app.db'); ``` It defaults to `':memory:'`, takes the engine’s own options second (`readonly`, `timeout`, `encryption` and the rest), and streams natively. ## libSQL ```sh npm install uql-orm @libsql/client ``` ```ts import { LibsqlQuerierPool } from 'uql-orm/libsql'; const pool = new LibsqlQuerierPool({ url: process.env.LIBSQL_URL!, authToken: process.env.LIBSQL_AUTH_TOKEN, }); ``` For an embedded replica, migrations must reach the remote, or the next sync loses the DDL. Pass `syncUrl` and the migrator connects there for schema changes: ```ts const pool = new LibsqlQuerierPool({ url: 'file:./local.db', syncUrl: process.env.LIBSQL_SYNC_URL, authToken: process.env.LIBSQL_AUTH_TOKEN, }); ``` You can also pass a client you built, such as `@libsql/client/web` or `@libsql/client-wasm`. Every querier shares it, and `pool.end()` leaves it open. > **Build your own client with intMode: 'bigint'** > > Without it, an integer past 2^53 throws instead of reading exactly. UQL sets it on clients it builds, not on yours. ```ts import { createClient } from '@libsql/client/web'; const pool = new LibsqlQuerierPool( createClient({ url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN, intMode: 'bigint', }), ); ``` ## Vector search Vectors are built in, so [semantic search](https://uql-orm.dev/querying/semantic-search.md) needs no extension. A metric the engine lacks throws: | | `cosine`, `l2` | `inner` | [Vector index](https://uql-orm.dev/querying/semantic-search.md#vector-indexes) | | - | - | - | - | | libSQL | yes | no | DiskANN | | Turso Cloud | yes | no | DiskANN on libSQL; refused on `tursodb` | | Embedded Turso | yes | yes | none: a plain index, and searches scan | ## Good to know SQLite-family indexes take no `USING` clause, so UQL drops an index `type` such as `hnsw` and an entity written for Postgres migrates unchanged. The Rust engine cannot read the table a write changes from inside a subquery, so on both Turso drivers an `updateMany` or `deleteMany` filtered by a relation first reads the matching ids. Neither libSQL nor Turso orders `json_group_array`, so a populated to-many keeps the subquery’s order. ## What the ORM adds on top of the driver Measured on the embedded engine against `@tursodatabase/database` directly, with the same prepared SQL: | Operation | Raw driver | Through UQL | Difference | | - | - | - | - | | Read by primary key | 3.4 us | 19.4 us | +16 us | | Insert 10 rows | 128 us | 157 us | +29 us | | Filtered top-10 over \~11k rows | 2.91 ms | 2.99 ms | +0.08 ms | Median of 5 runs of 200 iterations, in-memory, Node 24 on an M4 Pro. UQL adds tens of microseconds for building SQL and hydrating entities, which an HTTP round trip to Turso Cloud dwarfs. # HTTP (any framework) > Serve your entities to a client from any framework, over HTTP, tRPC or oRPC, with one API. Source: https://uql-orm.dev/http `uql-orm/http` serves your entities to a client: one API takes a client’s call, checks what it may reach, scopes it to the signed-in user and runs it in a transaction where it writes. HTTP is the transport uql ships, and any other (a tRPC or oRPC procedure, a server action) calls the same API. The [client](https://uql-orm.dev/browser.md) sends the same query you write on the server: [one query, every transport](https://uql-orm.dev/querying/querier.md#the-same-query-every-transport). ## The API ```ts import { createApi, toFetchHandler } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; const api = createApi({ pool, include: [User, Post] }); const handler = toFetchHandler(api); ``` `createApi` takes the options every transport shares; a transport only carries calls to `api.call(call, context)`, which takes a call as JSON and answers as JSON. `include` is required and lists the only entities a call can reach. A `$populate`, filter, sort or write that leads through a relation to an entity outside it is a `403`, so an entity holding secrets stays unreachable unless you list it. Relations a [middleware](#middleware) adds are allowed. ## Transports `toFetchHandler(api)` returns a web-standard `(request: Request) => Promise`. Mount it on a catch-all under the API’s base, `/api/v1` here so a later version can sit beside it: it reads the last two segments of the path as the entity and the op. Express takes [`toExpress(api)`](https://uql-orm.dev/express.md) instead, and any other framework `toRequestHandler(api)`, which takes a plain request object and answers `{ status, body, headers? }`, or `undefined` for a route the API does not serve (see [Fastify](https://uql-orm.dev/fastify.md)). A procedure calls the API itself ([tRPC](https://uql-orm.dev/trpc.md), [oRPC](https://uql-orm.dev/orpc.md)). | Runtime | Mount | | - | - | | [Hono](https://uql-orm.dev/hono.md), [Elysia](https://uql-orm.dev/elysia.md) | `app.mount('/api/v1', handler)` | | `Bun.serve` | `{ routes: { '/api/v1/*': handler } }` | | Cloudflare Workers | `export default { fetch: handler }` | | [Next.js](https://uql-orm.dev/nextjs.md), [Astro](https://uql-orm.dev/astro.md), [React Router](https://uql-orm.dev/react-router.md), [TanStack Start](https://uql-orm.dev/tanstack-start.md) | a catch-all route under `/api/v1` | | Nitro / h3 | `fromWebHandler(handler)`; on h3 v2, `(event) => handler(event.req)` | ## What a client may do Nothing is exposed by default: defining an entity serves nothing, and a client reaches only the entities an API’s `include` names, through a relation too. What a client may do to one is its definition’s `wire`, every operation where unset: ```ts import { defineEntity, f } from 'uql-orm'; export const User = defineEntity({ name: 'User', wire: ['read', 'insert', 'update'], fields: { id: f.number().autoIncrement(), name: f.string(), email: f.string().wire(['read']), password: f.string().wire(['insert']), }, }); const api = createApi({ pool, include: [Post, User] }); ``` - An entity’s `wire` is what it takes: `'read'`, `'insert'`, `'update'`, `'delete'`. A save needs `insert` and `update`, and so does a relation a write nests, which the cascade saves; an update nesting a to-many also deletes the rows it no longer lists, so it needs `delete` on the target. `wire: false` keeps an entity off every API, and `createApi` refuses one in `include`. A subclass declaring none takes its base’s. - A field’s `wire` is on its builder, a relation’s in its options: `'read'`, `'insert'` or `'update'`, or `false` for nothing. A decorated class says the same, `@Entity({ wire })`, `@Field(f.string().wire(false))`, `@OneToMany(() => Session, { mappedBy, wire: false })`. - It holds wherever the entity is reached: hide `address` on `Employee` and `/company/findMany` populating `employees` leaves it out too. - `read` is every way of reading a value: `$select`, `$where`, `$sort`, `$count`, a populated relation. Filtering by a hidden `password` would read it a character at a time, so it is refused like selecting it, and so is a JSON path into a hidden column (`'meta.plan'`). - `.eager(false)` is not a guard: it leaves a field out of a read naming no fields, and a client’s `$select: { password: true }` still reads it. Hide a secret from clients with `.wire(false)`. - A write the querier would drop, to a computed field or an update of an `updatable(false)` one, is refused rather than ignored. - A call naming what it may not reach is a `403` naming the path (`'creator.password' cannot be read through this API`), and a read naming no `$select` leaves out what it may not read, at every depth it populates. Every API serving an entity shows the same members. To narrow one API further, refuse in its middleware (below). ## The pool The API runs on the [pool](https://uql-orm.dev/pool.md) you pass. Usually one module builds it and is also what [`uql-migrate`](https://uql-orm.dev/migrations.md) reads: ```ts title="uql.config.ts" import type { Config } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; import { Post, User } from './shared/models/index.js'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, }); export default { pool, entities: [User, Post] } satisfies Config; ``` For a database per tenant, pass a function instead. It gets the transport’s context and the context [`contextOf`](#tenant-scoping) resolved, and runs only after every middleware passes: ```ts const api = createApi({ include: [User, Post], contextOf: (request) => ({ tenantId: tenantOf(request) }), pool: (_request, { tenantId }) => poolFor(tenantId as string), }); ``` ## Wire protocol Every call is `{base}/{entity}/{op}`: the entity at its kebab-cased class name, so `UserProfile` lives at `/user-profile`, and the op a querier method’s name: `findMany`, `findManyAndCount`, `findManyPage`, `findOne`, `findOneById`, `count`, `insertOne`, `insertMany`, `saveOne`, `saveMany`, `updateMany`, `updateOneById`, `deleteMany`, `deleteOneById`. The rest of the call is one JSON object of named keys: | Key | Holds | Taken by | | - | - | - | | `id` | the key of the row, whichever field carries `.id()` | `findOneById`, `updateOneById`, `deleteOneById` | | `query` | the [query](https://uql-orm.dev/querying/querier.md) | every op but `insert*` and `save*` | | `payload` | a row, an array of rows, or an update’s changes | the writes | | `hardDelete` | `true` to delete a [soft-deleting](https://uql-orm.dev/entities/soft-delete.md) entity’s rows for good | `deleteMany`, `deleteOneById` | A read is a `GET` with that object URL-encoded in `?q=` (left out when empty), or a `QUERY` or `POST` with it as the body. A write is a `POST` with it as the body: ```http GET /api/v1/user/findMany?q={"query":{"$where":{"status":"active"},"$limit":20}} GET /api/v1/user/findOneById?q={"id":42} POST /api/v1/user/insertOne {"payload":{"email":"ann@example.com"}} POST /api/v1/user/updateOneById {"id":42,"payload":{"name":"Ann"}} POST /api/v1/user/deleteMany {"query":{"$where":{"status":"banned"}},"hardDelete":true} ``` `q` is shown unencoded. With curl: ```sh curl -G https://example.com/api/v1/user/findMany \ --data-urlencode 'q={"query":{"$where":{"status":"active"},"$limit":20}}' curl https://example.com/api/v1/user/insertOne \ -H 'content-type: application/json' \ -d '{"payload":{"email":"ann@example.com"}}' ``` A read also takes `HEAD`, answered as its `GET` without the body. What changes the result lives in the call; headers carry only what concerns the request: `Authorization`, keys, tracing. A body needs `content-type: application/json`, which a plain HTML form cannot send, so no cross-site form can write; any other is a `415`. A method the op does not take is a `405` with an `Allow` header, and an entity or op the API does not serve a `404`, both of `kind: 'usage'`. A key the op does not take is a `400`: an `id` on an op not by id, a `payload` on a read, a `query` on an insert or a save, a `hardDelete` on anything but a delete. Values are JSON-typed and never coerced, so `"$limit": "10"` is refused. Give a [page](https://uql-orm.dev/querying/pagination.md) a `$limit`. JSON holds no `Date` or `bigint`, so a `bigint` travels as its digits and a `Date` as its ISO text. The API reads a call’s filters and rows back by the entity, and the [client](https://uql-orm.dev/browser.md) reads results the same way, so a date stays a date and a wide integer exact on every engine. Each write runs in a transaction. Updates and deletes answer how many rows they changed. A delete [soft-deletes](https://uql-orm.dev/entities/soft-delete.md) where the entity can, unless the call says `hardDelete: true`, and a delete that names no rows is refused. `$lock` is refused too, since each call commits on its own. A success is a `200` with the result under `data`: what the pool’s method answers (`findManyAndCount` answers `[rows, count]`), which the [client](https://uql-orm.dev/browser.md) unwraps. A failure answers its HTTP `status`, its [error kind](https://uql-orm.dev/querying/errors.md) when it has one, and the `path` in the call that is at fault, so a form can point at the field: ```jsonc { "data": ... } { "error": { "message": "'password' cannot be read through this API", "status": 403, "kind": "security", "path": ["query", "$where", "password"] } } ``` A malformed call is a `400`, and so is a `$` key the query does not take, such as a misspelt clause or `$lock`, rather than being dropped and answering another read. So is a write [optimistic locking](https://uql-orm.dev/entities/optimistic-locking.md) refuses. A `security` [filter](https://uql-orm.dev/querying/filters.md) or [what a client may do](#what-a-client-may-do) refusing is a `403`, and a stale version a `409`. A duplicate or a missing referenced row answers `409 Conflict`, a not-null or check violation `400 Bad Request`, and a deadlock or serialization failure `503 Service Unavailable`, never with the driver’s message, which would leak table names and values. Only a UQL error answers its own status and message, a `UqlRequestError` a middleware throws included; any other error, whatever `status` it carries, is a `500 Internal Server Error`. `encodeCall(call, readMethod)` and `decodeRequest(request)` from `uql-orm/http` are the two halves of this protocol, for a client or a server of your own; a client in another language follows the rules above. ## HTTP QUERY (RFC 10008) `QUERY` carries a read’s call in the body like `POST`, so a large `$where` never hits a URL-length limit, while saying the request is safe and repeatable as a `GET` does. The handler accepts it, but your framework must route it. Hono and Elysia `.mount()`, `Bun.serve`, Express’s `toExpress`, `fastify.all` from Fastify 5.11, a TanStack Start `ANY` handler, and an Astro `ALL` export or [`src/fetch.ts`](https://uql-orm.dev/astro.md#auto-generated-crud) all do. Next.js route handlers and React Router resource routes take the standard verbs only; send their reads as `POST` when a URL grows too long. The [client](https://uql-orm.dev/browser.md#read-method) sends `GET` unless you choose another. ## Middleware A middleware runs around each call, before the database is touched, and can be async. It receives the call (`entity`, `op`, `id`, the decoded `query`, the `payload`, `hardDelete`), the transport’s context (the framework’s request), and `next`. Reshape the call before `next`, reshape what `next` resolves to, or throw to abort: a `UqlRequestError` answers its 4xx `status` and message, and any error UQL did not raise a generic `500`. ```ts import { UqlRequestError } from 'uql-orm'; import { type ApiMiddleware, createApi } from 'uql-orm/http'; const authenticated: ApiMiddleware = async (call, request, next) => { if (!(await authenticate(request.headers.get('authorization')))) { throw new UqlRequestError('unauthorized', 401); } return next(call); }; const api = createApi({ pool, include: [User], use: [authenticated] }); ``` An entity’s own middleware goes in its `serve`, typed by the entity, so it reads and writes its members; narrowing on `call.op` types the payload. It runs on that entity’s calls alone, after the API’s: ```ts import { type EntityMiddleware, serve } from 'uql-orm/http'; const stamped: EntityMiddleware = (call, request, next) => call.op === 'insertOne' ? next({ ...call, payload: { ...call.payload, authorId: userOf(request) } }) : next(call); const api = createApi({ pool, include: [serve(Post, { use: [stamped] })], use: [authenticated], }); ``` Middleware runs in order, first to last, after the call is checked against what a client may do: what a middleware adds is the server’s own. It sees results as the entity holds them, a `Date` as a `Date`. Hide a field with [`.wire(false)`](#what-a-client-may-do) rather than stripping it from results: a middleware stripping rows still lets a client filter by the field. ## Tenant scoping Don’t scope tenants by adding to `$where` in a middleware: that misses joined relations and does not fail closed. Pass `contextOf` and declare a `security` [filter](https://uql-orm.dev/querying/filters.md) instead. The whole call then runs inside `withContext`, so every query in it is scoped and the client cannot opt out: ```ts const api = createApi({ pool, include: [Invoice], contextOf: (req) => ({ tenantId: authenticate(req).tenantId }), // from a verified session or JWT }); ``` The filter guards writes as well: an `insertOne` for another tenant is a `403`, and a `saveOne` onto another tenant’s row a `409`. See [Multi-tenancy](https://uql-orm.dev/multi-tenancy.md) for the filter itself. ## Custom routes beside it The API serves single-entity calls. Other paths are a `404` from `toFetchHandler` and fall through to `next()` in Express, so your own routes can share the prefix. Write those for multi-entity transactions, aggregations, raw SQL, uploads and streaming. > **Minification** > > Paths come from class names at runtime. If you minify the server bundle, keep class names (`keepNames` in esbuild, `keep_classnames` in terser), or pass the same `entityPath` function to `createApi` and `createClientQuerier` to name paths yourself. # Express > Query UQL from your Express routes, and optionally serve entity CRUD with one router. Source: https://uql-orm.dev/express Your Express routes query the pool directly. If you also want CRUD routes for many entities without writing them, `uql-orm/express` mounts the [API](https://uql-orm.dev/http.md) as a router. ## Your own routes ```ts import express from 'express'; import { Post } from './shared/models/index.js'; import { pool } from './uql.config.js'; const app = express(); app.get('/posts', async (_req, res) => { const posts = await pool.findMany(Post, { $where: { published: true }, $limit: 20, }); res.json(posts); }); app.listen(3000); ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. Run several writes together in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ## Auto-generated CRUD Requires Express 5. ```ts import { toExpress } from 'uql-orm/express'; import { createApi } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; app.use('/api/v1', toExpress(createApi({ pool, include: [User, Post] }))); ``` This serves the [wire protocol](https://uql-orm.dev/http.md#wire-protocol) for each entity, [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) included, and answers every failure with the [error envelope](https://uql-orm.dev/http.md#wire-protocol) itself, a malformed JSON body included. It parses a body only on a route it serves; a body your own `express.json()` parsed first is taken as it is, with that parser’s limits. A request for an unknown entity or route falls through with `next()`, unread, so your own routes can share `/api/v1`. ## Middleware and tenant scoping The API’s [middleware](https://uql-orm.dev/http.md#middleware) and [`contextOf`](https://uql-orm.dev/http.md#tenant-scoping) receive the `express.Request` as their context: ```ts import type { Request } from 'express'; import { UqlRequestError } from 'uql-orm'; import { type ApiMiddleware, createApi } from 'uql-orm/http'; const signedIn: ApiMiddleware = (call, req, next) => { if (!req.user) { throw new UqlRequestError('unauthorized', 401); } return next(call); }; const api = createApi({ pool, include: [User, Post], contextOf: (req) => ({ tenantId: req.user?.tenantId }), use: [signedIn], }); app.use('/api/v1', toExpress(api)); ``` `req.user` is whatever your auth middleware declares on `Express.Request` (Passport does it for you). # Fastify > Query UQL from your Fastify routes, and optionally serve entity CRUD through one catch-all route. Source: https://uql-orm.dev/fastify Your Fastify routes query the pool directly. If you also want CRUD routes for many entities without writing them, one catch-all route forwards to the [API](https://uql-orm.dev/http.md). ## Your own routes ```ts import Fastify from 'fastify'; import { Post } from './shared/models/index.js'; import { pool } from './uql.config.js'; const fastify = Fastify(); fastify.get('/posts', () => pool.findMany(Post, { $where: { published: true }, $limit: 20 }), ); await fastify.listen({ port: 3000 }); ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. Run several writes together in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ## Auto-generated CRUD Fastify’s request is not a web `Request`, so use `toRequestHandler`. It takes a plain request object and answers `{ status, body, headers? }`, a failure’s [error envelope](https://uql-orm.dev/http.md#wire-protocol) included, or `undefined` for a route it does not serve: ```ts import type { FastifyRequest } from 'fastify'; import { createApi, toRequestHandler } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; const handle = toRequestHandler( createApi({ pool, include: [User, Post] }), ); fastify.all<{ Params: { entityPath: string; op: string }; Querystring: { q?: string }; }>('/api/v1/:entityPath/:op', async (req, reply) => { const answered = await handle({ method: req.method, entityPath: req.params.entityPath, op: req.params.op, q: req.query.q, body: req.body, contentType: req.headers['content-type'], context: req, // what contextOf and middleware receive }); if (!answered) return reply.callNotFound(); const { status, body, headers = {} } = answered; return reply.status(status).headers(headers).send(body); }); ``` This serves the [wire protocol](https://uql-orm.dev/http.md#wire-protocol) for each entity. Fastify parses JSON bodies itself and matches your own routes before this catch-all. From Fastify 5.11, `fastify.all` routes [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) too and parses its body, so the [client](https://uql-orm.dev/browser.md#read-method) can send it. On older versions, keep the client on `GET` or `POST`. ## Middleware and tenant scoping The API’s [middleware](https://uql-orm.dev/http.md#middleware) and [`contextOf`](https://uql-orm.dev/http.md#tenant-scoping) receive whatever you passed as `context`. Name its type as the type parameter, for example `createApi(...)`, to read the `user` your auth plugin sets. # Hono > Query UQL from your Hono routes, and optionally mount entity CRUD with one API. Source: https://uql-orm.dev/hono Your Hono routes query the pool directly. If you also want CRUD routes for many entities without writing them, mount the [API](https://uql-orm.dev/http.md). Hono is fetch-native, so nothing else is needed. ## Your own routes ```ts import { Hono } from 'hono'; import { Post } from './shared/models/index.js'; import { pool } from './uql.config.js'; const app = new Hono(); app.get('/posts', async (c) => { const posts = await pool.findMany(Post, { $where: { published: true }, $limit: 20, }); return c.json(posts); }); export default app; // Bun and Workers; on Node, serve(app) from @hono/node-server ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. Run several writes together in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ## Auto-generated CRUD Mount the [API](https://uql-orm.dev/http.md) under a prefix, beside your own routes: ```ts import { cors } from 'hono/cors'; import { createApi, toFetchHandler } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; const handler = toFetchHandler(createApi({ pool, include: [User, Post] })); app.use('*', cors()); app.mount('/api/v1', handler); ``` `.mount()` strips the prefix and forwards every method, so this serves the [wire protocol](https://uql-orm.dev/http.md#wire-protocol), [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) included. An unknown route under `/api/v1` is a `404` from the handler, not passed on to later routes. Middleware and tenant scoping are the API’s: see [middleware](https://uql-orm.dev/http.md#middleware) and [`contextOf`](https://uql-orm.dev/http.md#tenant-scoping). Their `context` is the web `Request`. Hono’s `hc` client sees only chained routes, not mounted ones. Use the [client](https://uql-orm.dev/browser.md) for the CRUD routes. ## Cloudflare D1 A [D1](https://uql-orm.dev/cloudflare-d1.md) binding arrives with each request, and `.mount()` hands the handler a bare `Request` with no way back to `c.env`. Route it yourself: ```ts import { Hono } from 'hono'; import { UqlRequestError } from 'uql-orm'; import { D1QuerierPool } from 'uql-orm/d1'; import { API_OPS, type ApiMiddleware, createApi, toFetchHandler, } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; const readsOnly: ApiMiddleware = async (call, _context, next) => { if (API_OPS[call.op].access !== 'read') { throw new UqlRequestError( 'D1 runs no transaction: write through your own routes', 405, ); } return next(call); }; const app = new Hono<{ Bindings: { DB: D1Database } }>(); app.all('/api/v1/*', (c) => { const api = createApi({ pool: new D1QuerierPool(c.env.DB), include: [User, Post], use: [readsOnly], }); return toFetchHandler(api)(c.req.raw); }); ``` D1 has no transactions and the API runs every write in one, so serve reads alone (`readsOnly` refuses the rest) and write through your own routes. # Elysia > Query UQL from your Elysia routes, and optionally mount entity CRUD with one API. Source: https://uql-orm.dev/elysia Your Elysia routes query the pool directly. If you also want CRUD routes for many entities without writing them, mount the [API](https://uql-orm.dev/http.md). Elysia is fetch-native, so nothing else is needed. ## Your own routes ```ts import { Elysia } from 'elysia'; import { Post } from './shared/models/index.js'; import { pool } from './uql.config.js'; new Elysia() .get('/posts', () => pool.findMany(Post, { $where: { published: true }, $limit: 20 }), ) .listen(3000); // Bun; on Node, `new Elysia({ adapter: node() })` from @elysiajs/node ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. Run several writes together in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ## Auto-generated CRUD ```ts import { cors } from '@elysiajs/cors'; import { Elysia } from 'elysia'; import { createApi, toFetchHandler } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; const handler = toFetchHandler(createApi({ pool, include: [User, Post] })); new Elysia().use(cors()).mount('/api/v1', handler).listen(3000); ``` `.mount()` strips the prefix, forwards every method and leaves the body unparsed, so this serves the [wire protocol](https://uql-orm.dev/http.md#wire-protocol), [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) included. An unknown route under `/api/v1` is a `404` from the handler. Middleware and tenant scoping are the API’s: see [middleware](https://uql-orm.dev/http.md#middleware) and [`contextOf`](https://uql-orm.dev/http.md#tenant-scoping). Their `context` is the web `Request`. Eden Treaty cannot see mounted routes, so it keeps covering your own routes only. Use the [client](https://uql-orm.dev/browser.md) for the CRUD routes. # NestJS > Use UQL in NestJS with UqlModule, an injectable querier pool, request-scoped tenant context and optional CRUD routes. Source: https://uql-orm.dev/nestjs `uql-orm/nestjs` registers your querier pool with Nest’s dependency injection and ends it when the app shuts down. It supports Nest 10 to 12 and is tested against Nest 12. ## Setup ```ts title="app.module.ts" import { Module } from '@nestjs/common'; import { UqlModule } from 'uql-orm/nestjs'; import { pool } from './uql.config.js'; @Module({ imports: [UqlModule.forRoot({ pool })], // global unless you pass global: false }) export class AppModule {} ``` To build the pool from other providers, use `forRootAsync`: ```ts import { ConfigModule, ConfigService } from '@nestjs/config'; import { PgQuerierPool } from 'uql-orm/postgres'; UqlModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => new PgQuerierPool({ connectionString: config.get('DATABASE_URL') }), }); ``` Call `app.enableShutdownHooks()` in `main.ts` so the pool ends on `SIGTERM`. Declare your entities with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) rather than decorators. Nest’s constructor injection needs `experimentalDecorators: true`, and one `tsconfig.json` cannot compile both decorator specs. It takes the same `f` builders and gives the same queries; [the trade-offs](https://uql-orm.dev/entities/define-entity.md#decorators-or-defineentity) are small. CommonJS and ESM apps both work, since Node loads UQL’s ESM through `require(esm)`. Keep `module` at `commonjs` or `nodenext`, as Nest scaffolds it; `node16` and `node18` refuse the import. ## Injecting the pool Inject the pool with the `UQL_QUERIER_POOL` token. Never make a `Querier` a provider: it holds a connection, which a singleton would pin. ```ts import { Inject, Injectable } from '@nestjs/common'; import type { QuerierPool, Query, UniversalQuerier } from 'uql-orm'; import { UQL_QUERIER_POOL } from 'uql-orm/nestjs'; import { User } from './shared/models/index.js'; @Injectable() export class UsersService { constructor(@Inject(UQL_QUERIER_POOL) private readonly pool: QuerierPool) {} findMany(q: Query) { return this.pool.findMany(User, q); } create(user: User, db: UniversalQuerier = this.pool) { return db.insertOne(User, user); } } ``` ```ts import { Inject, Injectable } from '@nestjs/common'; import { defineEntity, f, type QuerierPool, type UniversalQuerier, } from 'uql-orm'; import { UQL_QUERIER_POOL } from 'uql-orm/nestjs'; export const AuditEvent = defineEntity({ name: 'AuditEvent', fields: { id: f.number().autoIncrement(), type: f.string(), }, }); export interface AuditEvent extends InstanceType {} @Injectable() export class AuditService { constructor(@Inject(UQL_QUERIER_POOL) private readonly pool: QuerierPool) {} record(event: Omit, db: UniversalQuerier = this.pool) { return db.insertOne(AuditEvent, event); } } ``` `create` and `record` accept a [`UniversalQuerier`](https://uql-orm.dev/querying/querier.md#accept-a-universalquerier) that defaults to the pool. That lets a caller run several services in one transaction by passing its querier down: ```ts import { Inject, Injectable } from '@nestjs/common'; import type { QuerierPool } from 'uql-orm'; import { UQL_QUERIER_POOL } from 'uql-orm/nestjs'; import { User } from './shared/models/index.js'; @Injectable() export class SignUpService { constructor( @Inject(UQL_QUERIER_POOL) private readonly pool: QuerierPool, private readonly users: UsersService, private readonly audit: AuditService, ) {} signUp(user: User) { return this.pool.transaction(async (querier) => { await this.users.create(user, querier); await this.audit.record({ type: 'user.created' }, querier); }); } } ``` In controllers, validate the few arguments an endpoint accepts and build the query on the server, rather than taking a client’s query. In Nest 12, `@Body({ schema })`, `@Query` and `@Param` take a Standard Schema such as zod, which `StandardSchemaValidationPipe` checks. ## Multi-tenancy Pass `contextOf`, which may be async, and the module adds a global interceptor that runs each request inside `withContext`. A `security` [filter](https://uql-orm.dev/multi-tenancy.md) then scopes every query in the request, relations, cascades and transactions included: ```ts type AuthedRequest = { user: { id: string; tenantId: number } }; UqlModule.forRoot({ pool, contextOf: (req) => ({ tenantId: req.user.tenantId, userId: req.user.id }), }); ``` Interceptors run after guards, so `req.user` is already set. The context reaches controllers and services but not guards or exception filters. If you need it earlier, say from a header, use your own middleware: `withContext(context, () => next())`. ## Auto-generated CRUD Nest’s default platform is Express 5, so the [Express router](https://uql-orm.dev/express.md) mounts in `main.ts`: ```ts title="main.ts" import { NestFactory } from '@nestjs/core'; import { toExpress } from 'uql-orm/express'; import { createApi } from 'uql-orm/http'; const app = await NestFactory.create(AppModule); app.enableShutdownHooks(); app.use('/api/v1', toExpress(createApi({ pool, include: [User, Post] }))); await app.listen(3000); ``` Unknown routes fall through to your controllers. The router runs before Nest’s interceptors, so the module’s `contextOf` does not reach it: pass the API [its own](https://uql-orm.dev/http.md#tenant-scoping). On the Fastify platform, use the [`toRequestHandler` bridge](https://uql-orm.dev/fastify.md). # Next.js > Query UQL from Next.js App Router server components, route handlers and server actions. Source: https://uql-orm.dev/nextjs Server components, route handlers and server actions run on the server, so they query the pool directly. [examples/nextjs](https://github.com/rogerpadilla/uql/tree/main/examples/nextjs) is a runnable Next.js 16 app, tested in CI. ```sh npm install uql-orm pg server-only npm install -D @babel/plugin-proposal-decorators@7 tsx ``` ## Where the pool lives ```ts title="src/db/uql.ts" import 'server-only'; import { PgQuerierPool } from 'uql-orm/postgres'; import './entities'; // registers the decorated entities // hot reload re-runs this module; reuse the pool instead of leaking a new one each time declare global { var uqlPool: PgQuerierPool | undefined; } export const pool = (globalThis.uqlPool ??= new PgQuerierPool({ connectionString: process.env.DATABASE_URL, })); ``` `server-only` turns an import from a client component into a build error, so the connection string never ships to the browser. `tsx` is for [`uql-migrate`](https://uql-orm.dev/migrations.md#running-the-cli). ## Decorators Next’s SWC compiles only legacy decorators, and UQL uses the standard ones. Either let Babel compile them, leaving `experimentalDecorators` off; Next picks up the config on its own, Turbopack included. Or declare entities with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md), which needs no decorators and so no Babel config: Decorators: ```json title="babel.config.json" { "presets": ["next/babel"], "plugins": [["@babel/plugin-proposal-decorators", { "version": "2023-11" }]] } ``` defineEntity: ```ts title="src/db/entities.ts" import { f, defineEntity } from 'uql-orm'; export const User = defineEntity({ name: 'User', fields: { id: f.number().autoIncrement(), email: f.string().unique(), }, }); export interface User extends InstanceType {} ``` The production build minifies class names, and a table is named after its class by default, so name every table: `@Entity({ name: 'users' })` ([details](https://uql-orm.dev/entities/basic.md#if-your-build-minifies-name-the-table)). ## Server components and route handlers ```tsx title="app/users/page.tsx" import { pool } from '@/db/uql'; import { User } from '@/db/entities'; export default async function UsersPage() { const users = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { posts: { $select: { title: true }, $limit: 5 } }, $limit: 20, }); return (
    {users.map((user) => (
  • {user.name} ({user.posts.length})
  • ))}
); } ``` A route handler queries the same way and returns `NextResponse.json(rows)`. Keep it on the default Node.js runtime, since `pg` needs TCP. ## Server actions An action is a public endpoint, so build the query from validated input, never from a client’s `Query`. Writes that must land together go in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md): ```ts title="app/users/actions.ts" 'use server'; import { revalidatePath } from 'next/cache'; import { z } from 'zod'; import { pool } from '@/db/uql'; import { Post, User } from '@/db/entities'; const NewUser = z.object({ email: z.email(), name: z.string().trim().min(1) }); export async function createUser(formData: FormData) { const form = NewUser.safeParse(Object.fromEntries(formData)); if (!form.success) return { errors: z.flattenError(form.error).fieldErrors }; await pool.transaction(async (querier) => { const id = await querier.insertOne(User, form.data); await querier.insertOne(Post, { authorId: id, title: 'Hello' }); }); revalidatePath('/users'); } ``` ## Auto-generated CRUD Mount the [API](https://uql-orm.dev/http.md) in a catch-all route under its base: ```ts title="app/api/v1/[...uql]/route.ts" import { createApi, toFetchHandler } from 'uql-orm/http'; import { pool } from '@/db/uql'; import { User } from '@/db/entities'; const handler = toFetchHandler(createApi({ pool, include: [User] })); export { handler as GET, handler as POST }; ``` Route handlers export the standard verbs only, so keep the [client](https://uql-orm.dev/browser.md#read-method) off `QUERY`. ## Multi-tenancy Wrap the work in `withContext` with the tenant from a verified session. A `security` [filter](https://uql-orm.dev/querying/filters.md) then scopes each query inside, across every `await`: ```ts title="src/db/withTenant.ts" import 'server-only'; import { withContext } from 'uql-orm'; import { getSession } from '@/auth'; export async function withTenant(run: () => Promise): Promise { const session = await getSession(); return session ? withContext({ tenantId: session.tenantId }, run) : run(); } ``` Then query inside it: `withTenant(() => pool.findMany(Invoice, { $limit: 50 }))`. Next’s `proxy.ts` cannot set the context, since it returns before your page queries. The CRUD route takes [`contextOf`](https://uql-orm.dev/http.md#tenant-scoping) instead. See [Multi-tenancy](https://uql-orm.dev/multi-tenancy.md). > **Vercel** > > On Fluid compute, call `attachDatabasePool(pool.pool)` from `@vercel/functions` so idle connections close before the function suspends. See [Serverless](https://uql-orm.dev/serverless.md). # React Router > Query UQL from React Router framework mode loaders, actions, resource routes and middleware. Source: https://uql-orm.dev/react-router In framework mode, loaders and actions run on the server, so they query the pool directly. Written for React Router 8; on v7, middleware needs its future flag. Data mode and SPA mode have no server, so there you mount the [API](https://uql-orm.dev/http.md) wherever your API runs and call it with the [client](https://uql-orm.dev/browser.md). ## Where the pool lives The `.server.ts` suffix keeps this module out of the client bundle: ```ts title="app/db.server.ts" import { PgQuerierPool } from 'uql-orm/postgres'; import './models'; export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_URL, }); ``` ## Loaders and actions `loaderData` is typed from what the loader returns, each post with a typed `author`: ```tsx title="app/routes/posts.tsx" import { pool } from '~/db.server'; import { Post } from '~/models'; import type { Route } from './+types/posts'; export async function loader() { return { posts: await pool.findMany(Post, { $select: { id: true, title: true }, $populate: { author: { $select: { name: true } } }, $where: { published: true }, $limit: 20, }), }; } export default function Posts({ loaderData }: Route.ComponentProps) { return (
    {loaderData.posts.map((post) => (
  • {post.title} - {post.author.name}
  • ))}
); } ``` An action is a public endpoint, so validate its input and build the query on the server. Several writes go in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ```ts title="app/routes/posts.new.tsx" import { redirect } from 'react-router'; import { z } from 'zod'; import { pool } from '~/db.server'; import { Post } from '~/models'; import type { Route } from './+types/posts.new'; const NewPost = z.object({ title: z.string().trim().min(1) }); export async function action({ request }: Route.ActionArgs) { const form = NewPost.safeParse(Object.fromEntries(await request.formData())); if (!form.success) return { errors: z.flattenError(form.error).fieldErrors }; return redirect(`/posts/${await pool.insertOne(Post, form.data)}`); } ``` ## Auto-generated CRUD Point a splat route, `route('api/v1/*', 'routes/uql.ts')`, at a resource route that forwards to the [API](https://uql-orm.dev/http.md): ```ts title="app/routes/uql.ts" import { createApi, toFetchHandler } from 'uql-orm/http'; import { pool } from '~/db.server'; import { Post, User } from '~/models'; import type { Route } from './+types/uql'; const handler = toFetchHandler(createApi({ pool, include: [Post, User] })); export const loader = ({ request }: Route.LoaderArgs) => handler(request); export const action = ({ request }: Route.ActionArgs) => handler(request); ``` `loader` serves `GET`, and `action` `POST`. `QUERY` reaches neither, so keep the [client](https://uql-orm.dev/browser.md#read-method) off it. ## Multi-tenancy Middleware on the root route wraps every loader, action and resource route below it, so set the context there. A `security` [filter](https://uql-orm.dev/querying/filters.md) then scopes every query. See [Multi-tenancy](https://uql-orm.dev/multi-tenancy.md). ```ts title="app/root.tsx" import { withContext } from 'uql-orm'; export const middleware: Route.MiddlewareFunction[] = [ async ({ request }, next) => { const session = await getSession(request.headers.get('cookie')); return session ? withContext({ tenantId: session.tenantId }, () => next()) : next(); }, ]; ``` # Astro > Query UQL from Astro pages, server islands, actions and a catch-all API endpoint. Source: https://uql-orm.dev/astro An Astro page can query the database in its frontmatter, with no API in between. Written for Astro 7. Database access needs [on-demand rendering](https://docs.astro.build/en/guides/on-demand-rendering/): an adapter, plus `output: 'server'` or `export const prerender = false` per route. ## Where the pool lives ```ts title="src/lib/uql.ts" import { DATABASE_URL } from 'astro:env/server'; import { PgQuerierPool } from 'uql-orm/postgres'; export const pool = new PgQuerierPool({ connectionString: DATABASE_URL }); ``` Declare `DATABASE_URL` in `env.schema` as `envField.string({ context: 'server', access: 'secret' })`, so it stays off the client and a missing value fails the build. If you are moving off `@astrojs/db`, which Astro 7 removed, the databases its upgrade guide suggests all work here: [Turso or libSQL](https://uql-orm.dev/turso.md), [SQLite](https://uql-orm.dev/sqlite.md), [Postgres](https://uql-orm.dev/postgres.md) or [PGlite](https://uql-orm.dev/pglite.md). Only the pool changes. ## Pages ```astro title="src/pages/posts/index.astro" --- import { pool } from '../../lib/uql'; import { Post } from '../../lib/models'; const posts = await pool.findMany(Post, { $select: { id: true, title: true }, $populate: { author: { $select: { name: true } } }, $where: { published: true }, $limit: 20, }); ---
    {posts.map((post) => (
  • {post.title} - {post.author.name}
  • ))}
``` ## Caching Route caching stops that page from querying on every request. Pick your adapter’s provider and set rules per URL: ```ts title="astro.config.ts" import { cacheVercel } from '@astrojs/vercel/cache'; import { defineConfig } from 'astro/config'; export default defineConfig({ cache: { provider: cacheVercel() }, routeRules: { '/posts': { maxAge: 60, swr: 300 } }, }); ``` Tag a page with `Astro.cache.set({ tags: ['posts'] })`, and after a write call `context.cache.invalidate({ tags: ['posts'] })` to drop only what changed. `memoryCache()` caches inside one instance only, so on serverless it saves few queries. The cache key is the URL, not your tenant context, so per-user data belongs in a server island or behind `Astro.cache.set(false)`. Defer the component and it renders in its own request: ```astro title="src/pages/account.astro"

Loading your orders...

``` ## Actions An action is a public endpoint, so build the query from its validated input, never from a client’s `Query`. Several writes go in [`pool.transaction`](https://uql-orm.dev/querying/transactions.md). ```ts title="src/actions/index.ts" import { z } from 'astro/zod'; import { ActionError, defineAction } from 'astro:actions'; import { Comment } from '../lib/models'; import { pool } from '../lib/uql'; export const server = { addComment: defineAction({ accept: 'form', input: z.object({ postId: z.coerce.number(), body: z.string().min(1) }), handler: async ({ postId, body }, context) => { const user = context.locals.user; if (!user) throw new ActionError({ code: 'UNAUTHORIZED' }); const id = await pool.insertOne(Comment, { postId, body, authorId: user.id, }); return pool.findOneById(Comment, id); }, }), }; ``` ## Auto-generated CRUD Mount the [API](https://uql-orm.dev/http.md) in a catch-all endpoint under its base. `ALL` catches every method, [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) included: ```ts title="src/pages/api/v1/[...uql].ts" import type { APIRoute } from 'astro'; import { createApi, toFetchHandler } from 'uql-orm/http'; import { Comment, Post } from '../../../lib/models'; import { pool } from '../../../lib/uql'; export const prerender = false; const handler = toFetchHandler(createApi({ pool, include: [Post, Comment] })); export const ALL: APIRoute = ({ request }) => handler(request); ``` You can also answer from `src/fetch.ts`, before Astro’s pipeline runs. That skips middleware, so set the tenant context there yourself: ```ts title="src/fetch.ts" import type { Fetchable } from 'astro'; import { astro, FetchState } from 'astro/fetch'; import { withContext } from 'uql-orm'; import { createApi, toFetchHandler } from 'uql-orm/http'; import { Comment, Post } from './lib/models'; import { pool } from './lib/uql'; const handler = toFetchHandler(createApi({ pool, include: [Post, Comment] })); export default { async fetch(request: Request) { const state = new FetchState(request); if (!state.pathname.startsWith('/api/v1/')) return astro(state); const session = await getSession(state.cookies); return session ? withContext({ tenantId: session.tenantId }, () => handler(request)) : handler(request); }, } satisfies Fetchable; ``` ## Multi-tenancy Astro middleware wraps `next()`, so setting the context there covers pages, islands, actions and the API endpoint. A `security` [filter](https://uql-orm.dev/querying/filters.md) then scopes their queries. See [Multi-tenancy](https://uql-orm.dev/multi-tenancy.md). ```ts title="src/middleware.ts" import { defineMiddleware } from 'astro:middleware'; import { withContext } from 'uql-orm'; export const onRequest = defineMiddleware(async (context, next) => { const session = await getSession(context.cookies); context.locals.user = session?.user; return session ? withContext({ tenantId: session.tenantId }, () => next()) : next(); }); ``` # TanStack Start > Query UQL from TanStack Start server functions, and optionally serve entity CRUD from a catch-all server route. Source: https://uql-orm.dev/tanstack-start Server functions run on the server, so they query the pool directly. For CRUD routes across many entities, mount the [API](https://uql-orm.dev/http.md) in a catch-all server route as well. ## Server functions A UQL query is plain JSON, so it can be a server function’s input, typed end to end: ```ts import { createServerFn } from '@tanstack/react-start'; import type { WireQuery } from 'uql-orm'; import { User } from './shared/models/index.js'; import { pool } from './uql.config.js'; export const listUsers = createServerFn({ method: 'GET' }) .validator((query: WireQuery) => query) // declares the type, checks nothing .handler(({ data }) => pool.findMany(User, data)); const users = await listUsers({ data: { $select: { id: true, name: true }, $where: { status: 'active' }, $limit: 10, }, }); ``` That validator trusts the caller, and the pool checks no `wire`, so a caller can read any field. For untrusted callers, validate a few arguments with a schema and build the query on the server, or hand the call to an [API](https://uql-orm.dev/http.md)’s `api.call`, which checks it. For tenant isolation, run the handler inside `withContext` and declare a `security` [filter](https://uql-orm.dev/querying/filters.md) ([Multi-tenancy](https://uql-orm.dev/multi-tenancy.md)). ## Auto-generated CRUD ```ts title="src/routes/api/v1/$.ts" import { createFileRoute } from '@tanstack/react-router'; import { createApi, toFetchHandler } from 'uql-orm/http'; import { Post, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; const handler = toFetchHandler(createApi({ pool, include: [User, Post] })); export const Route = createFileRoute('/api/v1/$')({ server: { handlers: { ANY: ({ request }: { request: Request }) => handler(request), }, }, }); ``` `ANY` answers every method no other handler names, [`QUERY`](https://uql-orm.dev/http.md#http-query-rfc-10008) included. # tRPC > Query UQL from tRPC procedures with validated inputs, scoped by tenant in one middleware. Source: https://uql-orm.dev/trpc Your procedures query the pool directly, and their validated inputs are the contract. Written for tRPC v11. For a client that writes whole UQL queries, one procedure carries every call to an [API](https://uql-orm.dev/http.md), and the [client](https://uql-orm.dev/browser.md) runs over it: each result is narrowed to what that call selects, which a procedure taking a `WireQuery` cannot do, since its output type is fixed when it is defined. See [whole queries](#whole-queries). ## Router One middleware checks the session and sets the [context](https://uql-orm.dev/multi-tenancy.md) for everything the procedure runs, so a `security` [filter](https://uql-orm.dev/querying/filters.md) scopes every query and insert: ```ts title="src/router.ts" import { initTRPC, TRPCError } from '@trpc/server'; import superjson from 'superjson'; import { withContext } from 'uql-orm'; import { createApi, parseWireCall } from 'uql-orm/http'; import { z } from 'zod'; import { Post, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; export const createContext = async ({ req }: { req: Request }) => ({ session: await getSession(req.headers.get('cookie')), }); const t = initTRPC .context() .create({ transformer: superjson }); const authed = t.procedure.use(({ ctx, next }) => { if (!ctx.session) throw new TRPCError({ code: 'UNAUTHORIZED' }); return withContext({ tenantId: ctx.session.tenantId }, () => next()); }); const api = createApi({ pool, include: [Post, User] }); export const appRouter = t.router({ // every call a client querier sends, see whole queries below uql: authed .input(parseWireCall) .mutation(({ input, ctx }) => api.call(input, ctx)), searchPosts: authed .input(z.object({ title: z.string().max(100) })) .query(({ input }) => pool.findMany(Post, { $select: { id: true, title: true }, $where: { title: { $istartsWith: input.title } }, $limit: 20, }), ), createPost: authed .input(z.object({ title: z.string().min(1).max(200) })) .mutation(({ input }) => pool.insertOne(Post, { title: input.title })), }); export type AppRouter = typeof appRouter; ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. `superjson` keeps `Date` values as dates in both directions. Without it they arrive as strings. ## Server The fetch adapter serves Bun, Deno, Workers and any fetch-native framework. On Node, use `@trpc/server/adapters/standalone`. ```ts title="src/server.ts" import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; import { appRouter, createContext } from './router.js'; export default { fetch: (req: Request) => fetchRequestHandler({ endpoint: '/trpc', req, router: appRouter, createContext, }), }; ``` ## Client ```ts title="src/client.ts" import { createTRPCClient, httpBatchLink } from '@trpc/client'; import superjson from 'superjson'; import type { AppRouter } from './router.js'; const trpc = createTRPCClient({ links: [httpBatchLink({ url: '/trpc', transformer: superjson })], }); const posts = await trpc.searchPosts.query({ title: 'uql' }); // typed { id, title }[] ``` ## Whole queries The `uql` procedure carries every call to the API: `api.call` takes a call as JSON and answers as JSON, so it serves every entity the API includes, checked against [what a client may do](https://uql-orm.dev/http.md#what-a-client-may-do). `parseWireCall` types the procedure’s input for the client, and the API checks the call again. With no `contextOf`, the call runs in the context `authed` set. On the client, the procedure is the transport: ```ts title="src/client.ts" import { createClientQuerier } from 'uql-orm/browser'; const db = createClientQuerier((call) => trpc.uql.mutate(call)); const posts = await db.findMany(Post, { $select: { id: true, title: true }, $limit: 20, }); // typed { id, title }[], each `Date` a `Date` ``` # oRPC > Query UQL from oRPC procedures with validated inputs, scoped by tenant in one middleware. Source: https://uql-orm.dev/orpc Your [oRPC](https://orpc.dev) procedures query the pool directly, and their validated inputs are the contract. Written for oRPC v1. For a client that writes whole UQL queries, one procedure carries every call to an [API](https://uql-orm.dev/http.md), and the [client](https://uql-orm.dev/browser.md) runs over it: each result is narrowed to what that call selects, which a procedure taking a `WireQuery` cannot do, since its output type is fixed when it is defined. See [whole queries](#whole-queries). ## Router One middleware checks the session and sets the [context](https://uql-orm.dev/multi-tenancy.md) for everything the procedure runs, so a `security` [filter](https://uql-orm.dev/querying/filters.md) scopes every query and insert: ```ts title="src/router.ts" import { ORPCError, os } from '@orpc/server'; import { withContext } from 'uql-orm'; import { createApi } from 'uql-orm/http'; import { z } from 'zod'; import { Post, User } from './shared/models/index.js'; import { pool } from './uql.config.js'; const authed = os .$context<{ headers: Headers }>() .use(async ({ context, next }) => { const session = await getSession(context.headers.get('cookie')); if (!session) throw new ORPCError('UNAUTHORIZED'); return withContext({ tenantId: session.tenantId }, () => next()); }); const api = createApi({ pool, include: [Post, User] }); export const router = { // every call a client querier sends, see whole queries below uql: authed .input(z.unknown()) .handler(({ input, context }) => api.call(input, context)), searchPosts: authed .input(z.object({ title: z.string().max(100) })) .handler(({ input }) => pool.findMany(Post, { $select: { id: true, title: true }, $where: { title: { $istartsWith: input.title } }, $limit: 20, }), ), createPost: authed .input(z.object({ title: z.string().min(1).max(200) })) .handler(({ input }) => pool.insertOne(Post, { title: input.title })), }; ``` [The pool](https://uql-orm.dev/http.md#the-pool) shows the `uql.config.ts` it comes from. oRPC’s RPC protocol keeps `Date` values as dates in both directions, with no transformer. ## Server ```ts title="src/server.ts" import { RPCHandler } from '@orpc/server/fetch'; import { router } from './router.js'; const handler = new RPCHandler(router); export default { fetch: async (request: Request) => { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: { headers: request.headers }, }); return matched ? response : new Response('Not found', { status: 404 }); }, }; ``` Bun, Deno and Workers serve this as is. On Node, use the same handler from `@orpc/server/node`. ## Client ```ts title="src/client.ts" import { createORPCClient } from '@orpc/client'; import { RPCLink } from '@orpc/client/fetch'; import type { RouterClient } from '@orpc/server'; import type { router } from './router.js'; const client: RouterClient = createORPCClient( new RPCLink({ url: '/rpc' }), ); const posts = await client.searchPosts({ title: 'uql' }); // typed { id, title }[] ``` ## Whole queries The `uql` procedure carries every call to the API: `api.call` takes a call as JSON and answers as JSON, so it serves every entity the API includes, checked against [what a client may do](https://uql-orm.dev/http.md#what-a-client-may-do). The API checks the call it is handed, and with no `contextOf` runs it in the context `authed` set. On the client, the procedure is the transport: ```ts title="src/client.ts" import { createClientQuerier } from 'uql-orm/browser'; const db = createClientQuerier((call) => client.uql(call)); const posts = await db.findMany(Post, { $select: { id: true, title: true }, $limit: 20, }); // typed { id, title }[], each `Date` a `Date` ``` # Browser > Query from the browser with the same typed queries, through your API with createClientQuerier or against Postgres in the tab with PGlite. Source: https://uql-orm.dev/browser A query can run from the browser two ways: sent to your API with `uql-orm/browser`, or against Postgres running in the tab with `uql-orm/pglite`. ## The client `createClientQuerier` calls the API that [`uql-orm/http`](https://uql-orm.dev/http.md) serves, over a transport: `httpTransport` for its [HTTP protocol](https://uql-orm.dev/http.md#wire-protocol), or any other, such as a [tRPC](https://uql-orm.dev/trpc.md) procedure. Share your entity classes with the browser and the query type-checks exactly as it does on the server: ```ts import { createClientQuerier, httpTransport } from 'uql-orm/browser'; import { User } from './shared/models/index.js'; const querier = createClientQuerier( httpTransport('https://api.yourdomain.com/api/v1'), ); const users = await querier.findMany(User, { $select: { email: true }, $populate: { profile: { $select: { picture: true } } }, $where: { email: { $endsWith: '@domain.com' } }, $limit: 10, }); // typed User[], each with a typed profile ``` It has the pool’s methods a client may call: `findMany`, `findManyAndCount`, `findManyPage`, `findOne`, `findOneById`, `count`, `exists`, `insertOne`, `insertMany`, `saveOne`, `saveMany`, `updateOneById`, `updateMany`, `deleteOneById` and `deleteMany`. Each answers what the pool’s does: rows, a count, `[rows, count]`, a page, the keys a write fills. The query travels as JSON, so the client takes a [`WireQuery`](https://uql-orm.dev/querying/querier.md#the-same-query-every-transport), which has no room for [`sql`](https://uql-orm.dev/querying/raw-sql.md) fragments. A `sql` fragment or a binary value throws before anything is sent; handle those in a route of your own. Rows come back as the entity holds them, a `Date` field a `Date` and a `bigint` exact, read by the entity’s metadata, which importing its class registers. So they are not plain JSON: a cache that persists them, such as a query persister or dehydrated SSR state, needs a serializer that keeps a `Date` and a `bigint`. A failed request over HTTP throws a `RequestError`, and so does a success that is no JSON `{ data }` envelope (an HTML page a wrong base URL lands on), with the server’s message, its HTTP `status`, its [error `kind`](https://uql-orm.dev/querying/errors.md) when it has one, and the `path` in the call that is at fault, such as `['query', '$where', 'email']`: ```ts import { RequestError } from 'uql-orm/browser'; try { await querier.findMany(User, {}); } catch (err) { if (err instanceof RequestError && err.status === 401) location.href = '/login'; } ``` ### Options Headers set on the transport apply to every call, and per-call options add to them: ```ts const querier = createClientQuerier( httpTransport('/api/v1', { headers: { Authorization: `Bearer ${session.token}` }, }), ); await querier.findMany( User, { $limit: 20 }, { signal: AbortSignal.timeout(10_000) }, ); ``` During server rendering, create one transport per request so a token never leaks into another user’s request. If the server names paths with `entityPath`, pass the same function to `createClientQuerier(transport, { entityPath })`. ### Read method Reads go as `GET` by default, the call in `?q=`, so a browser or CDN can cache them. Set `readMethod` to `'POST'` or [`'QUERY'`](https://uql-orm.dev/http.md#http-query-rfc-10008) to send them in the request body instead, past URL-length limits on large queries: ```ts const querier = createClientQuerier( httpTransport('/api/v1', { readMethod: 'QUERY' }), ); ``` Writes are always `POST`. A body costs a CORS preflight cross-origin, and `QUERY` also needs every proxy on the way to forward the method. ### Around each call A transport is a function, `(call, opts) => Promise`, so wrapping one runs code around every call, enough for a global spinner: ```ts const http = httpTransport('/api/v1'); const querier = createClientQuerier(async (call, opts) => { document.body.classList.add('loading'); try { return await http(call, opts); } finally { document.body.classList.remove('loading'); } }); ``` ## Postgres in the tab [PGlite](https://uql-orm.dev/pglite.md) is Postgres compiled to WASM. Give `PgliteQuerierPool` an `idb://` directory and the database lives in IndexedDB, surviving reloads. It is the `postgres` dialect, so your entities, queries and migrations are the server’s: ```ts import { PgliteQuerierPool } from 'uql-orm/pglite'; const pool = new PgliteQuerierPool('idb://app'); const users = await pool.findMany(User, { $select: { id: true, email: true } }); ``` > **Bundler setup** > > Your bundler must emit `pglite.wasm`, `initdb.wasm` and `pglite.data`; when they 404, the first query throws `Invalid FS bundle size`. Set a dated build `target` too: with `esnext`, decorators stay as syntax no browser runs, and the page fails with `Invalid or unexpected token`. PGlite has one connection, so one transaction runs at a time. [PGlite](https://uql-orm.dev/pglite.md#one-connection-and-what-follows-from-it) covers the rest. # TanStack Query > Use UQL queries as TanStack Query cache keys, with query options, pagination, mutations, optimistic updates and server rendering. Source: https://uql-orm.dev/react-query A UQL read is one call of plain JSON, so it can be its own `queryKey`. `createQueryOptions` derives the key from the call a read makes, so the key and the fetch cannot drift apart, and components asking for the same data share one cache entry. TanStack sorts object keys when hashing, so an inline literal stays stable without `useMemo`. The examples use React and TanStack Query v5; the keys and fetchers work the same with the Vue, Svelte and Solid adapters. ## Setup Create one [client](https://uql-orm.dev/browser.md) for the network and one `QueryClient` for the cache: ```ts title="src/lib/queryClient.ts" import { QueryClient, defaultShouldDehydrateQuery, environmentManager, } from '@tanstack/react-query'; import { createClientQuerier, createQueryOptions, httpTransport, RequestError, } from 'uql-orm/browser'; const transport = httpTransport('/api/v1'); export const querier = createClientQuerier(transport); export const uql = createQueryOptions(transport); const makeQueryClient = () => new QueryClient({ defaultOptions: { queries: { staleTime: 60_000, // a 4xx won't succeed on retry; add 429 back if your API rate-limits retry: (count, err) => count < 3 && !(err instanceof RequestError && err.status < 500), }, // keep pending queries too, so a server prefetch can stream in dehydrate: { shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', }, }, }); let browserQueryClient: QueryClient | undefined; // a fresh client per server render, one for the browser tab export function getQueryClient() { if (environmentManager.isServer()) return makeQueryClient(); return (browserQueryClient ??= makeQueryClient()); } ``` ## The key and the fetcher `uql(read)` takes a read written against the client and answers `{ queryKey, queryFn }`, so a component, a prefetch and an invalidation always agree. Declare the UQL query beside it, and both come from one literal: ```ts title="src/lib/userQueries.ts" import { queryOptions } from '@tanstack/react-query'; import type { Query } from 'uql-orm'; import { User } from './models.js'; import { uql } from './queryClient.js'; export const activeUsers = { $select: { id: true, name: true, email: true }, $where: { status: 'active' }, $limit: 20, } satisfies Query; export const activeUsersOptions = queryOptions( uql((db) => db.findMany(User, activeUsers)), ); ``` The key is `['uql', 'user', 'findMany', { query }]`: the entity’s path, the op and the rest of the call as JSON carries it. So a `count` and a `findMany` of one query never share an entry, a `Date` or a `bigint` in the query hashes as its text, and the key names the entity as the API does, minified builds included. The fetch passes TanStack’s `signal` on, which cancels the request when the component unmounts. ```tsx const { data: users = [] } = useQuery(activeUsersOptions); ``` `users` is `{ id, name, email }[]`, so `user.status` is a compile error. That narrowing needs `findMany` to see the literal: a generic `useFindMany(entity, q: Query)` widens every row back to a whole `User`. See [Type Safety](https://uql-orm.dev/type-safety.md). A read is one call to the API, so it is keyed by that call: one making none or several is refused, since no single key names it. ## Pagination `$skip` and `$limit` are part of the query, so each page gets its own entry. `keepPreviousData` keeps the current page on screen while the next loads, and `findManyAndCount` brings the total in the same request: ```ts import { keepPreviousData } from '@tanstack/react-query'; export const usersPage = (page: number) => queryOptions({ ...uql((db) => db.findManyAndCount(User, { $sort: { createdAt: 'desc' }, $limit: 20, $skip: page * 20, }), ), placeholderData: keepPreviousData, }); ``` For an infinite list, leave `$skip` out of the key so every page of the list shares one entry. That entry holds `{ pages, pageParams }`, not rows, so mark the key (`'infinite'`) to keep it apart from a plain query on the same filter: ```ts import { infiniteQueryOptions } from '@tanstack/react-query'; const feed = { $where: { status: 'active' }, $limit: 20 } satisfies Query; export const userFeedOptions = infiniteQueryOptions({ queryKey: [...uql.key(User), 'infinite', feed], initialPageParam: 0, queryFn: ({ pageParam, signal }) => querier.findMany(User, { ...feed, $skip: pageParam }, { signal }), getNextPageParam: (lastPage, allPages) => lastPage.length < feed.$limit ? undefined : allPages.length * feed.$limit, maxPages: 5, // refetching a long feed costs one request per page }); ``` ## Mutations Keys match by prefix, so `uql.key(User)` invalidates every read of the entity, infinite lists included, while `activeUsersOptions.queryKey` invalidates one: ```ts import { useMutation, useQueryClient } from '@tanstack/react-query'; import type { EntityData } from 'uql-orm'; export function useInsertUser() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (payload: EntityData) => querier.insertOne(User, payload), onSuccess: () => queryClient.invalidateQueries({ queryKey: uql.key(User) }), }); } ``` A read keyed by `User` that populates `posts` is not under `uql.key(Post)`: a write to a post invalidates both prefixes. For optimistic updates, read and write the cache through `activeUsersOptions.queryKey`. `queryOptions` types that key, so `setQueryData` checks your updater against `{ id, name, email }[]`. ## Server rendering Prefetch on the server with the **pool** instead of the client, reusing the same options, then hydrate: ```tsx title="app/users/page.tsx" import { HydrationBoundary, dehydrate } from '@tanstack/react-query'; import { pool } from '@/lib/uql.config'; export default function Page() { const queryClient = getQueryClient(); void queryClient .query({ ...activeUsersOptions, queryFn: () => pool.findMany(User, activeUsers), }) .catch(() => {}); return ( ); } ``` Nothing is awaited: the page streams, and the pending entry fills in when the database answers. A failed prefetch is swallowed so the client retries it. The pool and the client answer the same rows, so both fill the entry with the same shape. For per-request auth during server rendering, create a scoped client instead of the module-level one ([options](https://uql-orm.dev/browser.md#options)). # In search of the fastest TypeScript ORM > A SQL-generation speed benchmark across six TypeScript ORMs: Drizzle, Knex, MikroORM, Sequelize, TypeORM and UQL. Reproducible and open source. Source: https://uql-orm.dev/blog/in-search-of-the-fastest-typescript-orm > **Superseded** > > This post measures SQL generation alone, with no database involved. That benchmark is retired: generation turned out to be well under 0.5% of a real request, so it said little about how ORMs compare. The [benchmark page](https://uql-orm.dev/benchmark.md) and [What does an ORM really cost you?](https://uql-orm.dev/blog/what-orms-really-cost.md) measure a full PostgreSQL round trip instead. The numbers below are kept as they were, for the record. I kept reading *“just use Drizzle, it’s lightweight”* and *“ORMs are slow, use a query builder”*. So I measured it. The benchmark measures **SQL generation speed** alone: no database, no network, no connection pool, so what is left is the overhead the ORM adds to every request. Six entries, eight query types. --- ## Methodology - **Environment:** Node.js v24.18.1, Apple M4 Pro, 3 runs averaged. - **Versions:** Latest stable of every entry as of August 2026 (TypeORM 1.1.0, MikroORM 7.1.9, Sequelize 6.37.8, Drizzle 0.45.2, Knex 3.3.0, UQL 0.24.0). - **Fairness:** Each ORM uses its most idiomatic API (QueryBuilder for TypeORM/MikroORM), which benefits them by skipping entity overhead. - **Why no Prisma?** Prisma’s query compiler is Rust compiled to WebAssembly rather than pure JS/TS, and it exposes no public SQL-compilation API, so it cannot be measured this way. --- ## The results ### INSERT: 10 rows in batch | Entry | ops/sec | vs winner | | - | - | - | | UQL | 698K | 1.00x | | Knex | 463K | 0.66x | | Sequelize | 196K | 0.28x | | MikroORM | 111K | 0.16x | | TypeORM | 42K | 0.06x | | Drizzle | 12K | 0.02x | ### UPDATE: SET + WHERE | Entry | ops/sec | vs winner | | - | - | - | | UQL | 2,161K | 1.00x | | Knex | 695K | 0.32x | | TypeORM | 282K | 0.13x | | Sequelize | 236K | 0.11x | | MikroORM | 218K | 0.10x | | Drizzle | 79K | 0.04x | ### UPSERT: ON CONFLICT by id | Entry | ops/sec | vs winner | | - | - | - | | UQL | 691K | 1.00x | | Knex | 433K | 0.63x | | Sequelize | 327K | 0.47x | | TypeORM | 261K | 0.38x | | MikroORM | 260K | 0.38x | | Drizzle | 36K | 0.05x | ### DELETE: simple WHERE | Entry | ops/sec | vs winner | | - | - | - | | UQL | 3,996K | 1.00x | | Sequelize | 1,361K | 0.34x | | Knex | 1,084K | 0.27x | | TypeORM | 507K | 0.13x | | MikroORM | 263K | 0.07x | | Drizzle | 207K | 0.05x | ### SELECT: 1 field | Entry | ops/sec | vs winner | | - | - | - | | UQL | 4,675K | 1.00x | | Sequelize | 3,084K | 0.66x | | Knex | 1,092K | 0.23x | | TypeORM | 591K | 0.13x | | MikroORM | 565K | 0.12x | | Drizzle | 229K | 0.05x | ### SELECT: WHERE + SORT + LIMIT | Entry | ops/sec | vs winner | | - | - | - | | UQL | 1,365K | 1.00x | | Knex | 614K | 0.45x | | Sequelize | 381K | 0.28x | | TypeORM | 276K | 0.20x | | MikroORM | 73K | 0.05x | | Drizzle | 59K | 0.04x | ### SELECT: complex $or + operators | Entry | ops/sec | vs winner | | - | - | - | | UQL | 741K | 1.00x | | Knex | 243K | 0.33x | | TypeORM | 158K | 0.21x | | Sequelize | 150K | 0.20x | | Drizzle | 34K | 0.05x | | MikroORM | 28K | 0.04x | ### AGGREGATE: GROUP BY + COUNT + HAVING | Entry | ops/sec | vs winner | | - | - | - | | UQL | 1,482K | 1.00x | | Sequelize | 416K | 0.28x | | Knex | 304K | 0.21x | | TypeORM | 277K | 0.19x | | Drizzle | 74K | 0.05x | | MikroORM | 69K | 0.05x | **[Interactive charts](https://rogerpadilla.github.io/ts-orm-benchmark/chart.html)** --- ## Two things that surprised me **1. The “lightweight” option comes last in six of eight queries.** Drizzle, marketed as lightweight, is slower than Sequelize (a full ORM from 2014) in every category. Its expression trees create more intermediate objects than Sequelize’s string concatenation. **2. A standalone query builder can’t beat a well-designed ORM.** Knex has no entities or relations to deal with; it only builds SQL strings. Yet UQL, a full ORM with entities, relations and migrations, is faster in all eight categories, from 1.5x on batch INSERT to 4.9x on aggregates. “ORMs are slow” stops being true when the ORM precomputes its metadata and avoids intermediate allocations. --- ## How UQL gets there I wanted to know why the gap was so large. Most ORMs work out your schema at query time: *“What table does `User` map to? What column is `companyId`? Is it nullable?”* They answer these questions on every query. UQL answers them once, at startup. Field-to-column mappings, table names and relation paths go into lookup tables before the first query runs, so generating SQL is reading from a cache. The other difference is allocation. When TypeORM builds a SELECT, it creates a QueryBuilder, then an expression tree, then walks the tree to produce SQL. UQL pushes SQL fragments straight into a string buffer, with no intermediate objects for the garbage collector. --- ## When this matters in production Database latency is 1-50ms and ORM overhead is microseconds, so for a low-traffic app the difference is noise. At scale it starts to count. Take the WHERE + SORT + LIMIT query at 1,000 req/s: UQL (1,365K ops/s) spends under 1ms of CPU per second generating SQL, MikroORM (73K ops/s) roughly 14ms, about 19x more before a byte reaches the network. On serverless, where you pay per millisecond of CPU, that shows up on the bill; in containers, as more instances. --- ## Reproduce it I wrote UQL, which is why the benchmark lives in its own repo that anyone can audit and rerun. This SQL-generation benchmark is no longer maintained (see the note above). The current one, with its repro steps, is on the [benchmark page](https://uql-orm.dev/benchmark.md), and the [comparison page](https://uql-orm.dev/comparison.md) goes feature by feature. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # In search of the perfect TypeScript ORM > Five things a TypeScript ORM should get right, and where Prisma, Drizzle, MikroORM and TypeORM each fall short of them. Source: https://uql-orm.dev/blog/in-search-of-the-perfect-orm *Originally published on [Medium](https://medium.com/@rogerpadillac/in-search-of-the-perfect-orm-e01fcc9bce3d).* ## What is an ORM? An ORM provides a simpler way to interact with databases in an app: it lets developers work with data as objects. ## What is a perfect ORM for TypeScript? Below are the ideal features a TypeScript ORM should have, why such features are the most important ones, and how the existing ORMs fall short in most of these areas. **The top 5 features a perfect TypeScript ORM should have are:** ### 1. Serializable queries Queries that can travel between the layers of a system keep the design simple. If the client can send a query to the server over HTTP or websockets using the ORM’s own syntax, you no longer need an extra query language on top: the `GraphQL => ORM => Database` flow collapses to `ORM => Database`. Concretely: - No pseudo-language for queries and no context switching: the syntax is standard JSON, entirely declarative and serializable. - No additional servers and no extra steps in the build process. - Editors and IDEs understand the queries natively, without custom plugins or extensions. ### 2. Native TypeScript Use TypeScript itself for everything: JSON queries, classes, and decorators. - Type-safe queries and models that are natively validated by the same language that you use to write your app. - Context-aware queries allow auto-completion of the appropriate operators and fields according to the different parts of a query. - Entity definition with standard classes and decorators to avoid the need for proprietary DSLs (as happens with Prisma), extra steps in the build process, and custom extensions for the editors. ### 3. Multi-level operators Operations such as filter, sort, limit, project, and others work on any level of the queries (including relations and their fields). ### 4. Consistent API across databases Write the queries for any database in a consistent way and then transparently optimize these queries for the configured database dialect. ### 5. Universal syntax (language agnostic) Because the queries are standard JSON, they can be produced or consumed from any language: JSON is a first-class format in Python, Rust, Go, and virtually everything else. That also makes UQL implementations in other languages feasible. --- ## Why do the current top 3 TypeScript ORMs fall short? ### What does TypeORM lack to be a perfect ORM? **1. Lack of 100% serializable queries:** Notice how the `LessThan` operator is a function that has to be imported and called; that alone makes the query impossible to serialize. ```ts title="TypeORM" import { LessThan } from 'typeorm'; const loadedPosts = await dataSource.getRepository(Post).findBy({ likes: LessThan(10), }); ``` **2. Lack of Native TypeScript:** The query dissolves into strings because `relations` and `where` accept any string, so any invalid string can go there. ```ts title="TypeORM" const posts = await connection.manager.find(Post, { select: ['id'], relations: ['< anything can go here >'], }); ``` **3. Lack of consistent API across databases:** In the section that TypeORM has for MongoDB, there is a self-explanatory warning about this. **4. Lack of Universal Syntax (language agnostic):** It relies on closures to support advanced queries (and not every language out there supports closures). --- ### What does Prisma lack to be a perfect ORM? **1. Lack of Native TypeScript:** - Context-switching between the custom DSL and TypeScript makes this process obtrusive. - Extra steps in the build process to generate the corresponding files from the custom DSL. - It is required to install a custom extension for VS Code to get (basic) autocompletion from the editor for the DSL, which is far from being as good and reliable as with TypeScript. ```prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) email String @unique name String? role Role @default(USER) posts Post[] } ``` **2. Lack of consistent API across databases:** Prisma exposes low-level details about MongoDB that could be encapsulated by the ORM. ```prisma model User { id String @id @default(auto()) @map("_id") @db.ObjectId // Other fields } ``` **3. Lack of Universal Syntax (language agnostic):** It relies on its own proprietary DSL to define the models. --- ### What does MikroORM lack to be a perfect ORM? **1. Lack of 100% serializable queries:** Notice how that query uses two separate methods, one for the update and another for the where; that structure cannot be serialized. ```ts title="MikroORM" const qb = orm.em.createQueryBuilder(Author); qb.update({ name: 'test 123', type: PublisherType.GLOBAL }).where({ id: 123, type: PublisherType.LOCAL, }); ``` **2. Lack of Native TypeScript:** Dissolves into strings: any string can go inside the `fields` array, so the query loses the possibility of being type-safe. ```ts title="MikroORM" const author = await em.findOne( Author, {}, { fields: ['name', 'books.title', 'books.author', 'books.price'], }, ); ``` **3. Lack of Multi-level operators:** What if you need to filter the records of a relation or sort them? This seems unachievable in a type-safe way from what can be seen in the MikroORM docs. **4. Lack of consistent API across databases:** ```ts title="MikroORM" import { EntityManager } from '@mikro-orm/mongodb'; const em = orm.em as EntityManager; const qb = em.aggregate(/* ... */); ``` MikroORM exposes low-level details about MongoDB that could be encapsulated by the ORM. --- ## Why is UQL the closest to a perfect ORM? In short, because it was designed from the beginning with all of the above foundations. Let’s see how. ### 1. 100% serializable queries Even the insert and update operations have a fully serializable API. ```ts const lastUsers = await pool.findMany(User, { $select: { id: true, name: true, email: true }, $sort: { createdAt: -1 }, $limit: 20, }); ``` ### 2. Native TypeScript with truly type-safe queries Every operator and field is validated according to the context. For example, the possible values for the `$select` operator will automatically depend on the level. ```ts const lastUsersWithProfiles = await pool.findMany(User, { $select: { id: true, name: true }, $populate: { profile: { $select: { id: true, picture: true }, $required: true }, }, $sort: { createdAt: -1 }, $limit: 20, }); ``` ### 3. Multi-level operators The operators work on any level. For example, `$sort` and `$where` can be applied to the relations and their fields in a type-safe and context-aware way. ```ts const items = await pool.findMany(Item, { $select: { id: true, name: true }, $populate: { measureUnit: { $select: { id: true, name: true }, $where: { name: { $ne: 'unidad' } }, $required: true, }, tax: { $select: { id: true, name: true } }, }, $where: { price: { $gte: 1000 }, name: { $istartsWith: 'A' }, }, $sort: { tax: { name: 1 }, measureUnit: { name: 1 }, createdAt: -1, }, $limit: 100, }); ``` ### 4. Consistent API across databases One API for every database: the same entities and queries transparently work on any supported database, with the dialect-specific SQL (or MongoDB commands) generated for you. This makes it easier to switch from a Document to a Relational database (or vice-versa); the [migration guide](https://uql-orm.dev/switching-to-uql.md) walks through what that move looks like coming from Mongoose. ### 5. Universal syntax across languages Its syntax is standard JSON, so queries can be produced or consumed from other languages, enabling interoperation or even implementations of UQL in languages such as Python or Rust. --- See more at **[uql-orm.dev](https://uql-orm.dev)**. Please star it ⭐ on **[GitHub](https://github.com/rogerpadilla/uql)** if you like the idea! --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # In search of the type-safest ORM > Reading a column your query never selected is undefined at runtime and silent at compile time. Why I resisted fixing it, and what changed my mind. Source: https://uql-orm.dev/blog/in-search-of-the-type-safest-orm The [type-safety benchmark](https://github.com/rogerpadilla/ts-orm-benchmark#type-safety) writes ten ordinary mistakes in six ORMs’ own APIs and compiles them, so “type-safe” becomes a count instead of a word on a homepage. UQL caught nine. This is about the tenth, and why I put off fixing it. ## The mistake ```ts const [user] = await pool.findMany(User, { $select: { id: true, name: true }, }); user.email; // undefined at runtime. Every time. ``` `email` was never selected, so the property is not there. Nothing objected, because the result was typed as the whole entity whatever the query asked for. The `undefined` travels into a response body or the next update, and turns up days later as a null column nobody wrote. ## Why I left it alone, for a while I knew how to fix it. I didn’t want to, and not because of the type machinery. Narrowing takes something away. Once a row is `{ id, name }` instead of `User`, it stops being the loose bag application code likes to pass around: hand it to a helper typed `(user: User) => ...` and it’s rejected. I didn’t want to trade a daily convenience for a compile error on a mistake I rarely make. So I built it, upgraded every project I maintain, work ones included, and counted the damage. There was none: [Variability](https://variability.ai) alone has 200+ find calls across 25+ files, and it compiled clean, unchanged. The pattern I was protecting turned out to be one I don’t actually write. Code that tops up a row starts from a full entity, because it needs the fields; code that projects ships the row straight out, to an API response, a list, a picker. --- ## Why UQL still catches the typo To shape the row, the query has to be captured as a type parameter, and that is where TypeScript changed. TypeScript 6.0 stopped reporting unknown keys on a literal checked against a captured map. Prisma’s and Drizzle’s projections are exactly that shape, which is why a misspelled column [compiles for both today](https://uql-orm.dev/type-safety.md), and why they sit at nine and eight rather than ten. UQL captures the field *names* instead of the map holding them, so the compiler answers a different question: ```ts await pool.findMany(User, { $select: { id: true, emial: true }, // error: 'emial' is not a field }); // against a captured map: is 'emial' a known key? - no longer reported // against captured names: 'id' | 'emial' extends FieldKey? - 'emial' is not a field ``` The second is a constraint, and constraints are still checked. `$where`, `$sort` and each populated relation aren’t captured at all, so they keep the checks they always had. --- ## What does it look like now? The row is what you asked for, and the compiler knows it: ```ts const [user] = await pool.findMany(User, { $select: { name: true }, $populate: { posts: { $select: { id: true, title: true } } }, }); user.name; // string user.posts.map((post) => post.title); // a list, empty at worst, no guard needed user.email; // compile error: not selected user.profile; // compile error: not populated ``` A query with no projection still returns the whole entity, so nothing changes where you didn’t ask for anything. Where a helper has to take a projected row, name the shape instead of widening the query: ```ts import type { QueryFindResult } from 'uql-orm'; type UserCard = QueryFindResult; ``` That is ten of ten on the [benchmark](https://uql-orm.dev/type-safety.md), the only entry with no red mark. [![](/type-safety-poster.webp)](/type-safety.mp4) Each ORM's ten mistakes, underlined by the compiler as the tab changes. [Type it yourself](https://uql-orm.dev/type-safety.md). Ten probes can’t separate six ORMs the way a microsecond can, and I chose the ten. So the claim is the narrow one: these are ten mistakes people make on an ordinary afternoon, and this is the ORM that refuses all of them. Every probe is in [type-safety/](https://github.com/rogerpadilla/ts-orm-benchmark/tree/main/type-safety), compiled as written and again with each mistake corrected. Clone it and check. And if you’re where I was, weighing a check you suspect you won’t need against a convenience you’re sure you use: upgrade a branch and count the damage. It’s a cheaper argument than the one I had with myself. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # How much memory does an ORM cost per request? > Weighing the heap around a query looked like an afternoon of work. First I got zero bytes on Bun, then a 19% skew from forcing a collection. Source: https://uql-orm.dev/blog/measuring-orm-memory Someone on r/bun [asked how UQL’s RAM usage compares to Drizzle’s](https://www.reddit.com/r/bun/comments/1w2s434/comment/p6vlefo/). I didn’t know, so I measured it: weigh the heap, run the query, weigh it again, subtract. ## Three wrong numbers first **Bun reported zero.** JavaScriptCore refreshes `heapUsed` only when it collects, so every entry looked like it had allocated nothing. The memory run is on Node, minus the two Bun SQL entries. **A forced `global.gc()` added 19%.** It frees compiled code along with the garbage, and the rounds after it re-optimise as they run, allocating extra. **One process ranked them by start order.** The first entry paid to JIT what the rest inherited warm. One process per entry now. ## What came out Measured against hand-written `raw pg` with rows mapped by hand, so what is left is the ORM’s own allocation. | Entry | Total KB | Adds KB | | - | - | - | | raw pg | 245 | floor | | **UQL** | 446 | **+201** | | Drizzle | 769 | +524 | | Prisma | 1,053 | +808 | | TypeORM | 1,065 | +820 | | Sequelize | 1,296 | +1,051 | | MikroORM | 3,864 | +3,619 | 18x between lightest and heaviest, where the same lifecycle in time spans 10x. One step accounts for nearly all of it: the nested read, the only one that turns two result sets into an object graph, costs UQL 184KB and MikroORM 2,060KB. ## What survives Sixty more lifecycles, collected either side, leave the worst entry 42KB heavier (Sequelize), identity maps and all. What the table prices is the garbage each request hands the collector, not memory that stays. ## The answer UQL adds 201KB per request, Drizzle 524KB, MikroORM 3.6MB. That is allocation, not resident memory, on one machine with no pooling and no concurrency. [Run it yourself](https://github.com/rogerpadilla/ts-orm-benchmark): `bun run bench.memory` rewrites the table it publishes, so the [current numbers](https://uql-orm.dev/benchmark.md#memory) can never drift from the last run. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # From Mongoose to SQL: migrating MongoDB to PostgreSQL > MongoDB to PostgreSQL without a big-bang rewrite: port your Mongoose queries to UQL while still on MongoDB, then switch databases without touching them. Source: https://uql-orm.dev/blog/mongodb-to-postgresql The first time I wrote MongoDB queries with Mongoose, \~2015, I felt the real power of JSON in a database. SQL databases were only starting to support it (Postgres had just shipped `jsonb`), and no ORM handled JSON well (even now there aren’t many); so I had to write it, with one unified query language for all (SQL and MongoDB), and then moving between them would be quick. UQL is that ORM, and that is why its queries look kind of MongoDB’s. Another part in the history of “why UQL” is because GraphQL felt like a monster to me (in most cases), so I had to write something better, simpler and cleaner, but that is another story my friend… Below is how you can move from Mongoose/MongoDB to PostgreSQL simply, without a big rewrite. Let me introduce why teams commonly make this move. ## Why do teams leave MongoDB? It’s mostly because their data turned out to be relational after all. In their own words: - [Infisical](https://infisical.com/blog/postgresql-migration-technical) needed replica sets just to get transactions, lost `CASCADE` and “left dangling resources”, and ran “many $lookup operations to simulate joins”. After the move, their database bill dropped by half. - At [Jsmon](https://www.siddhartha.work/blog/mongodb-to-postgresql-migration), “schema constraints caught bugs that had been silently lurking for months”. - [Voucherify](https://www.voucherify.io/blog/how-we-moved-from-mongodb-to-postgres-without-downtime) kept part of their data in each database, a “doubled codebase, paradigms and concepts” for every feature, until they moved it all. ## What makes the move hard? ### 1. Ids and references Every `ObjectId`, and every reference pointing at one, has to survive the move. Infisical kept a LevelDB map from the old ids to the new ones. ### 2. Every query is rewritten Infisical rewrote “dozens of data structures and hundreds of queries” in three to four months. Voucherify spent three months on the code, then three more moving the data. ### 3. Embedded documents lose their update operators Arrays and subdocuments become JSON columns, where SQL has no `$push`, `$pull` or `$addToSet`. Each becomes hand-written JSON SQL that differs per database. Some argue that on Postgres [“the JSON operations are not atomic”](https://news.ycombinator.com/item?id=39860769), but a single `UPDATE` is atomic for its row, so the real question is how much you put in one statement. ### 4. Both databases must agree before you switch The safest cutover is the one The Guardian used, [a proxy that sent traffic to both APIs](https://www.infoq.com/news/2019/01/guardian-mongodb-postgresql) and compared their answers before switching. It is also the most expensive, with two data layers running side by side. --- ## Why UQL makes it simple? Because UQL runs the same entities and queries on MongoDB and on almost every well-known SQL database. That splits the move in two. First you port the queries from Mongoose to UQL one at a time, shipping each on the MongoDB you already run. Then you switch the database, and the queries stay as they are. While both databases run, the second one is another pool in the same codebase. ### 1. The entities read the collections as Mongoose left them These Mongoose models: ```ts title="Mongoose" const User = model( 'User', new Schema({ name: { type: String, required: true }, settings: { theme: String, notify: { email: Boolean } }, }), ); const Post = model( 'Post', new Schema({ title: { type: String, required: true }, likes: Number, tags: [String], author: { type: Schema.Types.ObjectId, ref: 'User', required: true }, }), ); ``` ^ that become these entities below, which read the collections as stored, `author` reference included, and create matching tables on SQL, plus a pool on the MongoDB you run today. UQL takes them as decorated classes or, closer to a Mongoose schema, declared as data with [`defineEntity`](https://uql-orm.dev/entities/define-entity.md). Both are typed the same, so the code below works with either: Decorators: ```ts import { ObjectId } from 'mongodb'; import { f, Entity, Field, ManyToOne, OneToMany, type Json } from 'uql-orm'; import { MongodbQuerierPool } from 'uql-orm/mongodb'; import { z } from 'zod'; const objectId = () => new ObjectId().toHexString(); @Entity({ name: 'users' }) export class User { @Field(f.string().id().onInsert(objectId)) id?: string; @Field(f.string()) name!: string; @Field( f .jsonb( z.object({ theme: z.string().optional(), notify: z.object({ email: z.boolean().optional() }).optional(), }), ) .nullable(), ) settings?: Json<{ theme?: string; notify?: { email?: boolean } }> | null; @OneToMany(() => Post, { mappedBy: (post) => post.author }) posts?: Post[]; } @Entity({ name: 'posts' }) export class Post { @Field(f.string().id().onInsert(objectId)) id?: string; @Field(f.string()) title!: string; @Field(f.number().nullable()) likes?: number | null; @Field(f.jsonb(z.array(z.string())).nullable()) tags?: Json | null; @Field(f.references(() => User).name('author')) authorId!: string; @ManyToOne(() => User, { references: (post) => post.authorId }) author?: User; } export const pool = new MongodbQuerierPool(process.env.MONGO_URL!); ``` defineEntity: ```ts import { ObjectId } from 'mongodb'; import { f, defineEntity } from 'uql-orm'; import { MongodbQuerierPool } from 'uql-orm/mongodb'; import { z } from 'zod'; const objectId = () => new ObjectId().toHexString(); export const User = defineEntity({ name: 'User', table: 'users', fields: { id: f.string().id().onInsert(objectId), name: f.string(), settings: f .jsonb( z.object({ theme: z.string().optional(), notify: z.object({ email: z.boolean().optional() }).optional(), }), ) .nullable(), }, }).relations((rel) => ({ posts: () => rel.oneToMany(Post, { mappedBy: (post) => post.author }), })); export type User = InstanceType; export const Post = defineEntity({ name: 'Post', table: 'posts', fields: { id: f.string().id().onInsert(objectId), title: f.string(), likes: f.number().nullable(), tags: f.jsonb(z.array(z.string())).nullable(), authorId: f.string().name('author'), }, }).relations((rel) => ({ author: () => rel.manyToOne(User, { references: (post) => post.authorId }), })); export type Post = InstanceType; export const pool = new MongodbQuerierPool(process.env.MONGO_URL!); ``` The payloads are [Standard Schemas](https://uql-orm.dev/querying/json.md#a-schema-for-the-payload), Zod here: each types its column by its output. UQL reads them for their types only and never validates a document, so validate input where it enters, as the Mongoose schema did on save. In code, an id is a 24-character hex string. On MongoDB, UQL stores it as an `ObjectId`, and stores the `author` reference the same way. That lets Mongoose and UQL share the collections while you port: Mongoose’s `populate` reads a post UQL wrote, and UQL reads what Mongoose updates. On SQL, the same string is the key. References and URLs keep working without the id map Infisical needed, and `objectId` gives rows inserted on SQL later an id of the same form. ### 2. Port each query once Most of a filter carries over as is, and the chained calls become keys of one object: ```ts title="Mongoose" await Post.find({ title: { $regex: '^launch', $options: 'i' }, likes: { $gte: 3 }, }) .select('title tags author') .populate('author', 'name') .sort({ likes: -1 }) .limit(10); ``` ```ts title="UQL" await pool.findMany(Post, { $select: { title: true, tags: true }, $populate: { author: { $select: { name: true } } }, $where: { title: { $regex: '(?i)^launch' }, likes: { $gte: 3 } }, $sort: { likes: -1 }, $limit: 10, }); ``` On MongoDB the `$populate` runs as a `$lookup`, on Postgres as a join, and both return the same rows. Where Mongoose needed an aggregation pipeline, the port is shorter. The top authors by post count: ```ts title="Mongoose" await User.aggregate([ { $lookup: { from: 'posts', localField: '_id', foreignField: 'author', as: 'posts', }, }, { $project: { name: 1, posts: { $size: '$posts' } } }, { $sort: { posts: -1 } }, { $limit: 10 }, ]); ``` ```ts title="UQL" await pool.findMany(User, { $select: { name: true }, $count: { posts: true }, $sort: { posts: { $count: -1 } }, $limit: 10, }); ``` The query names no collection and no join keys, because the entities already declare the relation. It runs on Postgres unchanged. ### 3. JSON updates stay atomic In UQL the update operators change one part of a JSON column in one statement, on SQL as on MongoDB: ```ts title="UQL" await pool.updateOneById(Post, postId, { likes: { $inc: 1 }, tags: { $pull: ['draft'], $addToSet: ['release'] }, }); await pool.updateOneById(User, userId, { settings: { $set: { 'notify.email': false } }, }); ``` MongoDB itself refuses `$pull` and `$addToSet` on one field (“Updating the path ‘tags’ would create a conflict at ‘tags’”). UQL applies them in order, on every database. ### 4. Mirror, copy, compare [Stripe’s recipe for moving live data](https://stripe.com/blog/online-migrations) starts with “dual writing to the existing and new tables to keep them in sync”, then moves the reads, then the writes. With a second pool on Postgres, each step is a few lines. Every write goes to MongoDB, then to SQL. MongoDB is still the source of truth, and a failure on SQL is only logged: ```ts title="UQL" import type { QuerierPool } from 'uql-orm'; import { PgQuerierPool } from 'uql-orm/postgres'; const pg = new PgQuerierPool({ connectionString: process.env.DATABASE_URL }); async function mirror(write: (db: QuerierPool) => Promise): Promise { const result = await write(pool); await write(pg).catch((error) => console.warn('mirror failed', error)); return result; } await mirror((db) => db.insertOne(Post, { id: objectId(), title: 'Hello', authorId: userId }), ); await mirror((db) => db.updateOneById(Post, postId, { likes: { $inc: 1 } })); ``` Inserts name their id up front, and both databases store that id. Port a collection’s writes before mirroring it, since a mirror only sees writes that go through UQL. Next, a copy streams each collection into its table, parents first. `saveMany` upserts each row by its id, which makes the copy safe to run again at any time. Each run repairs whatever a failed mirror missed. ```ts title="UQL" async function copy(entity: new () => E, batchSize = 1000) { let batch: E[] = []; for await (const row of pool.findManyStream(entity, {})) { batch.push(row); if (batch.length === batchSize) { await pg.saveMany(entity, batch); batch = []; } } if (batch.length) { await pg.saveMany(entity, batch); } } await copy(User); await copy(Post); ``` Last comes The Guardian’s comparison, minus the proxy. Each read runs on both pools and logs any difference. ```ts title="UQL" import { isDeepStrictEqual } from 'node:util'; // MongoDB omits a missing field and SQL returns null: drop both. const plain = (rows: unknown) => JSON.parse(JSON.stringify(rows, (_key, value) => value ?? undefined)); async function shadow(read: (db: QuerierPool) => Promise): Promise { const [served, shadowed] = await Promise.all([read(pool), read(pg)]); if (!isDeepStrictEqual(plain(served), plain(shadowed))) { console.warn('shadow read differs', { served, shadowed }); } return served; } const posts = await shadow((db) => db.findMany(Post, { $where: { likes: { $gte: 3 } }, $sort: { likes: -1 } }), ); ``` Once the answers agree under real traffic, serve reads from SQL. Then swap the two pools in `mirror`. SQL takes each write first, and MongoDB stays current in case you need to roll back. Retire the collections once nothing reads them. --- ## What doesn’t carry over? A few things behave differently on SQL: - `null` [compares as each database compares it](https://uql-orm.dev/querying/comparison-operators.md#null-is-compared-as-the-engine-compares-it): `{ status: { $ne: 'archived' } }` leaves out a row with no status on SQL, and matches it on MongoDB. Shadow reads catch these. - SQL foreign keys reject the dangling references MongoDB accepted. Expect to clean some up, as Infisical and Jsmon did. - `$where` with JavaScript, positional `$` updates and arbitrary pipeline stages have no portable equivalent. Relations, as above, and [`aggregate`](https://uql-orm.dev/querying/aggregate.md) cover what most pipelines are for. --- Every snippet above ran against MongoDB 8 and Postgres 18 before this was published. The full Mongoose-to-UQL table is in the [migration guide](https://uql-orm.dev/switching-to-uql.md), and the mirror, copy and comparison steps are on the [MongoDB page](https://uql-orm.dev/mongodb.md#moving-to-sql). If it helps, please star UQL ⭐ on **[GitHub](https://github.com/rogerpadilla/uql)**. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # Semantic search: native vector similarity in a multi-dialect ORM > Native vector similarity search on PostgreSQL, MariaDB, SQLite and MongoDB Atlas through one type-safe query API, with automatic index migration. Source: https://uql-orm.dev/blog/semantic-search Most ORMs stop short of vector similarity. Once you need it, you drop to raw SQL: hand-written distance expressions and dialect quirks, outside your type-safe query API. UQL 0.3 adds semantic search to the regular query API, with automatic migration of HNSW and IVFFlat indexes. > **Updated September 2026** > > Vector search has since reached CockroachDB, libSQL, Turso and SQL Server 2025, and gained [`$near`](https://uql-orm.dev/querying/semantic-search.md#distance-predicate) to filter by distance and [`$candidates`](https://uql-orm.dev/querying/semantic-search.md#tuning-recall) to tune recall. The [reference](https://uql-orm.dev/querying/semantic-search.md) has the current per-engine detail. ## What it looks like ```ts title="You write" const queryVec = await embed('How do vector indexes work?'); const results = await pool.findMany(Article, { $select: { id: true, title: true }, $sort: { embedding: { $vector: queryVec, $distance: 'cosine' } }, $limit: 10, }); ``` UQL generates each database’s SQL: PostgreSQL: ```sql SELECT "id", "title" FROM "Article" ORDER BY "embedding" <=> $1::vector LIMIT 10 ``` MariaDB: ```sql SELECT `id`, `title` FROM `Article` ORDER BY VEC_DISTANCE_COSINE(`embedding`, VEC_FromText(?)) LIMIT 10 ``` SQLite: ```sql SELECT `id`, `title` FROM `Article` ORDER BY vec_distance_cosine(`embedding`, ?) LIMIT 10 ``` One query for every dialect, with no raw SQL or dialect checks in your code. On MongoDB, the same query becomes an Atlas `$vectorSearch` pipeline. The search index itself is created in Atlas; the [reference](https://uql-orm.dev/querying/semantic-search.md) has the details. MongoDB Atlas: ```json [ { "$vectorSearch": { "index": "embedding_index", "path": "embedding", "queryVector": ["..."], "numCandidates": 100, "limit": 10 } } ] ``` ## Entity setup Declare the vector field and its index; UQL creates the column, the extension and the index: ```ts import { f, Entity, Field } from 'uql-orm'; @Entity({ indexes: (article, index) => [ index([article.embedding], { type: 'hnsw', distance: 'cosine', m: 16, efConstruction: 64, }), ], }) export class Article { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) title?: string | null; @Field(f.string().nullable()) category?: string | null; @Field(f.vector(1536).nullable()) embedding?: number[] | null; } ``` On Postgres, UQL emits `CREATE EXTENSION IF NOT EXISTS vector`. MariaDB has vectors built in; SQLite needs the [sqlite-vec](https://github.com/asg017/sqlite-vec) extension loaded. ## What else shipped `$project` returns the computed distance as a named field, without computing it twice, typed with the `WithDistance` helper (now inferred). Alongside it came four distance metrics (`cosine`, `l2`, `inner`, `l1`), three vector types (`vector`, `halfvec`, `sparsevec`), and HNSW, IVFFlat and native vector indexes, each where the engine has it. The [reference](https://uql-orm.dev/querying/semantic-search.md) lists which engine has which. ## Why `$sort`? Similarity search is sorting by distance, so UQL reuses `$sort`, which combines with `$where`, `$select`, `$limit` and ordinary sort fields: ```ts const results = await pool.findMany(Article, { $where: { category: 'science' }, $sort: { embedding: { $vector: queryVec, $distance: 'cosine' }, title: 'asc', }, $limit: 10, }); ``` ## Get started ```bash npm i uql-orm ``` - **[Full documentation](https://uql-orm.dev/querying/semantic-search.md)** - **[Comparison](https://uql-orm.dev/comparison.md)** - **[GitHub](https://github.com/rogerpadilla/uql)** If something is broken or missing, open an issue on [GitHub](https://github.com/rogerpadilla/uql). --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # The SQL tag: a function called without parentheses > How a tagged template splits SQL from its values, why that is plain JavaScript, what TypeScript adds on top, and what else changed in UQL 0.100.0. Source: https://uql-orm.dev/blog/sql-tag Here is a line of UQL 0.100: ```ts await pool.all`SELECT * FROM "User" WHERE "email" = ${email}`; ``` No parentheses, yet it is a function call. How JavaScript makes that call is what keeps `email` out of the SQL: it is sent as a bound parameter, never spliced into the text. Here is how. ## What a tag receives A template literal with a function name is a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates). It is plain JavaScript, there since ES2015, so it runs in every browser, Node and Bun with no build step. The engine calls the tag with the template cut into pieces: first an array of the literal text, then each `${}` value as an argument of its own. A tag that prints its arguments shows the split: ```ts function show(texts: TemplateStringsArray, ...values: unknown[]) { console.log(texts, values); } show`SELECT * FROM "User" WHERE "email" = ${'ana@example.com'} AND "age" > ${18}`; // ['SELECT * FROM "User" WHERE "email" = ', ' AND "age" > ', ''] ['ana@example.com', 18] ``` There is always one more string than there are values; here the last one is empty. ## From pieces to a query The text pieces are fixed in your source code. The values arrive at run time, from users, other services or anywhere else. A database driver expects exactly that split: SQL with placeholders, and the parameters beside it. So this: ```ts function sql(texts: TemplateStringsArray, ...values: unknown[]) { const text = texts.reduce((t, part, i) => `${t}$${i}${part}`); return { text, values }; } sql`SELECT * FROM "User" WHERE "email" = ${email}`; ``` Produces this: ```ts const query = { text: 'SELECT * FROM "User" WHERE "email" = $1', values: ['ana@example.com'], }; ``` Whatever `email` holds, an injection attempt like `'; DROP TABLE "User"; --` included, is sent as the value of `$1`, never as SQL. Nothing to escape by hand. In UQL the method is the tag: `all` and `run` take the template directly, so there is no `sql` helper to import and wrap. ## The parentheses trap Add parentheses and you have a different program: ```ts await pool.all`SELECT * FROM "User" WHERE "email" = ${email}`; // @ts-expect-error a plain string, with the value already inside it await pool.all(`SELECT * FROM "User" WHERE "email" = ${email}`); ``` The second line builds the whole string first, `email` and all, and hands the function the finished text. No library can take the value back out, so in UQL that line does not compile. ## What TypeScript adds TypeScript checks each `${}` against the tag’s parameter types, so UQL can state what a database can bind: strings, numbers, booleans, `bigint`, `Date`, bytes, `null`, lists of those, and SQL fragments. Two common slips stop at the compiler: ```ts // @ts-expect-error `status` may be undefined, which binds nothing await pool.all`SELECT * FROM "User" WHERE "status" = ${status}`; // @ts-expect-error an object is not a SQL value await pool.run`UPDATE "User" SET "prefs" = ${prefs} WHERE "id" = ${id}`; // this one compiles await pool.run`UPDATE "User" SET "prefs" = ${JSON.stringify(prefs)} WHERE "id" = ${id}`; ``` A tag also takes a type argument, so ``pool.all<{ id: number; email: string }>`...` ``hands back typed rows. ## Fragments `sql` is the same tag without running anything: it returns a fragment. A fragment inside another template is spliced in, its values still bound: ```ts import { sql } from 'uql-orm'; const conditions = [sql`"createdAt" > ${since}`]; if (status) conditions.push(sql`"status" = ${status}`); await pool.all`SELECT * FROM "User" WHERE ${sql.join(conditions, ' AND ')}`; ``` For trusted SQL held in a string, such as a file’s contents, use `sql.text(sql)`. It is the only call that binds nothing, so it is easy to find in a review. A tag binds values, not names: a table or column taken from user input still needs checking against a list you control. ## Also in 0.100.0 ### `undefined` in a filter throws Prisma’s docs warn that `deleteMany({ where: { id: undefined } })` [deletes every user](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/null-and-undefined), because an undefined key is dropped from the filter. UQL used to drop it too; now it throws: ```ts await pool.deleteMany(User, { $where: { email: maybeEmail } }); // UqlUsageError: $where on 'User' holds undefined at 'email': leave the key out not to filter by it, or name null ``` ### Writes that do what the code says A `transaction()` inside another is a savepoint, so a failing inner step rolls back alone. A to-many update keeps the children the payload lists and removes the rest. Any write can take [`returning`](https://uql-orm.dev/querying/methods.md#returning) and resolve to the rows it wrote, typed by the fields you name. ## Upgrading `npx uql-codemod` updates your imports and turns `all(sql, [a, b])` into a tag. Anything it cannot convert safely is listed for you. The [upgrade guide](https://uql-orm.dev/upgrade-guide.md) has the rest. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # Standard decorators: props & cons > uql-orm 0.23 moved from legacy TypeScript decorators to the TC39 standard spec: no compiler flags, no reflect-metadata, and what it cost to get there. Source: https://uql-orm.dev/blog/standard-decorators UQL 0.23 moved its decorators to the [TC39 standard spec](https://github.com/tc39/proposal-decorators). `experimentalDecorators`, `emitDecoratorMetadata` and `reflect-metadata` are gone, and one thing became possible that was not before. It also deleted three decorators, removed parameter injection, and locked NestJS out of the decorator API. This post covers both sides. ## What it looks like ```ts title="Before: legacy decorators" import { Entity, Field, Id, ManyToOne } from 'uql-orm'; import 'reflect-metadata'; @Entity() class User { @Id() id?: number; @Field() name?: string; @ManyToOne() company?: Relation; } ``` ```ts title="After: the standard spec" import { f } from 'uql-orm'; @Entity() class User { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) name?: string | null; @Field(f.references(() => Company).nullable()) companyId?: number | null; @ManyToOne(() => Company, { references: (user) => user.companyId }) company?: Company; } ``` It is more typing: `type` on every field and `entity` on every relation, because nothing is reflected any more. The next section shows what the compiler does with it. ## The declared type is checked against the property Under the legacy spec, a property decorator has this shape: ```ts type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; ``` No type parameter carries the property’s type. The decorator gets a key and nothing else, so the options you pass it are only data. This compiled fine: ```ts @Field({ type: String }) age?: number; ``` You got a `TEXT` column for a number, and you found out when the data looked wrong. `emitDecoratorMetadata` did not save you, because an explicit `type` skipped inference entirely: ```ts title="packages/uql-orm/src/entity/metadata/definition.ts (0.22)" if (opts.type) { opts = { ...opts, typeInferred: false }; } else { opts = { ...opts, type: inferType(entity, key), typeInferred: true }; } ``` Reflection only filled in a missing type; it never checked a stated one against the property. The standard spec hands a field decorator a `ClassFieldDecoratorContext`, generic in the field’s value type, so a decorator can constrain what it is attached to: ```ts title="packages/uql-orm/src/entity/decorator/members.ts" /** A member decorator that also constrains the property it may be applied to. */ type MemberDecorator = ( value: undefined, context: ClassFieldDecoratorContext, ) => void; /** A declared `type` wins; otherwise the column is the referenced primary key's own type. */ type DeclaredValue = O extends { readonly type: infer T extends FieldType } ? TsTypeOf : O extends { readonly references: EntityGetter } ? IdValue : never; export function Field< O extends FieldOptions> & ({ type: FieldType } | { references: EntityGetter }), >(opts: O): MemberDecorator | undefined>; ``` `@Field({ type: String })` returns a decorator that only applies to `string | undefined`. Put it on a `number` and it does not compile. The mandatory `type` stopped being redundant typing and became a claim the compiler checks. Once one option can name the value a property holds, the others have to agree with it: ```ts import { OneToMany } from 'uql-orm'; @ManyToOne(() => Company, { references: (user) => user.companyId }) company?: number; // error: a Company relation holds a Company, not its key @OneToMany(() => User, { mappedBy: (user) => user.company }) users?: User; // error: a to-many cardinality needs an array @Field({ type: 'int' }) createdAt?: Date; // error: a Date field is not an integer column @Field({ references: () => User }) authorId?: string; // error: User's key is a number, so this column is one too @Id({ type: 'uuid', onInsert: () => 42 }) id?: string; // error: a uuid column is not stamped with a number ``` None of these were catchable before. The migration did not introduce these bugs; it made existing ones visible. A type-test suite pins every one and fails the build if any stops erroring, and all but the foreign key one hold through `defineEntity` too (since 0.106 it checks that one as well, on the relation). The last two arrived in 0.24.3: the same mechanism, applied to the two other things that decide what a column holds, the key a foreign key points at and the generator that stamps a value into it. ## What reflection was costing `reflect-metadata` was 264 KB, carried for one call: `Reflect.getMetadata('design:type', ...)`. Every consumer had to import it once, globally, before any entity loaded, and keep two compiler flags on. It did less than it seemed, too. Reflected types could not survive a circular import, which is why `Relation` existed at all: an alias whose only job was to break a cycle that reflection itself created. It is deleted now. Dropping it is part of why the package [installs 1 MB with no dependencies](https://uql-orm.dev/blog/zero-dependencies.md). ## What we gave up **`@InjectQuerier()` is gone.** The standard spec has no parameter decorators, and the [TC39 proposal for them](https://github.com/tc39/proposal-class-method-parameter-decorators) is still Stage 1. A `@Transactional()` method read its querier from `AsyncLocalStorage` instead, through `currentQuerier()`. **`@Transactional()` and `currentQuerier()` are gone too**, since 0.29.0. Nothing but the decorator ever published that ambient querier, so `currentQuerier()` threw inside `pool.transaction()` and every other entry point. A transaction is [`pool.transaction(async (querier) => ...)`](https://uql-orm.dev/querying/transactions.md), which needs no class and no decorator. **`@Log()` and `@Serialized()` are gone.** A standard-spec decorator cannot preserve a generic method’s signature, so both would have quietly widened the types of anything they wrapped. The useful half of `@Log()`, error enrichment, was moved into the querier itself. **NestJS projects cannot use UQL’s decorators at all.** Nest injects constructor parameters with a parameter decorator, so a Nest project keeps `experimentalDecorators: true`, and one `tsconfig.json` cannot mix specs. No proposal advancing a stage closes that gap. Those projects use [`defineEntity`](https://uql-orm.dev/entities/define-entity.md) instead, which carries the same checks. **`target: 'esnext'` is now forbidden.** It is the one target where TypeScript emits decorator syntax untransformed, which Node and every browser reject with a `SyntaxError`. Every dated target downlevels it correctly. **`declare` fields stop working.** The spec has nothing to decorate on a `declare` member, so narrowing an inherited relation needs a real field with an initializer. **Oxc, Vite 8’s default transformer, implements no decorators at all.** It preserves `@Entity()` verbatim at every target, so a Vite 8 project needs esbuild, SWC or Babel through a plugin. esbuild, SWC, Babel with `version: '2023-11'`, Bun and `tsc` all handle the spec. Node 24 is the new minimum, shipped in the same release. ## The two things that nearly broke it Neither is in the spec documents, and both took a while to find. **`Symbol.metadata` does not exist yet.** No runtime we support defines it, checked on Node 24 and Bun 1.3. TypeScript’s decorator emit reads it to decide whether to build the metadata object at all, so without a polyfill every `context.metadata` is `undefined` and fields go unregistered without an error. UQL defines it with `Symbol.for`, not `Symbol()`, so a duplicated copy of the module under HMR or dual-loading lands on the same symbol, and so it agrees with the key esbuild and SWC fall back to. **tsc and SWC disagree about inheritance.** tsc chains a subclass’s `context.metadata` to its parent’s. SWC does not, in any decorator version. Anything built on that prototype chain works under one compiler and quietly loses inherited fields under the other. UQL resolves inheritance by walking the class prototype chain instead, and a test builds the unchained shape SWC emits to prove it. ## The codemod `uql-codemod` does most of the mechanical work, reading types from the type checker rather than guessing from the parse tree: ```sh npx uql-codemod --dry-run npx uql-codemod ``` It rewrites `@Field`/`@Id` types, relation `entity` getters and `Relation` to `T`, and strips both flags from `tsconfig.json` while preserving your comments and formatting. It refuses to touch what it cannot be sure about: `target: esnext`, values inherited through `extends`, every removed decorator, options objects it cannot read, and branded string ids. `tsc` does the rest of the migration. The annotations the codemod inserts are checked against the properties they describe, so anything it got wrong is a compile error rather than a silently wrong column. ## Was it worth it Yes, though not because of the compiler flags. Dropping two tsconfig settings and a 264 KB polyfill is housekeeping. The reason was that reflection put the type in two places and let them drift, and no amount of care fixes a design where the compiler cannot see the mistake. Now there is one declaration, and the compiler checks it against the property. It cost three decorators, parameter injection, and a framework’s worth of users pushed onto a different API. If you are on NestJS, you paid for this release and got a smaller install back. That is a worse trade than everyone else got, and not one I can improve until TC39 moves. ## Get started ```sh npm i uql-orm npx uql-codemod --dry-run ``` - **[Upgrade guide](https://uql-orm.dev/upgrade-guide.md)** - **[Entities: decorators](https://uql-orm.dev/entities/basic.md)** and **[`defineEntity`](https://uql-orm.dev/entities/define-entity.md)** - **[Zero dependencies: what we deleted to fit on the edge](https://uql-orm.dev/blog/zero-dependencies.md)** - **[Comparison](https://uql-orm.dev/comparison.md)** - **[GitHub](https://github.com/rogerpadilla/uql)** If the codemod leaves something behind that it could have handled, open an issue with the entity that tripped it. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # Type-safe triggers in an ORM. What? > UQL declares database triggers on the entity, checks their bodies against your entities, and renders them for PostgreSQL, MySQL, SQLite and SQL Server. Why it matters, how it works, and where it stops. Source: https://uql-orm.dev/blog/type-safe-triggers An audit log written by a lifecycle hook passes every test. Then someone runs a backfill, fixes a row in `psql`, or points a second service at the table, and the log has a gap. Nothing failed: an ORM hook only sees the ORM’s own writes. A database trigger sees every write. In UQL you declare it on the entity, the compiler checks its body, and UQL renders it for each SQL engine. ## The audit log, on the entity Triggers usually live as SQL strings in an old migration: invisible from the model, unchecked against the columns, and rewritten for every engine. Here the trigger sits beside the table it watches: ```ts import { f, Entity, Field, insertInto } from 'uql-orm'; @Entity() export class PostAudit { @Field(f.number().autoIncrement()) id?: number; @Field(f.number().name('post_id')) postId?: Post['id']; @Field(f.string().nullable().name('from_status')) fromStatus?: Post['status'] | null; @Field(f.string().nullable().name('to_status')) toStatus?: Post['status'] | null; } @Entity({ triggers: (post, trigger) => [ trigger({ on: 'afterUpdate', name: 'audit', of: [post.status], run: (newRow, oldRow) => insertInto(PostAudit, { postId: newRow.id, fromStatus: oldRow.status, toStatus: newRow.status, }), }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; } ``` `of` fires the trigger only when `status` changes, and `run` writes the audit row. Columns are read as properties, so the compiler knows every name and type. A `where` adds conditions on either row, such as `{ $old: { status: 'draft' } }`. ## What the compiler catches Each of these fails at build time, not when the trigger first fires: ```ts import { Entity, Field, f, insertInto } from 'uql-orm'; @Entity({ triggers: (post, trigger) => [ trigger({ on: 'afterInsert', run: (_newRow, oldRow) => insertInto(PostAudit, { postId: oldRow.id }), // error: no old row on insert }), trigger({ on: 'afterUpdate', run: (newRow) => insertInto(PostAudit, { post: newRow.id }), // error: PostAudit has no `post` }), trigger({ on: 'afterUpdate', of: [post.status], run: (newRow) => insertInto(PostAudit, { postId: newRow.status }), // error: postId holds a number }), ], }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().nullable()) status?: string | null; } @Entity() export class PostAudit { @Field(f.number().autoIncrement()) id?: number; @Field(f.number()) postId?: number; } ``` So does watching a column the entity lacks, or an `updateTable` or `deleteFrom` with no `$where`, which would hit every row on every fire. ## One declaration, every SQL engine This is what `sync` and generated migrations install. CockroachDB gets the Postgres form, MariaDB the MySQL one: PostgreSQL: ```sql CREATE OR REPLACE FUNCTION "_uql_Post__audit_0a57e9"() RETURNS trigger AS $uql$ BEGIN INSERT INTO "PostAudit" ("post_id", "from_status", "to_status") VALUES (NEW."id", OLD."status", NEW."status"); RETURN NULL; END $uql$ LANGUAGE plpgsql; CREATE TRIGGER "_uql_Post__audit_0a57e9" AFTER UPDATE OF "status" ON "Post" FOR EACH ROW WHEN (OLD."status" IS DISTINCT FROM NEW."status") EXECUTE FUNCTION "_uql_Post__audit_0a57e9"() ``` MySQL: ```sql CREATE TRIGGER `_uql_Post__audit_94c077` AFTER UPDATE ON `Post` FOR EACH ROW BEGIN IF NOT (OLD.`status` <=> NEW.`status`) THEN INSERT INTO `PostAudit` (`post_id`, `from_status`, `to_status`) VALUES (NEW.`id`, OLD.`status`, NEW.`status`); END IF; END ``` SQLite: ```sql CREATE TRIGGER `_uql_Post__audit_08d35c` AFTER UPDATE OF `status` ON `Post` FOR EACH ROW WHEN (OLD.`status` IS NOT NEW.`status`) BEGIN INSERT INTO `PostAudit` (`post_id`, `from_status`, `to_status`) VALUES (NEW.`id`, OLD.`status`, NEW.`status`); END ``` SQL Server: ```sql CREATE TRIGGER "_uql_Post__audit_d8fbff" ON "Post" AFTER UPDATE AS BEGIN SET NOCOUNT ON; INSERT INTO "PostAudit" ("post_id", "from_status", "to_status") SELECT inserted."id", deleted."status", inserted."status" FROM inserted JOIN deleted ON inserted."id" = deleted."id" WHERE EXISTS (SELECT deleted."status" EXCEPT SELECT inserted."status"); END ``` “Fire only when `status` changes” has to count `NULL` to `'draft'` as a change, which a plain `<>` does not. Each engine spells that differently, and SQL Server hands the trigger tables rather than rows: four chances to get it subtly wrong by hand. ## How other ORMs do it The same trigger, on PostgreSQL only: Drizzle, Prisma, TypeORM: ```sql -- No trigger API. This goes in a hand-written migration: `drizzle-kit generate --custom`, -- `prisma migrate dev --create-only`, or `queryRunner.query(...)` in a TypeORM migration. CREATE FUNCTION post_audit() RETURNS trigger AS $$ BEGIN INSERT INTO post_audit (post_id, from_status, to_status) VALUES (NEW.id, OLD.status, NEW.status); RETURN NULL; END $$ LANGUAGE plpgsql; CREATE TRIGGER post_audit AFTER UPDATE OF status ON post FOR EACH ROW WHEN (OLD.status IS DISTINCT FROM NEW.status) EXECUTE FUNCTION post_audit(); ``` MikroORM: ```ts title="MikroORM" // Declared on the entity and installed by migrations. The callback maps property names to // column names; the body and `when` around them are SQL strings, one set per dialect. import { defineEntity, p } from '@mikro-orm/core'; const PostSchema = defineEntity({ name: 'Post', properties: { id: p.integer().primary(), status: p.string().nullable(), }, triggers: [ { name: 'post_audit', timing: 'after', events: ['update'], when: 'OLD.status IS DISTINCT FROM NEW.status', body: (c) => `INSERT INTO post_audit (post_id, from_status, to_status) VALUES (NEW.${c.id}, OLD.${c.status}, NEW.${c.status}); RETURN NULL;`, }, ], }); ``` MikroORM comes closest: the trigger lives on the entity and takes column names from its metadata, but the SQL around them is a string, unchecked and written once per engine. TypeORM’s subscribers, like hooks, only see TypeORM’s own writes. ## Keeping them in sync `sync` and `generate:entities` install what an entity declares and drop what it no longer does. Each name ends in a hash of its SQL, so an unchanged trigger is left alone and an edited one is replaced. Triggers UQL did not create are never touched. ## Where it stops - **MongoDB has no triggers**, so a write to an entity declaring one is refused rather than made without it. - **`sql` bodies are not translated**: write one that runs on every engine you use, or one per engine. - **Entity filters do not apply inside a trigger**: soft delete and `security` do not scope its writes, so scope them by the row’s own columns. The engine-specific rules are on the [Triggers](https://uql-orm.dev/entities/triggers.md) page. ## Why it matters with coding agents Agents write much of the code that touches a database, including what hooks never see: a one-off script, a backfill, a quick `UPDATE`. A rule the database enforces holds for all of it, and a trigger on the entity sits in the file the agent reads, checked by the compiler it runs. ## Hook, trigger or stamp | You need | Use | | - | - | | Logic around UQL’s own writes: call an API, publish an event, validate | a [lifecycle hook](https://uql-orm.dev/entities/lifecycle-hooks.md) | | A row the database writes whoever changes the table, like an audit | a [trigger](https://uql-orm.dev/entities/triggers.md) | | A column the database keeps current on every write, like `updatedAt` | a [stamp](https://uql-orm.dev/entities/computed-fields.md#stamps-stored-on-an-event) | A stamp is a trigger whose body UQL writes. `currentTimestamp` is the database clock, in UTC to the millisecond on every engine: ```ts import { Computed, f, currentTimestamp, Entity, Field } from 'uql-orm'; @Entity() export class Post { @Field(f.number().autoIncrement()) id?: number; @Computed((row) => f.date().nullable().as(currentTimestamp).stored(['update']), ) readonly updatedAt?: Date | null; } ``` ## Get started - **[Triggers](https://uql-orm.dev/entities/triggers.md)**: every option, the SQL per engine, and the engine notes - **[Comparison](https://uql-orm.dev/comparison.md)**: triggers and the rest of the feature matrix, ORM by ORM - **[GitHub](https://github.com/rogerpadilla/uql)** If a trigger you need cannot be declared this way, open an issue with the SQL you would have written. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # UQL 0.105: entities as data with no classes, and columns as builders > UQL 0.105 lets you declare an entity as plain data, turns every column into a builder, and types more of what a query returns. What changed, with an example for each, and how to upgrade. Source: https://uql-orm.dev/blog/uql-0-105 UQL v0.105 is out, and it changes how to declare an entity. Now, a column is a builder, the whole entity can be plain data, and the types are simpler to write. Old definitions break but we have it covered by `npx uql-codemod`, it rewrites most of them for you, automatically. Notice: both ways (decorators and `defineEntity`) are still supported, but now both are simpler yet stronger. ## An entity as data `defineEntity` takes the columns and returns the class. There is nothing to write twice: ```ts title="src/models.ts" import { defineEntity, f } from 'uql-orm'; export const Author = defineEntity({ name: 'Author', fields: { id: f.number().id(), name: f.string(), bio: f.string().nullable(), }, }).relations((rel) => ({ books: () => rel.oneToMany(Book), })); export type Author = InstanceType; export const Book = defineEntity({ name: 'Book', fields: { id: f.number().id(), title: f.string(), status: f.enum(['draft', 'published']).default('draft'), authorId: f.number(), }, }).relations((rel) => ({ author: () => rel.manyToOne(Author, { references: (book) => book.authorId }), })); export type Book = InstanceType; ``` `Book` reads `title` as `string` and `status` as `'draft' | 'published'`, and `Author` reads `bio` as `string | null`. An insert may leave out `id` and `status`, since the database and the default fill them. No `!`, no `?`, no class. Decorated classes still work, and both styles mix in one project. Reach for a class when a row needs methods of its own. ## Columns are builders The same builders declare a decorated class’s columns: ```diff @Field({ type: String, nullable: true, length: 80 }) @Field(f.string().nullable().length(80)) ``` ```ts title="You write" import { Entity, Field, f } from 'uql-orm'; @Entity() export class Customer { @Field(f.number().autoIncrement()) id?: number; @Field(f.string().length(120).unique()) email!: string; @Field(f.string().nullable()) nickname?: string | null; } ``` A column is NOT NULL unless you say `.nullable()`, and a key is `.id()`, so `@Id` is gone. A builder only offers the options its type can take: ```ts f.number().length(10); // error: a number has no length ``` ## One decorator per class `@Index`, `@Filter` and `@Trigger` are gone too. A class lists them in its `@Entity`: ```ts title="You write" import { Entity, Field, f } from 'uql-orm'; @Entity({ indexes: (post, index) => [index([post.title], { unique: true })], filters: { published: { where: { publishedAt: { $ne: null } }, default: false }, }, }) export class Post { @Field(f.number().autoIncrement()) id?: number; @Field(f.string()) title!: string; @Field(f.date().nullable()) publishedAt?: Date | null; } ``` Each index is written with the `index` helper its callback hands you, so a column is a typed reference, never a string. Rename `title` and the index follows. ## Relations find their own join `rel.oneToMany(Book)` in `Author` above takes no options. `Book` has one relation pointing back at `Author`, so that is the join. Add `mappedBy` only when there are two to choose from. ## Filters that read through relations `defineEntity`’s `.filters()` may now follow `.relations()`, and then reads through them at any depth, each key typed: ```ts title="You write" import { defineEntity, f } from 'uql-orm'; export const Project = defineEntity({ name: 'Project', fields: { id: f.number().id(), archived: f.boolean() }, }); export const Task = defineEntity({ name: 'Task', fields: { id: f.number().id(), title: f.string(), projectId: f.number(), }, }) .relations((rel) => ({ project: () => rel.manyToOne(Project, { references: (task) => task.projectId }), })) .filters({ live: { where: { project: { archived: false } } } }); ``` Every read of `Task` now leaves out the tasks of archived projects. A typo such as `archivd` is a compile error, as it is in a `$where`. ## Queries type what they return `$select: { bio: false }` reads every field but `bio`, and the row’s type agrees: ```ts title="You write" import { Author } from './models.js'; const authors = await pool.findMany(Author, { $select: { bio: false } }); authors[0]?.name; authors[0]?.bio; // error: bio was not selected ``` A sort that projects a distance or a score puts it on the row, so the cast you used to write is gone: ```ts title="You write" import { defineEntity, f } from 'uql-orm'; export const Note = defineEntity({ name: 'Note', fields: { id: f.number().id(), body: f.string(), embedding: f.vector(3) }, }); const nearest = await pool.findMany(Note, { $select: { body: true }, $sort: { embedding: { $vector: await embed('release notes'), $distance: 'cosine', $project: 'distance', }, }, $limit: 5, }); nearest[0]?.distance; ``` ## Upgrading Run the codemod, first as a dry run: ```sh npx uql-codemod --dry-run npx uql-codemod ``` It rewrites option objects into builders, folds `@Index`, `@Filter` and `@Trigger` into `@Entity`, turns `$exclude` into `$select`, and reports what it cannot decide. Two changes compile unchanged, so check them by hand: the next migration rebuilds each unnamed JSON index once, and on MongoDB Atlas a vector `$sort`’s `$project` now holds the distance, lower nearer, so a check like `score > 0.8` flips into a cut-off on the distance. The [upgrade guide](https://uql-orm.dev/upgrade-guide.md) has the rest, release by release. ## Next: v1 UQL is close to v1. The next release we are aiming for is the first v1 beta: the API in this post is the one we plan to ship. Try it, and [open an issue](https://github.com/rogerpadilla/uql/issues) for anything that reads wrong or gets in your way. What you hit now shapes v1. # What a rename breaks: six TypeScript ORMs > Renaming a field, a foreign key and a relation in Drizzle, MikroORM, Prisma, Sequelize, TypeORM and UQL. Four of the six let a stale name compile. Source: https://uql-orm.dev/blog/what-a-rename-breaks Type safety is part of why you pick a TypeScript ORM. Then you press F2, the editor renames what it can see, and the rest of the schema quietly keeps the old name. One model, 19 places that name three of its members: indexes, both sides of a relation, a check constraint, a projection, raw SQL in a filter. I pressed F2 on `emailAddress` to `email`, `employerId` to `workplaceId`, `employer` to `workplace` in each and counted what got left behind. - renamed - stopped by the compiler - left behind silently ```ts import { count, eq, relations, type SQL, sql } from 'drizzle-orm'; import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import { check, index, integer, pgTable, serial, text, uniqueIndex, } from 'drizzle-orm/pg-core'; export const companies = pgTable('Company', { id: serial().primaryKey() }); export const users = pgTable( 'User', { id: serial().primaryKey(), emailAddress: text().notNull(), employerId: integer().references(() => companies.id), // Generated column emailLower: text().generatedAlwaysAs( (): SQL => sql`lower(${users.emailAddress})`, ), }, (t) => [ // Index on the field index().on(t.emailAddress), // Composite unique index uniqueIndex().on(t.emailAddress, t.employerId), // Covering index column | n/a: Drizzle's index builder has no INCLUDE // Expression index index().on(sql`lower(${t.emailAddress})`), // Partial index condition index() .on(t.employerId) .where(sql`${t.emailAddress} <> ''`), // Check constraint check('address_present', sql`${t.emailAddress} <> ''`), ], ); export const usersRelations = relations(users, ({ one }) => ({ // Foreign key of a relation employer: one(companies, { fields: [users.employerId], references: [companies.id], }), })); export const companiesRelations = relations(companies, ({ many }) => ({ // Inverse side of a relation staff: many(users), })); const schema = { companies, users, usersRelations, companiesRelations }; declare const db: NodePgDatabase; // Field in the projection await db.select({ id: users.id, address: users.emailAddress }).from(users); // Field in the filter await db.select().from(users).where(eq(users.emailAddress, 'ada@example.com')); // Field in the sort await db.select().from(users).orderBy(users.emailAddress); // Field inside a loaded relation await db.query.companies.findMany({ with: { staff: { columns: { emailAddress: true } } }, }); // Relation loaded by name await db.query.users.findMany({ with: { employer: true } }); // Field in inserted data await db.insert(users).values({ emailAddress: 'ada@example.com' }); // Field in updated data await db .update(users) .set({ emailAddress: 'ada@example.com' }) .where(eq(users.id, 1)); // Foreign key in a grouped count await db .select({ company: users.employerId, total: count() }) .from(users) .groupBy(users.employerId); // Field read off the result const [user] = await db.select().from(users); export const address = user.emailAddress; // Raw SQL in a filter await db .select() .from(users) .where(sql`lower(${users.emailAddress}) = ${'ada@example.com'}`); ``` rename-safety/drizzle.ts · static preview ## Two ways to miss A name the rename missed fails in one of two ways, and they are not the same problem. Some stop compiling. That costs an afternoon: `tsc` hands you the list, you work through it, nothing reaches production. The rest compile. The build is green, the tests that don’t touch that query pass, and the failure turns up later as a column that isn’t there. | ORM | Followed the rename | Stopped by the compiler | Left behind silently | | - | - | - | - | | UQL | 19 | 0 | 0 | | Drizzle | 14 | 4 | 0 | | TypeORM | 12 | 0 | 5 | | Prisma | 4 | 7 | 3 | | Sequelize | 4 | 0 | 12 | | MikroORM | 3 | 13 | 3 | Rows don’t all add up to 19: where an ORM can’t express a probe, there’s nothing to rename and nothing to count. ## Don’t read the first column on its own MikroORM follows the fewest renames of the six, yet it is among the safest. Its `defineEntity` builder types index properties against the entity, so the stale name in `{ properties: ['emailAddress'] }` is a compile error. 13 of its misses stop the build, 3 get through. Go by the leftmost column and you’d worry about the wrong tool. I did, for about a day. Sequelize is the one to worry about. Its classes are properly typed and `InferAttributes` does real work on the model, but everything around the model takes strings, and nothing checks them: ```ts title="Sequelize" // an index on a column that will not exist User.init(attributes, { sequelize, indexes: [{ fields: ['emailAddress'] }] }); // an association pointing at a key that will not exist User.belongsTo(Company, { foreignKey: 'employerId', as: 'employer' }); // queries asking for an attribute and a relation that will not exist await User.findAll({ attributes: ['id', 'emailAddress'] }); await User.findAll({ include: ['employer'] }); ``` All four compile after the rename. So do 12 of the 19 probes, and nothing warns you about any of them. ## TypeORM: decorators fine, strings not In TypeORM, the decorators aren’t the problem. `@Index((user: User) => [user.employerId])` takes a callback, so F2 edits it and a stale name is a type error. The SQL inside those same decorators doesn’t: ```ts title="TypeORM" @Index((user: User) => [user.employerId], { where: `"emailAddress" <> ''` }) @Check(`"emailAddress" <> ''`) @Column({ generatedType: 'STORED', asExpression: 'lower("emailAddress")' }) ``` The callback half renames and the string half doesn’t. Three of TypeORM’s 5 silent misses are that pattern; the other two are an inverse relation and a query. The whole table comes down to one question: whether the name goes through something the compiler resolves. `mappedBy((user) => user.employer)` is a property read. `as: 'employer'` is a string that looks like one. Drizzle sits high because its schema is values its queries import, so a stale name either follows or fails to compile. UQL follows all 19 because it never took a string option anywhere, indexes, checks and raw SQL included. --- The files, the renames and every verdict are [ts-orm-benchmark](https://github.com/rogerpadilla/ts-orm-benchmark#rename-safety)’s, on each ORM’s current stable release and its most type-safe entity API. Every rename is TypeScript 7.0.2’s own, or prisma-language-server 31.13.0’s for `schema.prisma`. I wrote UQL, so weigh that last row accordingly and then go check it: [the rename page](https://uql-orm.dev/rename-safety.md) runs the real compiler in your browser instead of showing you my screenshot of it. Press F2 yourself. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # What does an ORM really cost you? > A full PostgreSQL round trip through six TypeScript ORMs, and what each adds over hand-written driver code. The totals hide where the time goes. Source: https://uql-orm.dev/blog/what-orms-really-cost My benchmark now runs real PostgreSQL round trips. Six ORMs, one PostgreSQL, and a full lifecycle per pass: insert 10 rows, read 200 back with a filter and a sort, update one, read it again, load 50 parents with their children, delete, read the empty table. Every step is timed on its own, median of 250 interleaved iterations. ## The results | Entry | Adds | Total | | - | - | - | | UQL | +232µs | 1,621µs | | Drizzle | +685µs | 2,074µs | | TypeORM | +838µs | 2,227µs | | Sequelize | +1,185µs | 2,574µs | | Prisma | +1,345µs | 2,734µs | | MikroORM | +2,236µs | 3,625µs | > Figures as measured when this was written, on `pg` throughout. The harness is re-run as versions move, so the [current results](https://uql-orm.dev/benchmark.md) will differ. **Adds** is the number to read. Every entry pays the same PostgreSQL bill, so the totals compress into a 2.2x range and the ORMs look alike. Subtract the floor, hand-written SQL with rows mapped by hand at 1,389µs, and what is left is the ORM’s own cost, which spans 9.6x. Everything above runs on node-postgres, so the driver is not the variable. Four of the six support nothing else. ## Prisma Prisma is not slow across the board, and it does not finish last: MikroORM does, at 3,625µs against Prisma’s 2,734µs. Prisma’s nested read, the hardest step in the set, is the second fastest of any ORM here at 440µs. Its update, delete and single-row reads are all mid-field. It is one step: | INSERT 10 rows | | | - | - | | raw pg (hand-written) | 454µs | | UQL | 488µs | | MikroORM | 625µs | | Drizzle | 635µs | | Sequelize | 643µs | | TypeORM | 668µs | | **Prisma** | **1,366µs** | That step is 2.0x the next slowest ORM, and most of why Prisma places fifth. Turning on its query log shows what it sends: ```sql title="What Prisma sends for createManyAndReturn" INSERT INTO "public"."User" ("name","email","companyId") VALUES ($1,$2,$3), ($4,$5,$6), ... COMMIT ``` So `createManyAndReturn` wraps the batch in an explicit transaction, where the other five send one statement. That is reasonable, but it does not explain the gap: a BEGIN/COMMIT pair costs 88µs on this machine, and the gap to TypeORM, the next slowest, is 698µs. The transaction is about an eighth of it. The rest is Prisma’s own overhead on the way in and out, which you cannot opt out of. Prisma 7 dropped its Rust query engine for a TypeScript client runtime, so this is the faster Prisma, not the old one. ## The nested read is where ORMs are actually decided It is the only step that loads a relation, and it has the widest spread of any read: | SELECT 50 parents with their children | | | - | - | | raw pg (hand-written) | 256µs | | UQL | 346µs | | Prisma | 440µs | | TypeORM | 498µs | | Drizzle | 535µs | | Sequelize | 680µs | | MikroORM | 1,205µs | Turning two result sets into an object graph without an N+1 is an ORM’s main job, and here the field spans 3.5x. ## Run it yourself ```bash git clone https://github.com/rogerpadilla/ts-orm-benchmark.git cd ts-orm-benchmark bun install DATABASE_URL=postgres:///postgres npm run bench ``` It creates its own database and rewrites its own result tables, so the published numbers cannot drift from the last run. CI runs the full lifecycle with assertions on every push. The latest set always lives on the [benchmark page](https://uql-orm.dev/benchmark.md), and there is a feature-by-feature [comparison](https://uql-orm.dev/comparison.md) if speed is not your only axis. If your numbers come out different, open an issue. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.* # Zero dependencies: what we deleted > uql-orm installs one package, 288 kB on the wire, no runtime dependencies, every dialect included. Here is what came out to get there. Source: https://uql-orm.dev/blog/zero-dependencies `npm i uql-orm` installs one package. No dependencies, every dialect included. A month ago it pulled in four mandatory packages, roughly 4 MB unpacked; now it is 992 KB. ## One release, four dependencies gone `0.21.0` did it in one pass: \~4.0 MB down to 992 KB, cold start from 16.9 ms to 8.9 ms. Four packages, one job each, none worth a dependency of its own. `tslib` existed so TypeScript’s helper functions didn’t repeat across files. `"importHelpers": false` costs a few hundred bytes per file instead of a dependency edge. `sqlstring` escaped MySQL and MariaDB literals, badly: a `Uint8Array` came out as `` `0` = 255 `` instead of `X'ff00'`, a plain object as `'[object Object]'`. No crash, no warning, just wrong output. `Dialect.escape` handles all three SQL dialects itself now, byte-for-byte identical across 29 value shapes, and those two cases throw instead of writing garbage. `reflect-metadata` (264 KB) earned its keep with one call, `Reflect.getMetadata('design:type', ...)`, so `@Field()` could guess a column’s type from the property. Optional as of this release, gone two releases later. `jiti` (1.8 MB), a full TypeScript transpiler, existed to read one file: `uql.config.ts`. That’s a lot of compiler to hire for one sticky note. Gone too; the config now needs a runtime that already speaks TypeScript (`bun`, or `node --import tsx`). Then what was never code: 369 sourcemaps nobody opened, and a 108 KB CHANGELOG, shipped in every install. `files` in `package.json` is `["dist", "README.md"]` now. ## Then reflection went too Two releases later, `reflect-metadata` stopped being optional and started being pointless. `0.23.0` moved decorators to the [TC39 standard spec](https://github.com/tc39/proposal-decorators): `@Field()` and `@Id()` require an explicit `type` now, checked against the property, so there’s nothing left to reflect. The full story, including what it cost, is in [Standard decorators: props & cons](https://uql-orm.dev/blog/standard-decorators.md). ## What one `npm i` puts on disk Install one package into an empty project and count the bytes yourself: ```sh npm i --omit=dev uql-orm find node_modules -type f -exec cat {} + | wc -c ``` Unpacked bytes on disk, not the 288 kB you download. Tarballs are compressed, but a cold start loads the unpacked files. | Package | Installed | Files | | - | - | - | | `uql-orm` 0.24.1 | 1.0 MB | 384 | | `@mikro-orm/postgresql` 7.1.9 | 4.7 MB | 1,153 | | `drizzle-orm` 0.45.2 | 9.9 MB | 2,667 | | `sequelize` 6.37.8 | 15.0 MB | 2,708 | | `typeorm` 1.1.0 | 22.5 MB | 3,663 | | `@prisma/client` 7.9.1 | 75.0 MB | 94 | One caveat: 93% of `@prisma/client` is 70 MB of Rust query compilers cross-compiled to WebAssembly, one per engine it supports. UQL ships every dialect too, so per dialect is the fairer view: 4.9 MB for Prisma’s Postgres compiler alone, against 19.9 kB gzipped for UQL’s entire Postgres entry point. No row includes a driver. Add `pg` to any of them and they all grow the same amount. This table is the floor. ## What the small number doesn’t cover UQL is small; your driver may not be. `pg`, `mysql2`, `mariadb`, `mongodb` and `better-sqlite3` carry their own weight, and the last needs a native build. UQL’s promise is narrower than “small”: it adds nothing on top of whichever one you picked. Every entry point has a gzip budget checked on every build, added after 0.13.0 let `node:async_hooks` leak into browser bundles and had to be pulled. ## Get started ```sh npm i uql-orm ``` - **[Quick Start](https://uql-orm.dev/getting-started.md)** - **[Standard decorators: props & cons](https://uql-orm.dev/blog/standard-decorators.md)** - **[Comparison](https://uql-orm.dev/comparison.md)** - **[GitHub](https://github.com/rogerpadilla/uql)** If your install contains something that shouldn’t be there, open an issue. --- --- *[UQL](https://uql-orm.dev/index.md) is a JSON-native TypeScript ORM for Node.js and Bun. Supports PostgreSQL, PGlite, MySQL, MariaDB, MSSQL, SQLite, CockroachDB, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.*