uql-orm 0.107.1 → 0.107.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,10 +30,10 @@
30
30
  ---
31
31
 
32
32
  ```sh
33
- npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @tursodatabase/serverless, @libsql/client
33
+ npm install uql-orm pg
34
34
  ```
35
35
 
36
- That is the whole install ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata`; the decorators are the [TC39 standard spec](https://uql-orm.dev/entities/basic), and an entity can be declared as data instead, its row type derived, via [`defineEntity`](https://uql-orm.dev/entities/define-entity).
36
+ That is the whole install, `pg` swapped for your database's driver: `mysql2`, `mariadb`, `better-sqlite3`, `mongodb`, `@tursodatabase/serverless` or `@libsql/client` ([setup](https://uql-orm.dev/getting-started)). No compiler flags and no `reflect-metadata`; the decorators are the [TC39 standard spec](https://uql-orm.dev/entities/basic), and an entity can be declared as data instead, its row type derived, via [`defineEntity`](https://uql-orm.dev/entities/define-entity).
37
37
 
38
38
  <a href="https://uql-orm.dev">
39
39
  <picture>
@@ -86,6 +86,8 @@ export class Post {
86
86
  Or declare one as data, its row type derived:
87
87
 
88
88
  ```ts
89
+ import { defineEntity, f } from 'uql-orm';
90
+
89
91
  export const Post = defineEntity({
90
92
  name: 'Post',
91
93
  fields: {
@@ -94,7 +96,12 @@ export const Post = defineEntity({
94
96
  likes: f.number().nullable(),
95
97
  authorId: f.number().nullable(),
96
98
  },
97
- }).relations((rel) => ({ author: () => rel.manyToOne(User, { references: (post) => post.authorId }) }));
99
+ }).relations((rel) => ({
100
+ author: () => rel.manyToOne(User, { references: (post) => post.authorId }),
101
+ }));
102
+
103
+ // One name for the entity and its rows, as a class has: a function takes `post: Post`.
104
+ export type Post = InstanceType<typeof Post>;
98
105
  ```
99
106
 
100
107
  ### 2. A pool, and the migrations it drives
@@ -112,7 +119,7 @@ export default { pool, entities: [User, Post] } satisfies Config;
112
119
 
113
120
  ```sh
114
121
  npm i -D tsx # Node only: the CLI loads uql.config.ts through it
115
- npx uql-migrate generate:entities initial # diffs the entities against the database into a migration you review
122
+ npx uql-migrate generate:entities initial # writes the diff against the database, to review
116
123
  npx uql-migrate up # applies it
