uql-orm 0.93.1 → 0.95.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/README.md +3 -0
- package/dist/browser/uql-browser.min.js +1 -1
- package/dist/browser/uql-browser.min.js.map +4 -4
- package/dist/dialect/abstractDialect.d.ts +2 -0
- package/dist/dialect/abstractDialect.js +4 -0
- package/dist/dialect/abstractSqlDialect.d.ts +13 -8
- package/dist/dialect/abstractSqlDialect.js +29 -12
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mergeSqlDialect.js +1 -1
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +3 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +5 -2
- 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/cli-config.d.ts +9 -0
- package/dist/migrate/cli-config.js +24 -6
- package/dist/migrate/cli.js +9 -2
- package/dist/migrate/ddl/defaultSql.js +3 -1
- package/dist/migrate/drift/driftDetector.js +7 -2
- package/dist/mongo/mongoDialect.d.ts +1 -0
- package/dist/mongo/mongoDialect.js +0 -1
- package/dist/mongo/mongodbQuerier.d.ts +3 -3
- package/dist/mongo/mongodbQuerier.js +5 -13
- package/dist/mssql/mssqlDialect.d.ts +5 -4
- package/dist/mssql/mssqlDialect.js +5 -4
- 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 +33 -15
- package/dist/querier/abstractQuerier.js +116 -33
- package/dist/querier/abstractQuerierPool.d.ts +1 -1
- package/dist/querier/abstractQuerierPool.js +1 -1
- package/dist/querier/abstractSqlQuerier.d.ts +17 -12
- package/dist/querier/abstractSqlQuerier.js +61 -65
- 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/sqlite/abstractSqliteQuerier.d.ts +1 -1
- package/dist/sqlite/sqliteDialect.d.ts +1 -0
- package/dist/sqlite/sqliteDialect.js +1 -0
- package/dist/type/dialect.d.ts +3 -3
- package/dist/type/entity.d.ts +4 -4
- package/dist/type/querier.d.ts +1 -1
- package/dist/type/query.d.ts +1 -12
- package/dist/type/universalQuerier.d.ts +10 -6
- 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/dist/util/triggerWrite.d.ts +3 -3
- package/dist/util/triggerWrite.js +2 -2
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +8 -3
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { QueryRaw, SQL_VALUE_NAMES } from '../type/index.js';
|
|
2
|
+
import { isRecord } from '../util/object.util.js';
|
|
2
3
|
import { SQL_VALUES } from '../util/raw.js';
|
|
3
4
|
/**
|
|
4
5
|
* A column default that is SQL rather than a literal, whether an entity or a migration declares it or
|
|
@@ -36,7 +37,24 @@ export function schemaDefault(value, compile) {
|
|
|
36
37
|
}
|
|
37
38
|
return value instanceof QueryRaw ? SqlExpression.parenthesized(compile(value)) : value;
|
|
38
39
|
}
|
|
39
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* A default as text for an exact comparison: numbers as their digits, and objects (SQL included) and text
|
|
42
|
+
* holding a JSON document as JSON with its keys in order, since a `jsonb` column reprints what it stores.
|
|
43
|
+
*/
|
|
40
44
|
export function writtenDefault(value) {
|
|
41
|
-
|
|
45
|
+
const document = typeof value === 'string' ? jsonDocument(value) : value;
|
|
46
|
+
return typeof document === 'object' && document !== null ? JSON.stringify(document, keysInOrder) : String(value);
|
|
47
|
+
}
|
|
48
|
+
/** What `text` spells as JSON, or nothing where it is no JSON at all. */
|
|
49
|
+
function jsonDocument(text) {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(text);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** A `JSON.stringify` replacer writing each object's keys in order. */
|
|
58
|
+
function keysInOrder(_key, value) {
|
|
59
|
+
return isRecord(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1))) : value;
|
|
42
60
|
}
|
|
@@ -19,7 +19,7 @@ export declare abstract class AbstractSqliteQuerier extends AbstractSqlQuerier {
|
|
|
19
19
|
protected iterate(query: string, values: SqliteBindValue[]): Promise<Iterable<RawRow> | AsyncIterable<RawRow>>;
|
|
20
20
|
internalAll<T>(query: string, values?: unknown[]): Promise<T[]>;
|
|
21
21
|
internalRun(query: string, values?: unknown[]): Promise<import("../type/query.js").QueryUpdateResult>;
|
|
22
|
-
internalStream
|
|
22
|
+
internalStream(query: string, values?: unknown[]): AsyncGenerator<RawRow, void, unknown>;
|
|
23
23
|
/**
|
|
24
24
|
* SQLite drivers hold a single shared handle rather than a connection from a pool, so releasing
|
|
25
25
|
* a querier returns nothing at all. Drivers owning a closable per-querier connection override this.
|
|
@@ -19,6 +19,7 @@ export declare class SqliteDialect extends AbstractSqlDialect {
|
|
|
19
19
|
protected refusal(message: string): string;
|
|
20
20
|
/** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
|
|
21
21
|
readonly maxFunctionArgs: number;
|
|
22
|
+
readonly maxBindValues: number;
|
|
22
23
|
/**
|
|
23
24
|
* The [sqlite-vec](https://github.com/asg017/sqlite-vec) functions, which need that extension
|
|
24
25
|
* loaded on the connection (see `Sqlite3QuerierPool`'s `extensions` option). libSQL and Turso ship
|
|
@@ -71,6 +71,7 @@ export class SqliteDialect extends AbstractSqlDialect {
|
|
|
71
71
|
}
|
|
72
72
|
/** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
|
|
73
73
|
maxFunctionArgs = 127;
|
|
74
|
+
maxBindValues = 32766;
|
|
74
75
|
/**
|
|
75
76
|
* The [sqlite-vec](https://github.com/asg017/sqlite-vec) functions, which need that extension
|
|
76
77
|
* loaded on the connection (see `Sqlite3QuerierPool`'s `extensions` option). libSQL and Turso ship
|
package/dist/type/dialect.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityMeta, EntityPredicate, UpdatePayload } from './entity.js';
|
|
2
|
-
import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery
|
|
2
|
+
import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery } from './query.js';
|
|
3
3
|
import type { QueryAggMap, QueryAggregate, QueryAggregateOp, QueryGroupMap } from './queryAggregate.js';
|
|
4
4
|
import type { QueryRawRenderOptions } from './queryRaw.js';
|
|
5
5
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -313,8 +313,8 @@ export interface SqlQueryDialect {
|
|
|
313
313
|
insert<E>(ctx: QueryContext, entity: Type<E>, payload: E | E[], opts?: QueryRenderOptions): void;
|
|
314
314
|
/** An update of the records the query matches. */
|
|
315
315
|
update<E>(ctx: QueryContext, entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryRenderOptions): void;
|
|
316
|
-
/** An upsert of one record or many by their conflict paths,
|
|
317
|
-
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[],
|
|
316
|
+
/** An upsert of one record or many by their conflict paths, a conflicting row taking `update` where given. */
|
|
317
|
+
upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
|
|
318
318
|
/** A write in a trigger's body; `rows` are what a set-based engine's body reads, narrowed to the ones it fires for. */
|
|
319
319
|
triggerWrite(ctx: QueryContext, write: TriggerWrite, rows?: TriggerRows): void;
|
|
320
320
|
/** A delete of the records the query matches, a soft delete where the entity has one. */
|
package/dist/type/entity.d.ts
CHANGED
|
@@ -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/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'>;
|
package/dist/type/query.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey,
|
|
1
|
+
import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey, WrittenId } from './entity.js';
|
|
2
2
|
import type { QueryLock } from './queryLock.js';
|
|
3
3
|
import type { QueryRaw } from './queryRaw.js';
|
|
4
4
|
import type { QueryWhere } from './queryWhere.js';
|
|
@@ -447,17 +447,6 @@ Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E>
|
|
|
447
447
|
} : E;
|
|
448
448
|
/** The to-many relations a query populated, which come back as lists rather than as optional ones. */
|
|
449
449
|
type PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;
|
|
450
|
-
/**
|
|
451
|
-
* How an upsert treats a row its conflict paths find: by default it takes the payload, less those paths. `U` is
|
|
452
|
-
* what a trigger's `upsertInto` narrows the update to.
|
|
453
|
-
*/
|
|
454
|
-
export type UpsertOptions<E, U = UpdatePayload<E>> = {
|
|
455
|
-
/**
|
|
456
|
-
* What such a row takes instead, as an update does, `{ uses: { $inc: 1 } }` counting; `{}` leaves it as it is,
|
|
457
|
-
* inserting only where none is. The payload still inserts.
|
|
458
|
-
*/
|
|
459
|
-
readonly update?: U;
|
|
460
|
-
};
|
|
461
450
|
/** What upserting one row reports. `created` is only knowable for a single statement, so a batch has none. */
|
|
462
451
|
export type QueryUpsertOneResult<E> = {
|
|
463
452
|
readonly id?: WrittenId<E>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EntityId, EntityWrite, FieldKey, RelationKey, UpdateWrite, WrittenId } from './entity.js';
|
|
2
|
-
import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult,
|
|
2
|
+
import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
|
|
3
3
|
import type { QueryAggMap, QueryAggregate, QueryAggregateResult, QueryGroupMap } from './queryAggregate.js';
|
|
4
4
|
import type { Type } from './utility.js';
|
|
5
5
|
import type { QuerierCountedResult, QuerierRaw, QuerierResult, QuerierTransport } from './wire.js';
|
|
@@ -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}. */
|
|
@@ -92,10 +92,14 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
|
|
|
92
92
|
* than a guess where it cannot: a batch naming some keys, or a key that is not `AUTO_INCREMENT`.
|
|
93
93
|
*/
|
|
94
94
|
insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
|
|
95
|
-
/**
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Insert or update a record by its conflict paths; resolves to its id and whether it was created. A conflicting
|
|
97
|
+
* row takes the payload less those paths, or `update` as `updateMany` takes one: `{ uses: { $inc: 1 } }` counts,
|
|
98
|
+
* and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
|
|
99
|
+
*/
|
|
100
|
+
upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>): Promise<QueryUpsertOneResult<E>>;
|
|
101
|
+
/** Insert or update records by their conflict paths, as `upsertOne` does; resolves to their ids in payload order. */
|
|
102
|
+
upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>): Promise<QueryUpsertManyResult<E>>;
|
|
99
103
|
/**
|
|
100
104
|
* insert or update a record.
|
|
101
105
|
* @param entity the entity to persist on
|
|
@@ -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
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type
|
|
1
|
+
import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, 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
|
|
@@ -7,9 +7,9 @@ import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type Trig
|
|
|
7
7
|
export declare function insertInto<E extends object>(entity: Type<E>, row: WriteRow<E>): QueryRaw;
|
|
8
8
|
/**
|
|
9
9
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
10
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, {
|
|
10
|
+
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
11
11
|
*/
|
|
12
|
-
export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>,
|
|
12
|
+
export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, update?: UpdatePayload<E, QueryRaw, WritableKey<E>, never>): QueryRaw;
|
|
13
13
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
|
|
14
14
|
export declare function updateTable<E extends object>(entity: Type<E>, q: {
|
|
15
15
|
readonly $where: EntityPredicate<E>;
|
|
@@ -9,9 +9,9 @@ export function insertInto(entity, row) {
|
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
|
|
12
|
-
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, {
|
|
12
|
+
* does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { count: { $inc: 1 } })`.
|
|
13
13
|
*/
|
|
14
|
-
export function upsertInto(entity, conflictPaths, row,
|
|
14
|
+
export function upsertInto(entity, conflictPaths, row, update) {
|
|
15
15
|
return written({ kind: 'upsert', entity, conflictPaths, row, update });
|
|
16
16
|
}
|
|
17
17
|
/** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, 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, 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.95.0",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=24"
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -22,6 +22,8 @@ npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/
|
|
|
22
22
|
|
|
23
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`.
|
|
24
24
|
|
|
25
|
+
Node's type stripping runs no decorators: on Node, add `tsx` (`npm i -D tsx`), which `uql-migrate` imports `uql.config.ts` through. Next.js compiles TC39 decorators only through a `babel.config.json` with `@babel/plugin-proposal-decorators` at `version: '2023-11'`. A bundle that minifies class names (Next's server build, or any bundler's `minify`) needs `@Entity({ name: 'todo' })`: a table name is the class name otherwise.
|
|
26
|
+
|
|
25
27
|
```ts
|
|
26
28
|
// uql.config.ts
|
|
27
29
|
import type { Config } from 'uql-orm';
|
|
@@ -72,7 +74,7 @@ export class Post {
|
|
|
72
74
|
- 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.
|
|
73
75
|
- 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.
|
|
74
76
|
- 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.
|
|
75
|
-
- `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.
|
|
77
|
+
- `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.
|
|
76
78
|
- `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`.
|
|
77
79
|
- Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
78
80
|
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
|
|
@@ -108,7 +110,7 @@ const users = await pool.findMany(User, {
|
|
|
108
110
|
- `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
|
|
109
111
|
- 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
112
|
- 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.
|
|
111
|
-
- `upsertOne(Entity, { email: true }, row,
|
|
113
|
+
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update's payload with its operators (`{ uses: { $inc: 1 } }`), instead of `row`; a new one inserts `row`. An empty `{}` leaves a conflicting row as it is: insert if absent. Cascaded relations write on either branch, a found row's replaced, as `updateMany` does.
|
|
112
114
|
- `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.
|
|
113
115
|
- 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
116
|
- `$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.
|
|
@@ -128,15 +130,18 @@ await pool.transaction(async (querier) => {
|
|
|
128
130
|
|
|
129
131
|
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
132
|
|
|
133
|
+
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`.
|
|
134
|
+
|
|
131
135
|
## Migrations
|
|
132
136
|
|
|
133
|
-
`npx uql-migrate` reads `uql.config.ts
|
|
137
|
+
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
134
138
|
|
|
135
139
|
- `sync` applies what the entities imply (development only).
|
|
136
140
|
- `generate:entities` writes the diff as a migration file to review. It renames a column whose field was renamed and refuses a required column with no default on a table holding rows.
|
|
137
141
|
- `up` and `down` apply and revert migrations.
|
|
138
142
|
- `generate:from-db` writes entity classes from an existing database.
|
|
139
143
|
- `drift:check` fails when the database no longer matches.
|
|
144
|
+
- `sync --dry-run` prints only SQL on stdout, to append to a migration file another tool applies: on Cloudflare D1, wrangler's (https://uql-orm.dev/cloudflare-d1.md).
|
|
140
145
|
|
|
141
146
|
Triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
|
|
142
147
|
|