uql-orm 0.107.3 → 0.108.1
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/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +5 -5
- package/dist/cockroachdb/cockroachDialect.d.ts +1 -4
- package/dist/cockroachdb/cockroachDialect.js +1 -5
- package/dist/dialect/abstractSqlDialect.d.ts +84 -43
- package/dist/dialect/abstractSqlDialect.js +270 -192
- package/dist/dialect/aliases.d.ts +2 -0
- package/dist/dialect/aliases.js +2 -0
- package/dist/dialect/jsonSql.d.ts +9 -7
- package/dist/dialect/jsonSql.js +16 -10
- package/dist/dialect/mergeSqlDialect.d.ts +5 -7
- package/dist/dialect/mergeSqlDialect.js +20 -19
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
- package/dist/dialect/mysqlLikeSqlDialect.js +34 -12
- package/dist/dialect/operators.d.ts +7 -1
- package/dist/dialect/operators.js +37 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +4 -4
- package/dist/dialect/pgLikeSqlDialect.js +8 -7
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definedFixture/author.d.ts +4 -4
- package/dist/entity/metadata/definedFixture/book.d.ts +5 -5
- package/dist/entity/metadata/definition.d.ts +2 -0
- package/dist/entity/metadata/definition.js +19 -11
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/mariadb/mariaDialect.js +3 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +28 -7
- package/dist/migrate/ddl/defaultSql.d.ts +3 -2
- package/dist/migrate/ddl/defaultSql.js +8 -12
- package/dist/migrate/ddl/mysqlTableDdl.js +1 -1
- package/dist/migrate/ddl/tableDdl.d.ts +1 -1
- package/dist/migrate/drift/driftDetector.js +10 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +2 -2
- package/dist/migrate/migrator.js +2 -1
- package/dist/migrate/schemaChange.d.ts +0 -2
- package/dist/migrate/schemaChange.js +1 -4
- package/dist/migrate/schemaGenerator.d.ts +2 -2
- package/dist/migrate/triggerSql.js +11 -15
- package/dist/mongodb/mongoDialect.d.ts +6 -1
- package/dist/mongodb/mongoDialect.js +90 -46
- package/dist/mongodb/mongoSchemaGenerator.js +2 -2
- package/dist/mongodb/mongodbQuerier.d.ts +7 -9
- package/dist/mongodb/mongodbQuerier.js +54 -47
- package/dist/mssql/mssqlDialect.d.ts +9 -9
- package/dist/mssql/mssqlDialect.js +51 -28
- package/dist/mssql/mssqlWireTypes.d.ts +1 -4
- package/dist/mssql/mssqlWireTypes.js +19 -10
- package/dist/querier/abstractQuerier.d.ts +53 -29
- package/dist/querier/abstractQuerier.js +154 -102
- package/dist/querier/abstractSqlQuerier.d.ts +41 -10
- package/dist/querier/abstractSqlQuerier.js +145 -79
- package/dist/schema/declaredColumn.js +2 -2
- package/dist/schema/schemaASTDiffer.d.ts +3 -3
- package/dist/schema/sqlExpression.d.ts +7 -5
- package/dist/schema/sqlExpression.js +20 -16
- package/dist/schema/types.d.ts +8 -2
- package/dist/sqlite/sqliteDialect.js +1 -2
- package/dist/type/definedEntity.d.ts +5 -5
- package/dist/type/dialect.d.ts +26 -15
- package/dist/type/entity.d.ts +14 -8
- package/dist/type/query.d.ts +7 -2
- package/dist/type/queryAggregate.d.ts +4 -4
- package/dist/type/querySql.d.ts +4 -1
- package/dist/type/querySql.js +5 -1
- package/dist/type/queryWhere.d.ts +16 -11
- package/dist/type/universalQuerier.d.ts +7 -7
- package/dist/util/ddlExpression.util.d.ts +5 -0
- package/dist/util/ddlExpression.util.js +9 -2
- package/dist/util/dialect.util.d.ts +14 -6
- package/dist/util/dialect.util.js +17 -13
- package/dist/util/field.util.d.ts +12 -0
- package/dist/util/field.util.js +17 -1
- package/dist/util/fieldOption.util.js +5 -1
- package/dist/util/object.util.d.ts +4 -0
- package/dist/util/object.util.js +13 -0
- package/dist/util/query.util.d.ts +5 -3
- package/dist/util/query.util.js +7 -2
- package/dist/util/sql.d.ts +25 -7
- package/dist/util/sql.js +58 -18
- package/dist/util/triggerWrite.d.ts +7 -4
- package/dist/util/triggerWrite.js +5 -4
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +27 -19
package/dist/util/sql.js
CHANGED
|
@@ -88,15 +88,41 @@ export const SQL_VALUES = {
|
|
|
88
88
|
};
|
|
89
89
|
/**
|
|
90
90
|
* The fields of `entity` as {@link ColumnRef}s, each rendering inside `sql` as its column: named the way
|
|
91
|
-
* the dialect names it, so the naming strategy and `.name()` apply, and qualified by the
|
|
92
|
-
* in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
|
|
91
|
+
* the dialect names it, so the naming strategy and `.name()` apply, and qualified by `alias`, or else by the
|
|
92
|
+
* alias in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
|
|
93
93
|
*/
|
|
94
|
-
export function refs(entity) {
|
|
95
|
-
|
|
94
|
+
export function refs(entity, alias) {
|
|
95
|
+
const qualifier = alias === undefined ? undefined : { alias };
|
|
96
|
+
return refMap((key) => columnRef(entity, key, qualifier), () => tableSql(entity, alias));
|
|
96
97
|
}
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
|
|
98
|
+
/**
|
|
99
|
+
* The table `source` names, an entity or the refs read off one under their alias, `"order" "o"`, for raw SQL
|
|
100
|
+
* reading another table than its statement's: `sql`SELECT ${o.state} FROM ${tableOf(o)}``, `o = refs(Order, 'o')`.
|
|
101
|
+
*/
|
|
102
|
+
export function tableOf(source) {
|
|
103
|
+
if (typeof source === 'function') {
|
|
104
|
+
return tableSql(source);
|
|
105
|
+
}
|
|
106
|
+
const table = Reflect.get(source, TABLE);
|
|
107
|
+
if (!(table instanceof QuerySql)) {
|
|
108
|
+
throw new UqlUsageError(`tableOf takes an entity or the refs() read off one, not a definition's refs`);
|
|
109
|
+
}
|
|
110
|
+
return table;
|
|
111
|
+
}
|
|
112
|
+
/** `entity`'s table as its statements name it, under `alias` where one is given. */
|
|
113
|
+
function tableSql(entity, alias) {
|
|
114
|
+
return sql(({ ctx, dialect }) => {
|
|
115
|
+
ctx.append(dialect.tableRef(getMeta(entity), alias).ref);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** Where a refs map keeps the table it reads, for {@link tableOf}: a symbol, so no field can shadow it. */
|
|
119
|
+
const TABLE = Symbol('table');
|
|
120
|
+
/**
|
|
121
|
+
* A map answering each string key with `ref(key)`, typed as the caller's map, whose keys say what it holds, and
|
|
122
|
+
* {@link TABLE} with what renders the table where it reads one. No other symbol, so nothing probing it sees more.
|
|
123
|
+
*/
|
|
124
|
+
function refMap(ref, table) {
|
|
125
|
+
return new Proxy({}, { get: (_, key) => (key === TABLE ? table?.() : typeof key === 'string' ? ref(key) : undefined) });
|
|
100
126
|
}
|
|
101
127
|
/**
|
|
102
128
|
* The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
|
|
@@ -162,33 +188,43 @@ function relationAggregate(spec) {
|
|
|
162
188
|
* {@link refs} are, so each names its own column wherever it renders, a write to another table included.
|
|
163
189
|
* Columns only: a relation's aggregate is a subquery, and a trigger fires on one row, not over a table.
|
|
164
190
|
*/
|
|
165
|
-
export function rowRefs(entity,
|
|
166
|
-
return
|
|
191
|
+
export function rowRefs(entity, row) {
|
|
192
|
+
return refMap((key) => columnRef(entity, key, { row }));
|
|
167
193
|
}
|
|
168
194
|
/**
|
|
169
|
-
* One field as SQL, against its own entity or, read off a definition, the entity rendering it
|
|
170
|
-
*
|
|
195
|
+
* One field as SQL, against its own entity or, read off a definition, the entity rendering it, read off the
|
|
196
|
+
* alias in scope unless a `qualifier` names another.
|
|
171
197
|
*/
|
|
172
198
|
export function columnRef(entity, key, qualifier) {
|
|
173
199
|
return new ColumnRef(key, (opts) => {
|
|
174
|
-
const owner = entity
|
|
175
|
-
|
|
176
|
-
|
|
200
|
+
const owner = refOwner(entity, key, opts);
|
|
201
|
+
const scope = opts.entity;
|
|
202
|
+
if (!qualifier && scope && scope !== owner && !(scope.prototype instanceof owner)) {
|
|
203
|
+
throw new UqlUsageError(`a ref of '${owner.name}' cannot render against '${scope.name}', the table in scope: ` +
|
|
204
|
+
`read it off its own alias, refs(${owner.name}, 'alias')`);
|
|
177
205
|
}
|
|
178
206
|
renderColumn(getMeta(owner), key, { ...opts, entity: owner }, qualifier);
|
|
179
|
-
});
|
|
207
|
+
}, entity);
|
|
208
|
+
}
|
|
209
|
+
/** The entity a ref of `key` reads its column of: its own, or, read off a definition, the entity in scope. */
|
|
210
|
+
export function refOwner(entity, key, scope) {
|
|
211
|
+
const owner = entity ?? scope.entity;
|
|
212
|
+
if (!owner) {
|
|
213
|
+
throw new UqlUsageError(`'${key}' was read off a definition's refs, so it renders only inside its entity's SQL`);
|
|
214
|
+
}
|
|
215
|
+
return owner;
|
|
180
216
|
}
|
|
181
217
|
/**
|
|
182
218
|
* A field's column, or the expression an inlined computed one stands for, as a `$where` on it reads it.
|
|
183
|
-
* Under a `qualifier` the column is read off that row rather than off the alias in scope
|
|
219
|
+
* Under a `qualifier` the column is read off that row or alias rather than off the alias in scope. A row is
|
|
184
220
|
* written verbatim: it is a record the engine declares, not an identifier to quote and case-fold.
|
|
185
221
|
*/
|
|
186
222
|
function renderColumn(meta, key, opts, qualifier) {
|
|
187
|
-
const scope = qualifier
|
|
223
|
+
const scope = qualifier ? { ...opts, ...qualifiedBy(qualifier, opts) } : opts;
|
|
188
224
|
const field = meta.fields[key];
|
|
189
225
|
if (field && isInlinedExpression(field)) {
|
|
190
226
|
// A relation aggregate is a subquery correlated to a table in scope, and a trigger's row is not one.
|
|
191
|
-
if (qualifier
|
|
227
|
+
if (qualifier?.row && aggregateOf(field)) {
|
|
192
228
|
throw new UqlUsageError(`'${entityName(meta)}.${key}' reads a relation, which a trigger's row cannot: it fires on one row, ` +
|
|
193
229
|
'with no table in scope to correlate a subquery to. Name the columns it is derived from instead.');
|
|
194
230
|
}
|
|
@@ -197,6 +233,10 @@ function renderColumn(meta, key, opts, qualifier) {
|
|
|
197
233
|
}
|
|
198
234
|
scope.ctx.append(scope.escapedPrefix + scope.dialect.escapeId(scope.dialect.columnOf(meta, key), true));
|
|
199
235
|
}
|
|
236
|
+
/** The prefix a `qualifier` reads columns off, as the render options spell one. */
|
|
237
|
+
function qualifiedBy({ row, alias }, { dialect }) {
|
|
238
|
+
return row ? { escapedPrefix: `${row}.` } : { prefix: alias, escapedPrefix: dialect.escapeId(alias, true, true) };
|
|
239
|
+
}
|
|
200
240
|
/**
|
|
201
241
|
* An inlined computed field's expression as every clause splices it: grouped, so a comparison inside cannot
|
|
202
242
|
* chain with one around it (`a <= b = ?`). A relation aggregate is a subquery, grouped already.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntityPredicate, type
|
|
1
|
+
import { type EntityPredicate, type QueryUpsert, type QuerySql, type TriggerWrite, type AbstractType, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
|
|
4
4
|
* Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
|
|
@@ -6,10 +6,13 @@ import { type EntityPredicate, type QueryConflictPaths, type QuerySql, type Trig
|
|
|
6
6
|
*/
|
|
7
7
|
export declare function insertInto<E extends object>(entity: AbstractType<E>, row: WriteRow<E>): QuerySql;
|
|
8
8
|
/**
|
|
9
|
-
* A row inserted by a trigger's body, or what
|
|
10
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 },
|
|
9
|
+
* A row inserted by a trigger's body, or what `q.$conflict` finds taking `update` instead where it matches
|
|
10
|
+
* `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true } }, { postId: newRow.id, count: 1 },
|
|
11
|
+
* { count: { $inc: 1 } })`.
|
|
11
12
|
*/
|
|
12
|
-
export declare function upsertInto<E extends object>(entity: AbstractType<E>,
|
|
13
|
+
export declare function upsertInto<E extends object>(entity: AbstractType<E>, q: QueryUpsert<E> & {
|
|
14
|
+
readonly $where?: EntityPredicate<E>;
|
|
15
|
+
}, row: WriteRow<E>, update?: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
|
|
13
16
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
14
17
|
export declare function updateTable<E extends object>(entity: AbstractType<E>, q: {
|
|
15
18
|
readonly $where: EntityPredicate<E>;
|
|
@@ -8,11 +8,12 @@ export function insertInto(entity, row) {
|
|
|
8
8
|
return written({ kind: 'insert', entity, row });
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
-
* A row inserted by a trigger's body, or what
|
|
12
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 },
|
|
11
|
+
* A row inserted by a trigger's body, or what `q.$conflict` finds taking `update` instead where it matches
|
|
12
|
+
* `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true } }, { postId: newRow.id, count: 1 },
|
|
13
|
+
* { count: { $inc: 1 } })`.
|
|
13
14
|
*/
|
|
14
|
-
export function upsertInto(entity,
|
|
15
|
-
return written({ kind: 'upsert', entity,
|
|
15
|
+
export function upsertInto(entity, q, row, update) {
|
|
16
|
+
return written({ kind: 'upsert', entity, q, row, update });
|
|
16
17
|
}
|
|
17
18
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
18
19
|
export function updateTable(entity, q, set) {
|
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.
|
|
6
|
+
"version": "0.108.1",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -3,9 +3,10 @@ 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, triggers or filters
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
Use when a project imports uql-orm, or when defining entities (@Entity, defineEntity), triggers or filters
|
|
7
|
+
(soft delete, multi-tenancy), querying ($where, $populate, findMany, aggregate), writing (insertMany, upsertOne,
|
|
8
|
+
updateMany, returning), transactions, raw SQL (sql, refs) or migrations (uql-migrate) with it. UQL is not Prisma,
|
|
9
|
+
Drizzle, TypeORM or MikroORM: their APIs do not carry over.
|
|
9
10
|
---
|
|
10
11
|
|
|
11
12
|
# UQL
|
|
@@ -43,8 +44,8 @@ The pool's first argument is the driver's own config; set an acquire timeout the
|
|
|
43
44
|
|
|
44
45
|
Two forms, mixable per entity, producing the same queries and types:
|
|
45
46
|
|
|
46
|
-
- **Decorators**: a named class type,
|
|
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.
|
|
47
|
+
- **Decorators**: a named class type, and column-level foreign keys (`f.references`), so entities may reference each other in any order. Slightly stricter: a property may be typed narrower than its column (a branded id), and `mappedBy` must name a relation or foreign key at compile time. Each field is written twice (builder and property), and it needs the TC39 decorator transform.
|
|
48
|
+
- **`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. A shared set of fields spreads into `fields`.
|
|
48
49
|
|
|
49
50
|
`uql-codemod` cannot convert one form into the other. Details: https://uql-orm.dev/entities/define-entity.md
|
|
50
51
|
|
|
@@ -88,16 +89,16 @@ export class Post {
|
|
|
88
89
|
|
|
89
90
|
- 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
91
|
- 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.
|
|
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.
|
|
92
|
-
- `Date` is an instant, stored in UTC to the millisecond
|
|
92
|
+
- `.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. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
|
|
93
|
+
- `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
|
|
93
94
|
- 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
|
|
95
|
+
- `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 with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
|
|
95
96
|
- 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
|
+
- Optimistic lock: `@Field(f.version())` with `[versionKey]?: 'version'` on the class. An update, and an upsert or save of a row that exists, must carry the version it read; a stale one throws `UqlOptimisticLockError`.
|
|
97
98
|
- 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
99
|
- 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
|
|
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 }
|
|
100
|
+
- 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 entity filters and run no JavaScript: an insert fills an `.onInsert()` value or SQL, but an `insertInto` names every required column a callback fills (`.onInsert(() => crypto.randomUUID())`) where no database default does. MongoDB has none: https://uql-orm.dev/entities/triggers.md
|
|
101
|
+
- 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 }`.
|
|
101
102
|
- **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.
|
|
102
103
|
|
|
103
104
|
### defineEntity
|
|
@@ -139,9 +140,9 @@ export const Book = defineEntity({
|
|
|
139
140
|
|
|
140
141
|
- 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
142
|
- `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
|
|
143
|
+
- 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 aggregate fields: aggregates over a to-many, or expressions mixing them with columns.
|
|
143
144
|
- 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
|
|
145
|
+
- A hook is a function of the row and the same second argument. 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
|
|
|
146
147
|
### Filters, soft delete and tenants
|
|
147
148
|
|
|
@@ -174,7 +175,7 @@ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
|
|
|
174
175
|
|
|
175
176
|
- 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
177
|
- `.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()`.
|
|
178
|
+
- 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()`.
|
|
178
179
|
- `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
|
|
179
180
|
|
|
180
181
|
## Queries
|
|
@@ -197,25 +198,26 @@ const users = await pool.findMany(User, {
|
|
|
197
198
|
- 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
199
|
- 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
200
|
- `$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'
|
|
201
|
+
- `$sort` takes `'asc'`/`1`, `'desc'`/`-1`, or `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`.
|
|
201
202
|
- `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
203
|
- `$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
|
|
|
204
205
|
### `$where`
|
|
205
206
|
|
|
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
|
|
207
|
+
- `$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`. Combine with `$and`, `$or`, `$not`, `$nor`. A field takes only the operators its type allows.
|
|
207
208
|
- 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
209
|
- 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
210
|
- 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
211
|
- Full-text: `$where: { $text: { $value: 'wireless keyboard' } }` searches the entity's fulltext index; `$sort: { $text: 'desc' }` ranks by relevance.
|
|
211
212
|
- 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.
|
|
213
|
+
- An operator compares a field with another column of the row wherever it takes a value: `const rate = refs(Rate); pool.findMany(Rate, { $where: { effectiveTo: { $gt: rate.effectiveFrom } } })`. A check's refs work the same. A JSON path compared with a ref reads as that column's type. A ref of another entity than the one queried is refused: in raw SQL, read it off its own alias, `refs(Other, 'o')`.
|
|
212
214
|
- An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
|
|
213
215
|
- 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
216
|
|
|
215
217
|
### Writes
|
|
216
218
|
|
|
217
219
|
- 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.
|
|
220
|
+
- `upsertOne(Entity, { $conflict: { email: true }, $where? }, row, update?)`: a conflicting row matching `$where` takes `update` (an update payload), else the payload but keeping its own key; one not matching stays as it is. `upsertInto` in a trigger takes the same query. On MySQL and MariaDB, a `$where` may read only one column the update sets.
|
|
219
221
|
- `updateMany` and `deleteMany` that name no rows (no `$where` holding a value, no `$limit`) throw. Pass `{ unfiltered: true }` to mean the whole table.
|
|
220
222
|
- 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
223
|
|
|
@@ -223,7 +225,8 @@ const users = await pool.findMany(User, {
|
|
|
223
225
|
|
|
224
226
|
- ``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
227
|
- 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.
|
|
226
|
-
-
|
|
228
|
+
- SQL reading another table names it with `tableOf`, its columns off refs read under an alias, so a rename reaches them: ``const o = refs(Order, 'o'); sql`(SELECT ${o.state} FROM ${tableOf(o)} WHERE ${o.checkoutId} = ${checkout.id} LIMIT 1)` ``. Two aliases read one table twice.
|
|
229
|
+
- `queryErrorKind(err)` names a failure: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
|
|
227
230
|
|
|
228
231
|
## Aggregates
|
|
229
232
|
|
|
@@ -258,7 +261,7 @@ await pool.transaction(async (querier) => {
|
|
|
258
261
|
```
|
|
259
262
|
|
|
260
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.
|
|
261
|
-
- `querier.onCommit(fn)` runs `fn` after the outermost commit, never on rollback
|
|
264
|
+
- `querier.onCommit(fn)` runs `fn` after the outermost commit, never on rollback.
|
|
262
265
|
- 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
266
|
- A `findManyStream` holds its querier until the loop ends, refusing other statements meanwhile: run them after the loop, or on another connection.
|
|
264
267
|
|
|
@@ -274,6 +277,11 @@ await pool.transaction(async (querier) => {
|
|
|
274
277
|
|
|
275
278
|
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
|
|
276
279
|
|
|
280
|
+
## Before you finish
|
|
281
|
+
|
|
282
|
+
- Mail, webhooks and queued jobs run from `onCommit`, never from an after-hook or mid-transaction.
|
|
283
|
+
- Several writes that must land together run in one `pool.transaction(...)`; on MongoDB, so does an upsert with an `update` or `$where`, and an `updateMany` or `deleteMany` that cascades or runs hooks.
|
|
284
|
+
|
|
277
285
|
## Where to read more
|
|
278
286
|
|
|
279
287
|
- Operators and per-dialect SQL: https://uql-orm.dev/querying/comparison-operators.md
|