117
124
  ```
118
125
 
@@ -142,7 +149,6 @@ The same queries run from the browser too: [serve them over HTTP](https://uql-or
142
149
 
143
150
  - **One API, everywhere it runs.** PostgreSQL, PGlite, CockroachDB, MySQL, MariaDB, MSSQL, SQLite, Turso, libSQL, Neon, Cloudflare D1, Bun's native SQL, and even MongoDB. The same code on Node 22.18+, Bun, [Cloudflare Workers](https://uql-orm.dev/cloudflare-d1), [AWS Lambda and Vercel](https://uql-orm.dev/serverless), and [the browser](https://uql-orm.dev/browser), with no native binaries on the `fetch`-based drivers.
144
151
  - **Type-safe to the leaf, nothing to generate.** Every key is checked against your entity, down into populated relations and [JSON/JSONB](https://uql-orm.dev/querying/json) dot-paths, so `$like` on a numeric column is a compile error. No `.prisma` file, no generated client.
145
- - **Relations without N+1.** [`$populate`](https://uql-orm.dev/querying/relations) reads a to-many inside the parent's statement, so a read is one round trip. Nothing is lazy, so nothing fires behind your back in a serializer.
146
152
  - **Light.** Zero runtime dependencies and every dialect in one package, yet `uql-orm/postgres` is about 27 kB gzipped. See [what we deleted to get there](https://uql-orm.dev/blog/zero-dependencies).
147
153
  - **The hard things are built in.** [Semantic and vector search](https://uql-orm.dev/ai-semantic-search), [multi-tenant filters you cannot bypass by accident](https://uql-orm.dev/multi-tenancy), [soft-delete with restore](https://uql-orm.dev/entities/soft-delete), [streaming](https://uql-orm.dev/querying/streaming), and [drift checks](https://uql-orm.dev/migrations) that catch a database that no longer matches.
148
154
  - **SQL when you need it.** [`sql()`](https://uql-orm.dev/querying/raw-sql) fits anywhere a value or a field goes, [computed fields](https://uql-orm.dev/entities/computed-fields) are SQL you can filter and sort on, and a migration can be plain SQL.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.107.1",
6
+ "version": "0.107.3",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -3,8 +3,8 @@ name: uql-orm
3
3
  description: >
4
4
  Write code with UQL (the uql-orm package), the TypeScript ORM whose queries are plain JSON objects,
5
5
  on PostgreSQL, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, MongoDB, Turso, Neon, D1 and PGlite.
6
- Use when a project imports uql-orm, or when defining entities or triggers, querying, populating relations,
7
- writing transactions, raw SQL or migrations with it. UQL is not Prisma, Drizzle, TypeORM or MikroORM:
6
+ Use when a project imports uql-orm, or when defining entities, triggers or filters (soft delete, multi-tenancy),
7
+ querying, populating relations, writing transactions, raw SQL or migrations with it. UQL is not Prisma, Drizzle, TypeORM or MikroORM:
8
8
  their APIs do not carry over.
9
9
  ---
10
10
 
@@ -22,9 +22,7 @@ npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/
22
22
 
23
23
  ESM only. Needs Node 22.18+, Bun or an edge runtime, and TypeScript 5.7+.
24
24
 
25
- Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. A project on legacy decorators (NestJS, Angular) keeps its config and defines entities with `defineEntity`: https://uql-orm.dev/entities/define-entity.md
26
-
27
- Node runs no decorators natively yet, so add `tsx` there (`npm i -D tsx`); `uql-migrate` loads `uql.config.ts` through it. A bundler that minifies class names needs `@Entity({ name: 'todo' })`, since the table name defaults to the class name.
25
+ Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. Node runs no decorators natively yet, so add `tsx` there (`npm i -D tsx`); `uql-migrate` loads `uql.config.ts` through it. A bundler that minifies class names needs `@Entity({ name: 'todo' })`, since the table name defaults to the class name.
28
26
 
29
27
  ```ts
30
28
  // uql.config.ts
@@ -39,8 +37,19 @@ export default { pool, entities: [User, Post] } satisfies Config;
39
37
 
40
38
  Driver entry points: `uql-orm/postgres`, `mysql`, `mariadb`, `sqlite`, `mongodb`, `libsql`, `turso`, `neon`, `d1`, `pglite`, `bun-sql`, `mssql`, `cockroachdb`. Build the pool once per process and import it.
41
39
 
40
+ The pool's first argument is the driver's own config; set an acquire timeout there (`connectionTimeoutMillis` on the `pg` family), which otherwise waits forever. The second holds uql's options: `namingStrategy: new SnakeCaseNamingStrategy()` maps `createdAt` to `created_at` in queries and migrations alike (never name each column by hand), `logger: true` or a level list, `slowQuery: 200` (ms), and a default `schema`. Call `await pool.end()` on shutdown, except in serverless functions: https://uql-orm.dev/pool.md
41
+
42
42
  ## Entities
43
43
 
44
+ Two forms, mixable per entity, producing the same queries and types:
45
+
46
+ - **Decorators**: a named class type, base classes carrying fields and relations, and column-level foreign keys (`f.references`), so entities may reference each other in any order. Each field is written twice (builder and property), and it needs the TC39 decorator transform.
47
+ - **`defineEntity`**: the row type is derived, nothing written twice; no transform, so it fits projects on legacy decorators (NestJS, Angular), and it can be built at run time. Cheaper to type-check. Relations come last, and the row type needs a `type X = InstanceType<typeof X>` alias.
48
+
49
+ `uql-codemod` cannot convert one form into the other. Details: https://uql-orm.dev/entities/define-entity.md
50
+
51
+ ### Decorators
52
+
44
53
  ```ts
45
54
  import { Entity, f, Field, ManyToOne, OneToMany } from 'uql-orm';
46
55
 
@@ -77,65 +86,26 @@ export class Post {
77
86
  }
78
87
  ```
