uql-orm 0.93.0 → 0.94.0
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 +1 -1
- package/dist/browser/uql-browser.min.js.map +3 -3
- package/dist/dialect/abstractDialect.d.ts +2 -0
- package/dist/dialect/abstractDialect.js +4 -0
- package/dist/dialect/abstractSqlDialect.d.ts +11 -6
- package/dist/dialect/abstractSqlDialect.js +37 -13
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -0
- package/dist/dialect/mysqlLikeSqlDialect.js +4 -1
- package/dist/dialect/pgLikeSqlDialect.d.ts +2 -0
- package/dist/dialect/pgLikeSqlDialect.js +4 -0
- package/dist/dialect/queryContext.d.ts +2 -0
- package/dist/dialect/queryContext.js +6 -0
- package/dist/maria/mariadbQuerier.d.ts +2 -1
- package/dist/maria/mariadbQuerier.js +2 -8
- package/dist/migrate/ddl/index.d.ts +1 -1
- package/dist/migrate/ddl/index.js +3 -3
- package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
- package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
- package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
- package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
- package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
- package/dist/migrate/ddl/pgTableDdl.js +12 -6
- package/dist/migrate/ddl/tableDdl.d.ts +9 -6
- package/dist/migrate/ddl/tableDdl.js +15 -6
- package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
- package/dist/migrate/drift/driftDetector.js +7 -2
- package/dist/migrate/schemaChange.d.ts +2 -5
- package/dist/migrate/schemaGenerator.js +1 -1
- package/dist/mongo/mongoDialect.d.ts +1 -2
- package/dist/mongo/mongoDialect.js +18 -15
- package/dist/mongo/mongodbQuerier.js +3 -10
- package/dist/mssql/mssqlDialect.d.ts +3 -2
- package/dist/mssql/mssqlDialect.js +3 -2
- package/dist/mssql/mssqlQuerier.d.ts +2 -2
- package/dist/mssql/mssqlQuerier.js +1 -3
- package/dist/mysql/mysql2Querier.d.ts +1 -1
- package/dist/mysql/mysql2Querier.js +1 -9
- package/dist/pglite/index.d.ts +1 -0
- package/dist/pglite/index.js +1 -0
- package/dist/pglite/pgliteDialect.d.ts +6 -0
- package/dist/pglite/pgliteDialect.js +6 -0
- package/dist/pglite/pgliteQuerierPool.d.ts +2 -2
- package/dist/pglite/pgliteQuerierPool.js +2 -2
- package/dist/postgres/pgQuerier.d.ts +2 -4
- package/dist/postgres/pgQuerier.js +1 -9
- package/dist/querier/abstractQuerier.d.ts +21 -3
- package/dist/querier/abstractQuerier.js +86 -17
- package/dist/querier/abstractQuerierPool.d.ts +1 -1
- package/dist/querier/abstractQuerierPool.js +23 -23
- package/dist/querier/abstractSqlQuerier.d.ts +15 -10
- package/dist/querier/abstractSqlQuerier.js +54 -57
- package/dist/querier/cursorStream.d.ts +1 -1
- package/dist/schema/sqlExpression.d.ts +4 -1
- package/dist/schema/sqlExpression.js +20 -2
- package/dist/schema/types.d.ts +2 -5
- package/dist/sqlite/abstractSqliteQuerier.d.ts +1 -1
- package/dist/sqlite/sqliteDialect.d.ts +1 -0
- package/dist/sqlite/sqliteDialect.js +1 -0
- package/dist/type/entity.d.ts +9 -9
- package/dist/type/migration.d.ts +7 -8
- package/dist/type/querier.d.ts +1 -1
- package/dist/type/universalQuerier.d.ts +1 -1
- package/dist/util/dialect.util.d.ts +1 -1
- package/dist/util/object.util.d.ts +2 -0
- package/dist/util/object.util.js +8 -0
- package/dist/util/query.util.d.ts +3 -1
- package/dist/util/query.util.js +7 -0
- package/dist/util/sql.util.d.ts +2 -4
- package/dist/util/sql.util.js +10 -19
- package/package.json +10 -10
- package/skills/uql-orm/SKILL.md +22 -51
package/dist/type/entity.d.ts
CHANGED
|
@@ -140,14 +140,14 @@ type JsonUpdateOpFor<V, T = UnwrapJson<NonNullable<V>>> = [T] extends [never] ?
|
|
|
140
140
|
/**
|
|
141
141
|
* A scalar field's update operator, as {@link JsonUpdateOp} is a JSON field's, computed in the statement:
|
|
142
142
|
* `$inc` adds, `$mul` multiplies, a NULL counting as 0 on every engine. One per field, since their order
|
|
143
|
-
* would change the result. A `bigint` steps by a `bigint`, exactly.
|
|
144
|
-
* @example `{ stock: { $inc: -1 } }`
|
|
143
|
+
* would change the result. A `bigint` steps by a `bigint`, exactly, and the step may be SQL of the field's type.
|
|
144
|
+
* @example `{ stock: { $inc: -1 } }`, `{ total: { $inc: newRow.amount } }`
|
|
145
145
|
*/
|
|
146
|
-
export type FieldUpdateOp<T
|
|
146
|
+
export type FieldUpdateOp<T = number | bigint | QueryRaw> = ExactlyOne<Record<'$inc' | '$mul', T>>;
|
|
147
147
|
/** The {@link FieldUpdateOp} a field takes: `never` on one it has no operator for, which is any but a number. */
|
|
148
|
-
type FieldUpdateOpFor<V> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number
|
|
148
|
+
type FieldUpdateOpFor<V, Raw> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number | RawFor<Raw, number>> : [NonNullable<V>] extends [bigint] ? FieldUpdateOp<bigint | RawFor<Raw, bigint>> : never;
|
|
149
149
|
/** What an update takes beyond the value: `null` to clear an optional member, `raw` SQL, and update operators. */
|
|
150
|
-
type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V>;
|
|
150
|
+
type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V, Raw>;
|
|
151
151
|
/**
|
|
152
152
|
* What a whole-record write persists: the fields and relations with their declared optionality, a
|
|
153
153
|
* related row as a caller writes one, and no methods. Two mapped types, since asking each key costs a
|
|
@@ -326,12 +326,12 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
|
|
|
326
326
|
};
|
|
327
327
|
export type OnFieldCallback<V = TsTypeOf<FieldType>> = V | QueryRaw | (() => V | QueryRaw);
|
|
328
328
|
/**
|
|
329
|
-
* What a column may default to: its value, or on a JSON column the
|
|
330
|
-
* erased `FieldOptions` takes
|
|
329
|
+
* What a column may default to: its value, or on a JSON column the document it stores, `[]`, or its SQL text,
|
|
330
|
+
* `'{}'`. The erased `FieldOptions` takes them all, so every field's options stay assignable to it.
|
|
331
331
|
*/
|
|
332
332
|
type DdlDefault<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonDdlDefault : [TsTypeOf<FieldType>] extends [T] ? JsonDdlDefault | T : T;
|
|
333
|
-
/** What a JSON column, and the field-less `FieldOptions`, may default to. */
|
|
334
|
-
type JsonDdlDefault = Scalar |
|
|
333
|
+
/** What a JSON column, and the field-less `FieldOptions`, may default to: a document, a list included. */
|
|
334
|
+
type JsonDdlDefault = Scalar | object;
|
|
335
335
|
/**
|
|
336
336
|
* The TypeScript type a declared `type` implies, the inverse of {@link TypeFor}: a decorator checks the
|
|
337
337
|
* property against it, `defineEntity` the other way round. `entityOptions.test-d.ts` keeps them agreeing.
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -187,10 +187,7 @@ export type ColumnChange = Change<ColumnSchema> & {
|
|
|
187
187
|
readonly isBreaking?: boolean;
|
|
188
188
|
};
|
|
189
189
|
/** A name changed, `from` the database's `to` the entity's. */
|
|
190
|
-
export type Rename =
|
|
191
|
-
readonly from: string;
|
|
192
|
-
readonly to: string;
|
|
193
|
-
};
|
|
190
|
+
export type Rename = Alteration<string>;
|
|
194
191
|
/** Renamed columns by qualified table name. */
|
|
195
192
|
export type ColumnRenames = ReadonlyMap<string, readonly Rename[]>;
|
|
196
193
|
/**
|
|
@@ -202,6 +199,11 @@ export interface Change<T> {
|
|
|
202
199
|
readonly from?: T;
|
|
203
200
|
readonly to?: T;
|
|
204
201
|
}
|
|
202
|
+
/** A {@link Change} with both sides: the object altered in place. */
|
|
203
|
+
export type Alteration<T> = {
|
|
204
|
+
readonly from: T;
|
|
205
|
+
readonly to: T;
|
|
206
|
+
};
|
|
205
207
|
/** A primary key, whichever side it is read from: the entities, the database, or a diff between them. */
|
|
206
208
|
export interface PrimaryKeySchema {
|
|
207
209
|
/** Its columns **in order**, which is what a composite is: `(a, b)` is not `(b, a)`. */
|
|
@@ -233,10 +235,7 @@ export interface SchemaDiff {
|
|
|
233
235
|
* The table copied into a new one, which is how an engine that {@link DialectFeatures.rebuildsTables}
|
|
234
236
|
* applies the changes above. Its column renames are carried by the copy.
|
|
235
237
|
*/
|
|
236
|
-
readonly rebuild?:
|
|
237
|
-
readonly from: RebuiltTable;
|
|
238
|
-
readonly to: RebuiltTable;
|
|
239
|
-
};
|
|
238
|
+
readonly rebuild?: Alteration<RebuiltTable>;
|
|
240
239
|
}
|
|
241
240
|
/**
|
|
242
241
|
* What every sync entry point takes: `safe` keeps it additive, `drop` lets it remove a column, and
|
package/dist/type/querier.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ type DualRead<Q extends keyof ProjectedQuery<object, never, never, never, never,
|
|
|
34
34
|
export interface Querier extends UniversalQuerier {
|
|
35
35
|
findOne: DualRead<'one', 'one'>;
|
|
36
36
|
findMany: DualRead<'many', 'many'>;
|
|
37
|
-
/** Stream records with the relations and counts `findMany` reads.
|
|
37
|
+
/** Stream records with the relations and counts `findMany` reads, `afterLoad` on each. The querier runs nothing else until the loop ends. */
|
|
38
38
|
findManyStream: DualRead<'many', 'stream'>;
|
|
39
39
|
/** Find many records and count every match. */
|
|
40
40
|
findManyAndCount: DualRead<'many', 'counted'>;
|
|
@@ -81,7 +81,7 @@ export interface SharedQuerier<W extends QuerierTransport, O, DO = O> {
|
|
|
81
81
|
export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions> {
|
|
82
82
|
/**
|
|
83
83
|
* Stream the records matching the query one at a time, each with the relations and counts `findMany`
|
|
84
|
-
* reads, for bulk reads.
|
|
84
|
+
* reads, for bulk reads. `afterLoad` runs on each row as it arrives.
|
|
85
85
|
*/
|
|
86
86
|
findManyStream: ProjectedRead<'many', 'stream', 'server', QueryOptions>;
|
|
87
87
|
/** Insert a record and resolve to its id. See {@link UniversalQuerier.insertMany}. */
|
|
@@ -82,7 +82,7 @@ export declare function isFieldUpdateOp(value: unknown): value is FieldUpdateOp;
|
|
|
82
82
|
* The one operator a scalar field's update carries, and its operand. Naming both throws rather than
|
|
83
83
|
* reading one: their order would change the result, and an untyped payload is how both arrive.
|
|
84
84
|
*/
|
|
85
|
-
export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint];
|
|
85
|
+
export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint | QueryRaw];
|
|
86
86
|
/** Returns a `QueryOptions.filters` value with the built-in soft-delete filter disabled (used by hard delete). */
|
|
87
87
|
export declare function withoutSoftDeleteFilter(filters: QueryOptions['filters']): QueryOptions['filters'];
|
|
88
88
|
/**
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { EntityMeta } from '../type/index.js';
|
|
2
2
|
export declare function clone<T>(value: T): T;
|
|
3
|
+
/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */
|
|
4
|
+
export declare function chunk<T>(items: readonly T[], size: number): T[][];
|
|
3
5
|
/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */
|
|
4
6
|
export declare function hasKeys<T>(obj: T): obj is NonNullable<T>;
|
|
5
7
|
/**
|
package/dist/util/object.util.js
CHANGED
|
@@ -7,6 +7,14 @@ export function clone(value) {
|
|
|
7
7
|
}
|
|
8
8
|
return { ...value };
|
|
9
9
|
}
|
|
10
|
+
/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */
|
|
11
|
+
export function chunk(items, size) {
|
|
12
|
+
const chunks = [];
|
|
13
|
+
for (let start = 0; start < items.length; start += size) {
|
|
14
|
+
chunks.push(items.slice(start, start + size));
|
|
15
|
+
}
|
|
16
|
+
return chunks;
|
|
17
|
+
}
|
|
10
18
|
/** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */
|
|
11
19
|
export function hasKeys(obj) {
|
|
12
20
|
if (typeof obj !== 'object' || obj === null)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityId, EntityMeta, FieldKey, Query, QueryConflictPaths, QuerySearch, QuerySortDirection, QuerySortMap, QueryWhere, QueryWhereArray } from '../type/index.js';
|
|
1
|
+
import type { EntityData, EntityId, EntityMeta, FieldKey, Query, QueryConflictPaths, QuerySearch, QuerySortDirection, QuerySortMap, QueryWhere, QueryWhereArray } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Maps each of `keys` to `true`, the shape of a `$select` or conflict paths. This and the builders below hold
|
|
4
4
|
* the casts generic code needs to build a statement: the compiler types these maps per entity, so it does not
|
|
@@ -9,6 +9,8 @@ export declare function keySet<E>(keys: readonly FieldKey<E>[]): QueryConflictPa
|
|
|
9
9
|
export declare function whereWith<E>(key: FieldKey<E>, value: unknown, where?: QueryWhere<E>): QueryWhere<E>;
|
|
10
10
|
export declare function whereEach<E>(keys: readonly FieldKey<E>[], valueOf: (key: FieldKey<E>) => unknown): QueryWhere<E>;
|
|
11
11
|
export declare function whereAnyOf<E>(clauses: QueryWhereArray<E>): QueryWhere<E>;
|
|
12
|
+
/** The rows matching one of `rows` on `keys`: one list where a single key names them, an alternative each where several do. */
|
|
13
|
+
export declare function whereKeysIn<E>(keys: readonly FieldKey<E>[], rows: readonly EntityData<E>[]): QueryWhere<E>;
|
|
12
14
|
/** A `$sort` from `[key, direction]` pairs, sorting by the keys in the order given. */
|
|
13
15
|
export declare function sortOf<E>(entries: readonly (readonly [FieldKey<E>, QuerySortDirection])[]): QuerySortMap<E>;
|
|
14
16
|
/**
|
package/dist/util/query.util.js
CHANGED
|
@@ -19,6 +19,13 @@ export function whereEach(keys, valueOf) {
|
|
|
19
19
|
export function whereAnyOf(clauses) {
|
|
20
20
|
return { $or: clauses };
|
|
21
21
|
}
|
|
22
|
+
/** The rows matching one of `rows` on `keys`: one list where a single key names them, an alternative each where several do. */
|
|
23
|
+
export function whereKeysIn(keys, rows) {
|
|
24
|
+
const [soleKey] = keys;
|
|
25
|
+
return keys.length === 1
|
|
26
|
+
? whereWith(soleKey, rows.map((row) => row[soleKey]))
|
|
27
|
+
: whereAnyOf(rows.map((row) => whereEach(keys, (key) => row[key])));
|
|
28
|
+
}
|
|
22
29
|
/** A `$sort` from `[key, direction]` pairs, sorting by the keys in the order given. */
|
|
23
30
|
export function sortOf(entries) {
|
|
24
31
|
return Object.fromEntries(entries);
|
package/dist/util/sql.util.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import type { InsertIdSource, QueryUpdateResult, RawRow } from '../type/index.js';
|
|
2
2
|
import type { PrimaryKey } from '../type/utility.js';
|
|
3
|
+
/** Every row nested as {@link unflatObject} nests one, by the columns the first row names. */
|
|
3
4
|
export declare function unflatObjects<T extends object>(objects: RawRow[]): T[];
|
|
4
|
-
/**
|
|
5
|
-
* Unflattens a single raw row using pre-computed attribute paths.
|
|
6
|
-
* Use this for streaming to avoid per-row array allocations.
|
|
7
|
-
*/
|
|
5
|
+
/** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
|
|
8
6
|
export declare function unflatObject<T extends object>(row: RawRow, attrsPaths: Record<string, string[]>): T;
|
|
9
7
|
export declare function obtainAttrsPaths<T extends object>(row: T): {
|
|
10
8
|
[k: string]: string[];
|
package/dist/util/sql.util.js
CHANGED
|
@@ -1,37 +1,28 @@
|
|
|
1
1
|
import { OWNED_PREFIX, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
|
|
2
|
-
import { hasKeys } from './object.util.js';
|
|
2
|
+
import { hasKeys, isRecord } from './object.util.js';
|
|
3
3
|
import { fnv1a } from './string.util.js';
|
|
4
4
|
/** Pre-computed regex for each SQL identifier escape character to avoid per-call allocation. */
|
|
5
5
|
const escapeIdRegexCache = { '`': /`/g, '"': /"/g };
|
|
6
|
+
/** Every row nested as {@link unflatObject} nests one, by the columns the first row names. */
|
|
6
7
|
export function unflatObjects(objects) {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
const attrsPaths = obtainAttrsPaths(objects[0]);
|
|
11
|
-
if (!hasKeys(attrsPaths)) {
|
|
12
|
-
return objects;
|
|
13
|
-
}
|
|
8
|
+
const [first] = objects;
|
|
9
|
+
const attrsPaths = first ? obtainAttrsPaths(first) : {};
|
|
14
10
|
return objects.map((row) => unflatObject(row, attrsPaths));
|
|
15
11
|
}
|
|
16
|
-
/**
|
|
17
|
-
* Unflattens a single raw row using pre-computed attribute paths.
|
|
18
|
-
* Use this for streaming to avoid per-row array allocations.
|
|
19
|
-
*/
|
|
12
|
+
/** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
|
|
20
13
|
export function unflatObject(row, attrsPaths) {
|
|
14
|
+
if (!hasKeys(attrsPaths)) {
|
|
15
|
+
return row;
|
|
16
|
+
}
|
|
21
17
|
const dto = {};
|
|
22
18
|
for (const col in row) {
|
|
23
|
-
if (row[col] === null) {
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
19
|
const attrPath = attrsPaths[col];
|
|
27
20
|
if (attrPath) {
|
|
28
21
|
let target = dto;
|
|
29
22
|
for (let i = 0; i < attrPath.length - 1; i++) {
|
|
30
23
|
const seg = attrPath[i];
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
target = target[seg];
|
|
24
|
+
const next = target[seg];
|
|
25
|
+
target = isRecord(next) ? next : (target[seg] = {});
|
|
35
26
|
}
|
|
36
27
|
target[attrPath[attrPath.length - 1]] = row[col];
|
|
37
28
|
}
|
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, Deno, 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.94.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
|
@@ -135,25 +135,25 @@
|
|
|
135
135
|
"@electric-sql/pglite": "0.5.8",
|
|
136
136
|
"@electric-sql/pglite-pgvector": "0.0.9",
|
|
137
137
|
"@libsql/client": "^0.18.0",
|
|
138
|
-
"@neondatabase/serverless": "^1.
|
|
139
|
-
"@nestjs/common": "^12.1.
|
|
140
|
-
"@nestjs/core": "^12.1.
|
|
141
|
-
"@nestjs/testing": "^12.1.
|
|
142
|
-
"@tursodatabase/database": "^0.
|
|
138
|
+
"@neondatabase/serverless": "^1.2.0",
|
|
139
|
+
"@nestjs/common": "^12.1.2",
|
|
140
|
+
"@nestjs/core": "^12.1.2",
|
|
141
|
+
"@nestjs/testing": "^12.1.2",
|
|
142
|
+
"@tursodatabase/database": "^0.8.1",
|
|
143
143
|
"@tursodatabase/serverless": "^1.4.0",
|
|
144
144
|
"@types/better-sqlite3": "^9.6.0",
|
|
145
145
|
"@types/express": "^5.0.6",
|
|
146
146
|
"@types/mssql": "^12.3.0",
|
|
147
147
|
"@types/pg": "^8.23.1",
|
|
148
|
-
"@types/ws": "^8.18.
|
|
148
|
+
"@types/ws": "^8.18.2",
|
|
149
149
|
"better-sqlite3": "^13.0.3",
|
|
150
150
|
"express": "^5.2.1",
|
|
151
151
|
"mariadb": "^3.5.4",
|
|
152
152
|
"mongodb": "^7.7.0",
|
|
153
153
|
"mssql": "^12",
|
|
154
|
-
"mysql2": "^3.24.
|
|
155
|
-
"pg": "^8.23.
|
|
156
|
-
"pg-query-stream": "^4.17.
|
|
154
|
+
"mysql2": "^3.24.5",
|
|
155
|
+
"pg": "^8.23.1",
|
|
156
|
+
"pg-query-stream": "^4.17.1",
|
|
157
157
|
"rxjs": "^7.8.2",
|
|
158
158
|
"sqlite-vec": "^0.1.9",
|
|
159
159
|
"ws": "^8.22.0"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -10,11 +10,9 @@ description: >
|
|
|
10
10
|
|
|
11
11
|
# UQL
|
|
12
12
|
|
|
13
|
-
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs
|
|
14
|
-
on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
13
|
+
Entities are classes; a query is a JSON object checked key by key against the entity; the same query runs on every database UQL supports. There is no schema file, no generated client, and no query builder.
|
|
15
14
|
|
|
16
|
-
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task
|
|
17
|
-
before guessing an option: every page listed there is a `.md` URL.
|
|
15
|
+
The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Read the page for the task before guessing an option: every page listed there is a `.md` URL.
|
|
18
16
|
|
|
19
17
|
## Setup
|
|
20
18
|
|
|
@@ -22,9 +20,7 @@ before guessing an option: every page listed there is a `.md` URL.
|
|
|
22
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
23
21
|
```
|
|
24
22
|
|
|
25
|
-
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard:
|
|
26
|
-
never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`.
|
|
27
|
-
In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
23
|
+
ESM only. Node 24+, Bun, Deno or an edge runtime, TypeScript 5.2+. Decorators are the TC39 standard: never enable `experimentalDecorators` or `emitDecoratorMetadata`, never import `reflect-metadata`. In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is a dated one (`es2022`+), not `esnext`.
|
|
28
24
|
|
|
29
25
|
```ts
|
|
30
26
|
// uql.config.ts
|
|
@@ -37,9 +33,7 @@ export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_U
|
|
|
37
33
|
export default { pool, entities: [User, Post] } satisfies Config;
|
|
38
34
|
```
|
|
39
35
|
|
|
40
|
-
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`,
|
|
41
|
-
`uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`,
|
|
42
|
-
`uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
36
|
+
Each driver has its own entry point: `uql-orm/postgres`, `uql-orm/mysql`, `uql-orm/maria`, `uql-orm/sqlite`, `uql-orm/mongo`, `uql-orm/libsql`, `uql-orm/turso`, `uql-orm/neon`, `uql-orm/d1`, `uql-orm/pglite`, `uql-orm/bunSql`, `uql-orm/mssql`, `uql-orm/cockroachdb`. Build the pool once per process and import it.
|
|
43
37
|
|
|
44
38
|
## Entities
|
|
45
39
|
|
|
@@ -78,15 +72,13 @@ export class Post {
|
|
|
78
72
|
- A column is nullable unless it says `nullable: false`, and its property must admit `null` to match: `title?: string | null`. A property typed without `| null` on a nullable column is a compile error.
|
|
79
73
|
- Declare a `nullable: false` column `!` (`email!: string`): reads have it and inserts must name it, except a single-column key and a `version`, which uql fills. Declare `?` whatever an insert may leave out: a nullable, `onInsert`, `defaultValue`, `eager: false` or `computed` field, and relations.
|
|
80
74
|
- An engine's own column type is a `raw` constant, ``columnType: raw`tsvector` ``, rendered verbatim and carrying its own `length`/`precision`: never a bare string.
|
|
81
|
-
- `defaultValue` is a value of the field's type, or SQL the database evaluates per row: one of `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``raw`...` ``. A string is always text, `'CURRENT_TIMESTAMP'` included. The migration builder takes the same.
|
|
75
|
+
- `defaultValue` is a value of the field's type (a JSON column's document, `[]` or `{}`), or SQL the database evaluates per row: one of `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``raw`...` ``. A string is always text, `'CURRENT_TIMESTAMP'` included. The migration builder takes the same.
|
|
82
76
|
- `currentTimestamp` is the database clock, UTC to the millisecond on every engine, where a raw `CURRENT_TIMESTAMP` is not on SQLite, MySQL or SQL Server. Use it for a default, a stamp, `onUpdate` or `$where`.
|
|
83
77
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
84
78
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|
|
85
79
|
- `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })` states a partial index's filter as the predicate the query passes, never as `raw`: a planner matches the two by shape, so `raw` that means the same thing leaves the index unused.
|
|
86
|
-
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock:
|
|
87
|
-
|
|
88
|
-
- `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`.
|
|
89
|
-
`stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
80
|
+
- `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock: an update must carry the version it read (a compile error otherwise), and one against a row someone else moved on throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409). Its updates name one row by its id; save and upsert are refused.
|
|
81
|
+
- `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`. `stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
|
|
90
82
|
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns the body, written with `insertInto`, `upsertInto` (as `upsertOne` takes it), `updateTable`, `deleteFrom` and `refuse(message)` (fails the write), which are typed by the entity written and render on every engine; `deferred: true` fires an after trigger at commit, on Postgres only; anything else is `raw` SQL over the rows, per engine where they differ. A trigger's writes skip uql's fills and entity filters, soft delete included. MongoDB has none. Details, SQL Server's per-statement shape included: https://uql-orm.dev/entities/triggers.md
|
|
91
83
|
- `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
|
|
92
84
|
|
|
@@ -106,48 +98,26 @@ const users = await pool.findMany(User, {
|
|
|
106
98
|
});
|
|
107
99
|
```
|
|
108
100
|
|
|
109
|
-
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`;
|
|
110
|
-
|
|
111
|
-
-
|
|
112
|
-
|
|
113
|
-
`NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
114
|
-
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000
|
|
115
|
-
costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass
|
|
116
|
-
`endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique
|
|
117
|
-
`nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages
|
|
118
|
-
correctly but cannot use an index.
|
|
119
|
-
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`,
|
|
120
|
-
`$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`,
|
|
121
|
-
`$isNotNull`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
101
|
+
- The keys are `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`; `$count: { posts: true }` tallies a to-many under `_count` without loading it.
|
|
102
|
+
- `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, and `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'` or `'descNullsLast'` to say where nulls land, which reads the same on every engine (emulated where there is no `NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
|
|
103
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass `endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique `nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages correctly but cannot use an index.
|
|
104
|
+
- `$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`. `$and`, `$or`, `$not` and `$nor` combine clauses.
|
|
122
105
|
- NULL compares the way the engine compares it: on SQL, `$ne`, `$nin`, `$not` and `$nor` leave out a NULL row, where MongoDB keeps it. Name NULL where you want it, `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`; ask for NULL with `{ col: null }` and its absence with `{ col: { $ne: null } }`.
|
|
123
|
-
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's
|
|
124
|
-
|
|
125
|
-
relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
126
|
-
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error.
|
|
127
|
-
Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
106
|
+
- `$text: { $value }` in `$where` searches text on every engine with full-text search, through the entity's `@Index(..., { type: 'fulltext', config })`, whose columns may carry a `weight`. `$sort: { $text: 'desc' }` ranks by relevance, and `{ $text: { $project: 'score' } }` also returns it, typed with `WithProjection<E, 'score'>`.
|
|
107
|
+
- A result is narrowed to what the query selected and populated: reading an unselected field is a compile error. Name that shape with `QueryFindResult<User, 'id' | 'email'>` rather than widening the query.
|
|
128
108
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
129
|
-
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`,
|
|
130
|
-
|
|
131
|
-
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`,
|
|
132
|
-
`aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`,
|
|
133
|
-
`upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
|
|
109
|
+
- A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`, whose handler serves only the entities its required `include` names.
|
|
110
|
+
- 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.
|
|
134
111
|
- `upsertOne(Entity, { email: true }, row, { update })`: a conflicting row takes `update`, an update's payload with its operators, instead of `row`; a new one inserts `row`. `{ update: {} }` leaves a conflicting row as it is: insert if absent.
|
|
135
112
|
- `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an `undefined` or an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
|
|
136
|
-
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row
|
|
140
|
-
someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and
|
|
141
|
-
refuse it.
|
|
142
|
-
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`,
|
|
143
|
-
`notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind
|
|
144
|
-
rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
113
|
+
- An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0, so a guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. On SQL the step may be a ref or `raw` of the field's type (`{ total: { $inc: newRow.amount } }` in a trigger). JSON fields take `$set`, `$unset`, `$push`, `$pull`.
|
|
114
|
+
- `$lock: true` locks the rows a read returns (`{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds) and needs an open transaction; SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
115
|
+
- `queryErrorKind(err)` names any failure the same on every engine - `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security` - so catch by kind rather than by a driver's code or an `instanceof`. Every error UQL raises itself is a `UqlError`.
|
|
145
116
|
- `raw()` embeds SQL anywhere a value or field goes; `pool.all(sql, values)` runs a raw `SELECT`. A field read off `refs(Entity)` carries its type: on its own as a value it fits only a field of that type.
|
|
146
117
|
|
|
147
118
|
## Connections and transactions
|
|
148
119
|
|
|
149
|
-
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it.
|
|
150
|
-
To run several operations on one connection, or atomically, hold a querier:
|
|
120
|
+
Every method is on both the pool and a querier. A pool call acquires a connection for that call and releases it. To run several operations on one connection, or atomically, hold a querier:
|
|
151
121
|
|
|
152
122
|
```ts
|
|
153
123
|
await pool.transaction(async (querier) => {
|
|
@@ -156,8 +126,9 @@ await pool.transaction(async (querier) => {
|
|
|
156
126
|
});
|
|
157
127
|
```
|
|
158
128
|
|
|
159
|
-
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the
|
|
160
|
-
|
|
129
|
+
Inside the callback, call `querier`, never `pool`: a `pool` call runs on another connection, outside the transaction. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
130
|
+
|
|
131
|
+
A `findManyStream` holds its querier until the loop ends, which refuses any other statement meanwhile: inside the loop, run them on another connection, or after the loop on SQLite and PGlite, whose pool has one. A statement binding more values than the engine takes (100 on D1, 2098 on SQL Server) is refused too: split a long `$in`.
|
|
161
132
|
|
|
162
133
|
## Migrations
|
|
163
134
|
|