79
88
 
80
- - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal()`, `f.decimal(precision)`, `f.decimal(precision, scale)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other column type, and `f.references(() => Target)` for a foreign key, which takes the target's key type. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A bound holds in either order around `.columnType('char')`, but not around a `sql` type, which carries its own.
81
- - A column is NOT NULL unless `.nullable()`; its property then admits `null` (`title?: string | null`).
82
- - A JSON column's property is `Json<T>`, where `T` is the payload: `settings?: Json<{ theme?: string }> | null`, or `Json<z.infer<typeof Settings>>` for a schema. A plain object type reads as a relation, and `$where`, `$sort` and the update operators refuse it.
83
- - Declare a NOT NULL column with `!` (`email!: string`). Declare `?` for anything else an insert may omit: nullable columns, `.eager(false)` fields, and relations. A computed field is present on a default read, so it is not optional. uql fills a single-column key and a version.
84
- - A NOT NULL field a default fills (`.default()`, `.onInsert()`) is `!` and listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
89
+ - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal(precision?, scale?)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other type, and `f.references(() => Target)` for a foreign key typed as the target's key. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's.
90
+ - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the single-column key and version uql fills. A NOT NULL field a default fills (`.default()`, `.onInsert()`) stays `!` and is listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
85
91
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included.
86
- - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring indexes, filters, checks or triggers but no table is `@Entity({ abstract: true, ... }) abstract class`, or `abstract: true` in `defineEntity`. A query or write on one does not compile: query the entities extending it.
87
- - `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`). `f.number().precision(10).scale(2)` opts into a rounding JS number.
88
- - Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`. Either may be left out where only one member fits: a decorated many-to-one's one foreign key to its target, a one-to-many's one many-to-one pointing back.
89
- - `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows in the same transaction; an update replaces a to-many's rows.
90
- - **MongoDB:** a key declared `f.number()` and left to the database is refused, since MongoDB only generates ObjectIds. Declare the key a string, or give it an `.onInsert()` generator.
91
- - Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update must carry the version it read. A stale one throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409).
92
- - Computed fields are `readonly` and read in any query that names them. As SQL over the row, ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` making a generated column, or as a relation aggregate: `@Computed((user) => user.resources.count())`.
93
- - Indexes, checks, filters and triggers are `@Entity` options, each entry made by the helper the callback is handed. Partial index: `@Entity({ indexes: (post, index) => [index([post.authorId], { where: { archived: { $ne: true } } })] })`; a string second argument is the index's name. Write the predicate as a query, not `sql`.
94
- - JSON path index: read the path off the column's ref, `index([user.settings.theme])` for text, `index([{ column: user.settings.rating, type: Number }])` for any other value, `type: [String]` for an array's elements. MySQL keys a text path or element as `CHAR(n)`, `{ column: user.tags, type: [String], charLength: 64 }`, and a `TEXT` column by a prefix, `{ column: post.body, prefixLength: 64 }`.
95
- - Triggers run in the database: `@Entity({ triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })] })`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. A trigger's writes skip uql's fills and entity filters. MongoDB has no triggers: https://uql-orm.dev/entities/triggers.md
96
-
97
- ### Choosing a form
98
-
99
- Both forms are supported, mix them per entity, and produce the same queries and types.
100
-
101
- - Decorators
102
- - Pros
103
- - A named class type shows on hover.
104
- - A column can be a foreign key (`@Field(f.references(() => User))`), so entities may reference each other in any order.
105
- - No `.relations()` ordering rules.
106
- - Shared structure through base classes (`StampedEntity`, `WorkspaceScoped`) that carry fields and relations.
107
- - The familiar form from TypeORM and MikroORM.
108
- - Cons
109
- - Each field is written twice, as a builder and as a TypeScript property (`@Field(f.string()) name!: string`).
110
- - The TC39 decorator transform is required: Node needs `tsx`, and some bundlers need a Babel step.
111
- - Without `@Entity({ name })`, the table name comes from the class name, which a minifier can change.
112
- - Higher type-check cost on the benchmark model (9,297 vs 5,110 instantiations).
113
- - Cannot be declared at run time.
114
- - `uql-codemod` cannot convert it into `defineEntity`.
115
- - `defineEntity`
116
- - Pros
117
- - The row type is derived from the builders, with nothing written twice.
118
- - Shorter: 19 to 30% fewer lines in the two apps this was measured on.
119
- - Lower type-check cost on the benchmark model.
120
- - Shared relation helpers, and derived fields declared with their relations.
121
- - Plain data: no transform, and it can be built at run time (a CMS content type).
122
- - The form for projects that cannot enable TC39 decorators, such as legacy-decorator NestJS and Angular.
123
- - Cons
124
- - Relations are thunks declared after the columns, and `.relations()` comes last (only `.filters()` may follow it).
125
- - No column-level foreign keys: a shared key is a relation helper, and an eager read across two entities can create an inference cycle (TS7022).
126
- - Each entity needs a `type X = InstanceType<typeof X>` alias for its name.
127
- - No class to annotate or extend: inheritance uses `extends` naming the base.
128
- - Newer and less used.
92
+ - `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
93
+ - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
94
+ - `mappedBy` and `references` may be left out where only one member fits. `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows in the same transaction; an update replaces a to-many's rows.
95
+ - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
96
+ - Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update must carry the version it read; a stale one throws `UqlOptimisticLockError`.
97
+ - Computed fields are `readonly`: ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` for a generated column, or a relation aggregate, `@Computed((user) => user.posts.count())`.
98
+ - Indexes, checks, filters and triggers are `@Entity` options, each entry made by the helper the callback is handed. A partial index's predicate is a query: `indexes: (post, index) => [index([post.authorId], { where: { archived: { $ne: true } } })]`. A JSON path is indexed off the column's ref, `index([user.settings.theme])`: https://uql-orm.dev/entities/indexes.md
99
+ - Triggers run in the database: `triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })]`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. They skip uql's fills and entity filters. MongoDB has none: https://uql-orm.dev/entities/triggers.md
100
+ - Hooks are methods with `this` bound to the payload: `@BeforeInsert()`, `@AfterInsert()`, and the same pairs for update, upsert and delete, plus `@AfterLoad()`. Changes to `this` in a before-hook are written. `upsert*` runs only the upsert pair, and `save*` the upsert pair for a row carrying its key. Each receives `{ querier, onCommit }`: send mail from `onCommit`, never straight from an after-hook.
101
+ - **MongoDB:** a `f.number()` key left to the database is refused, since MongoDB only generates ObjectIds. Declare it a string, or give it an `.onInsert()` generator.
129
102
 
130
103
  ### defineEntity
131
104
 
132
- The same entities declared as data, the row type derived:
133
-
134
105
  ```ts
135
106
  import { defineEntity, f, sql } from 'uql-orm';
136
107
  import { z } from 'zod';
137
108
 
138
- // Any Standard Schema types the payload: a Zod schema here.
139
109
  const Settings = z.object({ theme: z.string(), bio: z.string().optional() });
140
110
 
141
111
  export const Author = defineEntity({
@@ -147,16 +117,7 @@ export const Author = defineEntity({
147
117
  },
148
118
  }).relations(
149
119
  (rel) => ({ books: () => rel.oneToMany(Book, { mappedBy: (book) => book.author }) }),
150
- (author) => ({
151
- bookCount: () => author.books.count(),
152
- topStock: () => author.books.max((book) => book.stock),
153
- // A derived field may also combine its own columns with an aggregate in one expression.
154
- stockGap: () =>
155
- f
156
- .number()
157
- .nullable()
158
- .as(sql`${author.books.max((book) => book.stock)} - ${author.id}`),
159
- }),
120
+ (author) => ({ bookCount: () => author.books.count() }),
160
121
  );
161
122
  export type Author = InstanceType<typeof Author>;
162
123
 
@@ -167,25 +128,54 @@ export const Book = defineEntity({
167
128
  title: f.string(),
168
129
  stock: f.number().default(0),
169
130
  authorId: f.number(),
170
- editorId: f.number().nullable(),
171
131
  },
172
132
  })
173
133
  .computed((book) => ({ shout: f.string().as(sql`upper(${book.title})`) }))
174
134
  .indexes((book, index) => [index([book.title])])
175
- .hooks({ beforeInsert: [(book) => void (book.stock ??= 0)] })
176
135
  .relations((rel) => ({
177
136
  author: () => rel.manyToOne(Author, { references: (book) => book.authorId }),
178
- editor: () => rel.manyToOne(Author, { references: (book) => book.editorId, onDelete: 'SET NULL' }),
179
137
  }));
180
138
  ```
181
139
 
182
- - Each field is a column builder, as in the decorated form. The row follows from them: a key, a version and a NOT NULL column are always present, a `.nullable()` one reads `| null`; a default (`.default()`, `.onInsert()`, `.autoIncrement()`) makes it optional on insert; `f.enum()` gives the literal union. No `!`, `?` or brands to write.
183
- - The other options are sections chained after `defineEntity`, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters` and `hooks` read the columns; `relations` comes last, but for a `filters` that reads through them: `.relations(...).filters({ byActiveAuthor: { where: { author: { active: true } } } })`. `defineEntity` itself takes `name` (the class name, which a naming strategy derives the table from), `table`, `schema`, `extends`, `abstract` and `fields`.
184
- - Each relation is a thunk, `author: () => rel.manyToOne(...)`, so entities pointing at each other can sit in either order and in different files. In `defineEntity`, a foreign key is a relation: `manyToOne` names its `references` column, whose type is checked against the target's key; the column itself stays a plain field. `oneToMany(Book)` with no options is mapped by the one relation of `Book` pointing back.
185
- - `relations`' second callback declares the derived fields: each value is a thunk, read lazily, of an aggregate over a to-many (`() => author.books.count()`) or a column expression. The callback's refs are the entity's own columns and its relations, so one expression can combine them.
186
- - A hook is a function of the row and `{ querier, onCommit }`.
187
- - A JSON column's payload is a Standard Schema, `f.json(schema)`, typed by its output: any library's schema (Zod, Valibot, ArkType), or a hand-written `StandardSchemaV1`. Without one, any path reads. The schema types the column; uql never runs it, so a write is not validated.
188
- - Behaviour is a function of the row, `label(author: Author)`: a row reads back as a plain object, so a method would never be there.
140
+ - Columns are the same builders. No `!`, `?` or brands to write: a `.nullable()` column reads `| null`, a default makes it optional on insert, `f.enum()` gives the literal union.
141
+ - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `hooks`, then `relations` last; only a `filters` reading through relations follows it.
142
+ - A relation is a thunk, so entities pointing at each other can sit in any order and file. A foreign key is a plain field that a `manyToOne` names as `references`, checked against the target's key type. `relations`' second callback declares derived fields: aggregates over a to-many, or expressions mixing them with columns.
143
+ - A JSON column's payload is any Standard Schema (Zod, Valibot, ArkType), typed by its output. uql never runs it, so a write is not validated.
144
+ - A hook is a function of the row and `{ querier, onCommit }`. Behaviour is a plain function of the row (`label(author: Author)`): a row reads back as a plain object, so a method would never be there.
145
+
146
+ ### Filters, soft delete and tenants
147
+
148
+ A filter is a named `$where` fragment applied to every read, update and delete of its entity, so never repeat it in a query.
149
+
150
+ ```ts
151
+ import { Entity, f, Field, withContext } from 'uql-orm';
152
+
153
+ declare module 'uql-orm' {
154
+ interface UqlContext {
155
+ tenantId?: number;
156
+ }
157
+ }
158
+
159
+ @Entity({
160
+ filters: {
161
+ active: { where: { status: 'active' }, default: false },
162
+ tenant: { where: (ctx) => (ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined), security: true },
163
+ },
164
+ })
165
+ export class Invoice {
166
+ @Field(f.number().id()) id?: number;
167
+ @Field(f.number()) companyId!: number;
168
+ @Field(f.string().nullable()) status?: string | null;
169
+ @Field(f.date().nullable().softDelete()) deletedAt?: Date | null;
170
+ }
171
+
172
+ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
173
+ ```
174
+
175
+ - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
176
+ - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
177
+ - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`. Its keys are typed by augmenting `UqlContext`, as above.
178
+ - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
189
179
 
190
180
  ## Queries
191
181
 
@@ -203,37 +193,45 @@ const users = await pool.findMany(User, {
203
193
  });
204
194
  ```
205
195
 
206
- - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`. `$count: { posts: true }` counts a to-many under `_count` without loading it. `$select: { password: false }` reads every field but `password`.
207
196
  - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first, or the query's `$entity`. Signatures: https://uql-orm.dev/querying/methods.md
208
- - Results are narrowed to what the query selected and populated, at every depth of `$populate`. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing by typing it `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`; typed `Query<E>`, it reads whole rows.
209
- - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list, empty when there are no children. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
210
- - `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, plus `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`, which behave the same on every engine. Unqualified, each engine keeps its own null order.
211
- - `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`, `$isNotNull`. Combine with `$and`, `$or`, `$not`, `$nor`. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
197
+ - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
198
+ - Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
199
+ - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
200
+ - `$sort` takes `'asc'`/`1`, `'desc'`/`-1`, or `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`, which behave the same on every engine.
201
+ - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique NOT NULL field; no `$skip`.
202
+ - `$lock: true` locks the rows a read returns, inside an open transaction; `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. The SQLite family and MongoDB refuse it.
203
+
204
+ ### `$where`
205
+
206
+ - `$where` takes a value for equality, a list as an implicit `$in`, or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$between`, `$in`, `$nin`, `$isNull`, `$isNotNull`, `$not`. Combine with `$and`, `$or`, `$not`, `$nor`. A field takes only the operators its type allows.
207
+ - Text: `$like`, `$startsWith`, `$endsWith`, `$includes`, each with a case-insensitive `i` form (`$ilike`, `$istartsWith`, ...). `$like` reads `%`, `_` and `\` the same on every engine; the other three take their text literally. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
208
+ - Arrays and JSON: `$all: ['a', 'b']`, `$size: 3` or `{ $gte: 2 }`, `$elemMatch: { city: 'NYC', zip: { $startsWith: '10' } }`. A JSON path filters like a field: `{ 'settings.billing.plan': 'pro' }`.
209
+ - A relation key keeps the parents with a matching related row, as an `EXISTS`, never duplicating them: `{ posts: { title: { $iincludes: 'orm' } } }`, or by count: `{ posts: { $size: { $gte: 5 } } }`. For a subquery no relation covers, `$exists` / `$nexists` take a `sql` fragment.
210
+ - Full-text: `$where: { $text: { $value: 'wireless keyboard' } }` searches the entity's fulltext index; `$sort: { $text: 'desc' }` ranks by relevance.
211
+ - Vectors: `$sort: { embedding: { $vector: v } }` with a `$limit` returns the nearest; `$where: { embedding: { $near: { $vector: v, $lt: 0.35 } } }` keeps only close rows; `$candidates` tunes ANN recall.
212
212
  - An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
213
- - NULL compares as the engine does: on SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
214
- - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does. It returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique NOT NULL field, and takes no `$skip`.
215
- - `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update payload with operators. Without `update`, a conflicting row takes the payload but keeps its own key. Resolves to the row's id.
216
- - Writes take `{ returning: { id: true } }` as their last argument and resolve to those rows. Without it, inserts and upserts resolve to ids, and updates and deletes to a count.
217
- - `updateMany` and `deleteMany` that name no rows throw: no `$where` holding a value, and no `$limit`. Pass `{ unfiltered: true }` to mean the whole table.
218
- - Updates use operators: `{ stock: { $inc: -1 } }` or `$mul`, with NULL counted as 0. Put a guard in `$where` (`stock: { $gte: 1 }`) to make a decrement race-safe.
219
- - JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order on one value. `$set` and `$unset` take keys or dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`.
220
- - `$lock: true` locks the rows a read returns, and `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. It needs an open transaction. SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
213
+ - On SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
214
+
215
+ ### Writes
216
+
217
+ - Without options, inserts and upserts resolve to ids, updates and deletes to a count. A last argument `{ returning: { id: true } }` resolves to those rows instead.
218
+ - `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update` (an update payload), else the payload but keeping its own key.
219
+ - `updateMany` and `deleteMany` that name no rows (no `$where` holding a value, no `$limit`) throw. Pass `{ unfiltered: true }` to mean the whole table.
220
+ - Update operators: `{ stock: { $inc: -1 } }` or `$mul`, with NULL counted as 0. A guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order; `$set` and `$unset` take dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`.
221
+
222
+ ### Raw SQL and errors
223
+
224
+ - ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object. `sql` builds a fragment, `sql.join(fragments, ' AND ')` joins them, and `sql.text(s)` runs trusted SQL held in a string: never user input.
225
+ - A condition no operator expresses is a `sql` fragment beside the others, naming columns through `refs()`, never by string: ``const item = refs(Item); $where: { $and: [{ companyId: 1 }, sql`${item.price} * ${item.stock} > ${10000}`] }``. SQL databases only.
221
226
  - `queryErrorKind(err)` names a failure the same on every engine: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
222
- - Raw SQL: ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object. `sql` builds a fragment, and `sql.join(fragments, ' AND ')` joins them. `sql.text(s)` runs trusted SQL held in a string. Never build it from user input.
223
227
 
224
228
  ## Aggregates
225
229
 
226
- Compute in SQL, not in code. Loading rows to dedupe, count or sum them in JavaScript costs a round trip and every row.
230
+ Compute in SQL, not in code: loading rows to dedupe, count or sum them in JavaScript costs a round trip and every row.
227
231
 
228
232
  ```ts
229
- import { Post } from './entities.js';
230
- import { pool } from './uql.config.js';
231
-
232
233
  // Distinct values: a $group with no $select returns each once.
233
- const titles = await pool.aggregate(Post, {
234
- $group: { title: true },
235
- $sort: { title: 1 },
236
- });
234
+ const titles = await pool.aggregate(Post, { $group: { title: true }, $sort: { title: 1 } });
237
235
 
238
236
  // Tallies per group, in one statement.
239
237
  const counts = await pool.aggregate(Post, {
@@ -242,16 +240,15 @@ const counts = await pool.aggregate(Post, {
242
240
  });
243
241
  ```
244
242
 
245
- - `$select` takes `$count` (`'*'` or a field), `$countDistinct`, `$sum`, `$avg`, `$min` and `$max`. Over no rows a count is `0` and the others are `null`.
246
- - `$where` on the query filters rows before grouping. An operator's own `$where` filters only the rows that operator reads, which pivots rows into columns in one query: `{ $count: '*', $where: { published: true } }`.
247
- - `$having` and `$sort` name a grouped column or a `$select` alias, never a field that is not grouped.
248
- - A `$group` key can reach a to-one relation's field: `{ orderId: { transaction: { orderId: true } } }`. A to-many cannot be grouped, since it multiplies the rows.
249
- - A per-row count belongs on the entity as a `computed` field, not as an aggregate per request. Counts for a read's rows: `$count: { posts: true }`.
250
- - Details: https://uql-orm.dev/querying/aggregate.md
243
+ - `$select` takes `$count` (`'*'` or a field), `$countDistinct`, `$sum`, `$avg`, `$min` and `$max`. Over no rows a count is `0` and the others `null`.
244
+ - The query's `$where` filters rows before grouping. An operator's own `$where` filters only what it reads, pivoting rows into columns in one query: `{ $count: '*', $where: { published: true } }`.
245
+ - `$having` and `$sort` name a grouped column or a `$select` alias.
246
+ - A `$group` key can reach a to-one relation's field (`{ orderId: { transaction: { orderId: true } } }`), never a to-many's.
247
+ - A per-row count belongs on the entity as a computed field, or on a read as `$count`, not in an aggregate. Details: https://uql-orm.dev/querying/aggregate.md
251
248
 
252
249
  ## Connections and transactions
253
250
 
254
- Every method is on the pool and on a querier. A pool call takes a connection for that call. To run several operations on one connection, or atomically, use a transaction:
251
+ Every method is on the pool and on a querier. A pool call takes a connection for that call. For several operations on one connection, or atomically:
255
252
 
256
253
  ```ts
257
254
  await pool.transaction(async (querier) => {
@@ -260,27 +257,28 @@ await pool.transaction(async (querier) => {
260
257
  });
261
258
  ```
262
259
 
263
- The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A nested `transaction()` is a savepoint; MongoDB refuses it. For a transaction that opens in one place and ends in another, use `beginTransaction`, `commitTransaction` and `rollbackTransaction`. `querier.onCommit(fn)` runs `fn` after the outermost commit and never on rollback: use it for mail and queued jobs. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
264
-
265
- A `findManyStream` holds its querier until the loop ends, and other statements on it are refused meanwhile. Run them after the loop, or on another connection.
260
+ - The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A nested `transaction()` is a savepoint; MongoDB refuses it.
261
+ - `querier.onCommit(fn)` runs `fn` after the outermost commit, never on rollback: use it for mail and queued jobs.
262
+ - A transaction opened in one place and ended in another uses `beginTransaction`, `commitTransaction` and `rollbackTransaction`. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
263
+ - A `findManyStream` holds its querier until the loop ends, refusing other statements meanwhile: run them after the loop, or on another connection.
266
264
 
267
265
  ## Migrations
268
266
 
269
- Upgrading an existing project: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which rewrites what it can and reports the rest. What changed by version: https://uql-orm.dev/upgrade-guide.md
270
-
271
267
  `npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
272
268
 
273
- - `sync`: applies what the entities imply. Development only.
274
- - `generate:entities`: writes the diff as a migration file to review. A renamed column is a drop and an add, unless a naming strategy maps it or you write `renameColumn(table, from, to)`. It refuses a required column with no default on a table that holds rows.
275
- - `up` and `down`: each migration runs in its own transaction, under a lock so concurrent instances run it once. From code, `await new Migrator(pool, { migrationsPath }).up()` before the app starts.
269
+ - `sync`: applies what the entities imply. Development only. `sync --dry-run` prints only the SQL, for another tool to apply.
270
+ - `generate:entities`: writes the diff as a migration file to review. A renamed column is a drop and an add, unless a naming strategy maps it or you write `renameColumn(table, from, to)`. It refuses a required column with no default on a table holding rows.
271
+ - `up` and `down`: each migration in its own transaction, under a lock so concurrent instances run it once. From code: `await new Migrator(pool, { migrationsPath }).up()` before the app starts.
276
272
  - `generate:from-db`: writes entity classes from an existing database.
277
273
  - `drift:check`: fails when the database no longer matches the entities.
278
- - `sync --dry-run`: prints only SQL on stdout, for a migration file another tool applies.
274
+
275
+ Upgrading uql itself: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which rewrites what it can and reports the rest. Breaking changes: https://uql-orm.dev/upgrade-guide.md
279
276
 
280
277
  ## Where to read more
281
278
 
282
279
  - Operators and per-dialect SQL: https://uql-orm.dev/querying/comparison-operators.md
283
- - Relations and deep `$populate`: https://uql-orm.dev/querying/relations.md
284
- - Computed fields and stamps: https://uql-orm.dev/entities/computed-fields.md
280
+ - Relations, relation filters and deep `$populate`: https://uql-orm.dev/querying/relations.md
281
+ - JSON paths and operators: https://uql-orm.dev/querying/json.md
282
+ - Full-text and vector search: https://uql-orm.dev/querying/full-text.md, https://uql-orm.dev/querying/semantic-search.md
283
+ - Computed fields: https://uql-orm.dev/entities/computed-fields.md
285
284
  - Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
286
- - Breaking changes by version: https://uql-orm.dev/upgrade-guide.md