uql-orm 0.94.0 → 0.95.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/README.md +3 -0
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +4 -4
- package/dist/d1/d1Querier.d.ts +2 -0
- package/dist/d1/d1Querier.js +4 -0
- package/dist/dialect/abstractSqlDialect.d.ts +6 -6
- package/dist/dialect/abstractSqlDialect.js +8 -8
- package/dist/dialect/mergeSqlDialect.d.ts +2 -2
- package/dist/dialect/mergeSqlDialect.js +1 -1
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -2
- package/dist/dialect/mysqlLikeSqlDialect.js +4 -7
- package/dist/dialect/pgLikeSqlDialect.d.ts +2 -2
- package/dist/dialect/pgLikeSqlDialect.js +4 -4
- package/dist/dialect/queryContext.d.ts +0 -2
- package/dist/dialect/queryContext.js +0 -6
- package/dist/maria/mariadbQuerier.d.ts +4 -0
- package/dist/maria/mariadbQuerier.js +14 -2
- 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/mongo/mongodbQuerier.d.ts +3 -3
- package/dist/mongo/mongodbQuerier.js +2 -3
- package/dist/mssql/mssqlDialect.d.ts +3 -3
- package/dist/mssql/mssqlDialect.js +3 -3
- package/dist/pglite/pgliteQuerier.d.ts +2 -2
- package/dist/querier/abstractQuerier.d.ts +22 -17
- package/dist/querier/abstractQuerier.js +72 -46
- package/dist/querier/abstractSqlQuerier.d.ts +3 -3
- package/dist/querier/abstractSqlQuerier.js +39 -33
- package/dist/schema/sqlExpression.d.ts +2 -2
- package/dist/schema/sqlExpression.js +2 -2
- package/dist/type/dialect.d.ts +3 -3
- package/dist/type/entity.d.ts +2 -2
- package/dist/type/query.d.ts +1 -12
- package/dist/type/universalQuerier.d.ts +9 -5
- package/dist/util/object.util.js +3 -0
- package/dist/util/sql.util.d.ts +0 -2
- package/dist/util/sql.util.js +0 -6
- 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 +6 -3
|
@@ -40,13 +40,14 @@ function groupByInsertShape(meta, payload) {
|
|
|
40
40
|
return [...groups.values()];
|
|
41
41
|
}
|
|
42
42
|
/**
|
|
43
|
-
* A group's row indexes split into statements of at most `maxRows` rows within the bind budget, payload order
|
|
44
|
-
*
|
|
45
|
-
* is a safe upper bound.
|
|
43
|
+
* A group's row indexes split into statements of at most `maxRows` rows within the bind budget, payload order kept,
|
|
44
|
+
* and a statement whose rows name no column into one per row, as `DEFAULT VALUES` writes. `DEFAULT` cells bind no
|
|
45
|
+
* parameter, so fields-per-record is a safe upper bound. D1 allows 100 binds, which a couple of dozen rows reach.
|
|
46
46
|
*/
|
|
47
47
|
function chunkWithinLimits(meta, payload, group, maxBindValues, maxRows = Infinity) {
|
|
48
|
-
const
|
|
49
|
-
|
|
48
|
+
const width = (indexes) => getInsertFieldKeys(meta, indexes.map((index) => payload[index])).length;
|
|
49
|
+
const size = Math.max(1, Math.min(maxRows, Math.floor(maxBindValues / (width(group) || 1))));
|
|
50
|
+
return chunk(group, size).flatMap((indexes) => (width(indexes) ? [indexes] : chunk(indexes, 1)));
|
|
50
51
|
}
|
|
51
52
|
export class AbstractSqlQuerier extends AbstractQuerier {
|
|
52
53
|
dialect;
|
|
@@ -305,20 +306,27 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
305
306
|
const sole = meta.ids.length === 1;
|
|
306
307
|
const idField = sole ? meta.fields[idKey] : undefined;
|
|
307
308
|
const generatedKey = !!idField && isAutoIncrement(idField, true);
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
309
|
+
// Per group, not per batch: the two carry different columns - one names the key, one does not - so a budget
|
|
310
|
+
// taken over their union would under-fill the statement that is missing one. Header ids are only sound where
|
|
311
|
+
// every row of a statement left its key to the database, so a supplied id cannot void the others.
|
|
312
|
+
const statements = partitionBySuppliedId(rows, idKey).flatMap((group) => {
|
|
311
313
|
const idsReliable = sole &&
|
|
312
314
|
(this.dialect.insertIdSource === 'returning' ||
|
|
313
315
|
(generatedKey && group.every((index) => rows[index][idKey] === undefined)));
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
316
|
+
const { maxBindValues, maxInsertRows } = this.dialect;
|
|
317
|
+
return chunkWithinLimits(meta, rows, group, maxBindValues, maxInsertRows).map((indexes) => ({
|
|
318
|
+
indexes,
|
|
319
|
+
idsReliable,
|
|
320
|
+
}));
|
|
321
|
+
});
|
|
322
|
+
// Inferring multiple ids from the single header id (MySQL) assumes a known stride; a clustered
|
|
323
|
+
// server may set `auto_increment_increment` > 1, so probe it (once, cached) before inferring.
|
|
324
|
+
if (this.dialect.insertIdSource === 'firstId' &&
|
|
325
|
+
statements.some(({ indexes, idsReliable }) => idsReliable && indexes.length > 1)) {
|
|
326
|
+
this.#insertIdIncrement ??= await this.loadInsertIdIncrement();
|
|
327
|
+
}
|
|
328
|
+
const insert = async () => {
|
|
329
|
+
for (const { indexes, idsReliable } of statements) {
|
|
322
330
|
const statementRows = indexes.map((index) => rows[index]);
|
|
323
331
|
const { ids = [] } = await this.exec((ctx) => this.dialect.insert(ctx, entity, statementRows));
|
|
324
332
|
if (idsReliable) {
|
|
@@ -327,42 +335,40 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
327
335
|
}
|
|
328
336
|
}
|
|
329
337
|
}
|
|
330
|
-
}
|
|
331
|
-
await this.
|
|
338
|
+
};
|
|
339
|
+
await (statements.length > 1 ? this.atomically(insert) : insert());
|
|
332
340
|
}
|
|
333
341
|
async internalUpdateMany(entity, q, payload, opts) {
|
|
334
342
|
const { changes = 0 } = await this.exec((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
|
|
335
343
|
return changes;
|
|
336
344
|
}
|
|
337
|
-
async internalUpsertOne(entity, conflictPaths, payload,
|
|
338
|
-
return this.internalUpsertMany(entity, conflictPaths, [payload],
|
|
345
|
+
async internalUpsertOne(entity, conflictPaths, payload, update) {
|
|
346
|
+
return this.internalUpsertMany(entity, conflictPaths, [payload], update);
|
|
339
347
|
}
|
|
340
|
-
async internalUpsertMany(entity, conflictPaths, payload,
|
|
348
|
+
async internalUpsertMany(entity, conflictPaths, payload, update) {
|
|
341
349
|
if (!payload?.length) {
|
|
342
350
|
return { changes: 0 };
|
|
343
351
|
}
|
|
344
352
|
payload = clone(payload);
|
|
345
353
|
const meta = getMeta(entity);
|
|
346
|
-
// One statement per shape, each split again to
|
|
347
|
-
//
|
|
348
|
-
//
|
|
354
|
+
// One statement per shape, each split again to fit the bind budget, less what its assignments bind once.
|
|
355
|
+
// Grouping first is what makes that one figure: every row of a group carries the same columns. No row cap:
|
|
356
|
+
// the one engine with one, SQL Server, upserts through a MERGE, whose source takes any number.
|
|
349
357
|
const statements = groupByInsertShape(meta, payload).flatMap((group) => {
|
|
350
|
-
const
|
|
351
|
-
const assigned = this.dialect.upsertAssignmentBinds(entity, conflictPaths, rows, opts.update);
|
|
358
|
+
const assigned = this.dialect.upsertAssignmentBinds(entity, conflictPaths, payload[group[0]], update);
|
|
352
359
|
return chunkWithinLimits(meta, payload, group, this.dialect.maxBindValues - assigned);
|
|
353
360
|
});
|
|
354
361
|
if (statements.length === 1) {
|
|
355
|
-
return this.runUpsert(entity, conflictPaths, payload,
|
|
362
|
+
return this.runUpsert(entity, conflictPaths, payload, update);
|
|
356
363
|
}
|
|
357
|
-
// An upsert's assignment list is the statement's, so rows of different shapes go in statements
|
|
358
|
-
|
|
359
|
-
return this.transaction(async () => {
|
|
364
|
+
// An upsert's assignment list is the statement's, so rows of different shapes go in statements of their own.
|
|
365
|
+
return this.atomically(async () => {
|
|
360
366
|
let changes = 0;
|
|
361
367
|
// Placed by index, since grouping by shape reorders the rows. A statement reporting fewer ids
|
|
362
368
|
// than it wrote places none.
|
|
363
369
|
const ids = new Array(payload.length);
|
|
364
370
|
for (const indexes of statements) {
|
|
365
|
-
const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]),
|
|
371
|
+
const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]), update);
|
|
366
372
|
changes += written;
|
|
367
373
|
if (reported?.length === indexes.length) {
|
|
368
374
|
for (let position = 0; position < indexes.length; position++) {
|
|
@@ -374,11 +380,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
|
|
|
374
380
|
return { changes, ids };
|
|
375
381
|
});
|
|
376
382
|
}
|
|
377
|
-
async runUpsert(entity, conflictPaths, payload,
|
|
383
|
+
async runUpsert(entity, conflictPaths, payload, update) {
|
|
378
384
|
const meta = getMeta(entity);
|
|
379
385
|
// Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
|
|
380
386
|
const unnamed = meta.ids.length === 1 && payload.some((row) => !namesKey(meta, row));
|
|
381
|
-
const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload,
|
|
387
|
+
const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, update));
|
|
382
388
|
const ordered = payload.length === 1 ||
|
|
383
389
|
(this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
|
|
384
390
|
if (ordered && result.ids?.length === payload.length) {
|
|
@@ -25,7 +25,7 @@ export declare class SqlExpression {
|
|
|
25
25
|
*/
|
|
26
26
|
export declare function schemaDefault(value: unknown, compile: (sql: QueryRaw) => string): unknown;
|
|
27
27
|
/**
|
|
28
|
-
* A default as text
|
|
29
|
-
* holding a JSON
|
|
28
|
+
* A default as text to compare: numbers as their digits, other text as written, and objects (SQL included) and text
|
|
29
|
+
* holding a JSON object or list as JSON with its keys in order, equal as documents, since `jsonb` reprints them.
|
|
30
30
|
*/
|
|
31
31
|
export declare function writtenDefault(value: unknown): string;
|
|
@@ -38,8 +38,8 @@ export function schemaDefault(value, compile) {
|
|
|
38
38
|
return value instanceof QueryRaw ? SqlExpression.parenthesized(compile(value)) : value;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
|
-
* A default as text
|
|
42
|
-
* holding a JSON
|
|
41
|
+
* A default as text to compare: numbers as their digits, other text as written, and objects (SQL included) and text
|
|
42
|
+
* holding a JSON object or list as JSON with its keys in order, equal as documents, since `jsonb` reprints them.
|
|
43
43
|
*/
|
|
44
44
|
export function writtenDefault(value) {
|
|
45
45
|
const document = typeof value === 'string' ? jsonDocument(value) : value;
|
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
|
@@ -330,8 +330,8 @@ export type OnFieldCallback<V = TsTypeOf<FieldType>> = V | QueryRaw | (() => V |
|
|
|
330
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: a document, a list included. */
|
|
334
|
-
type JsonDdlDefault = Scalar |
|
|
333
|
+
/** What a JSON column, and the field-less `FieldOptions`, may default to: a document, a list included, or its text. */
|
|
334
|
+
type JsonDdlDefault = Scalar | Record<string, unknown> | readonly unknown[];
|
|
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/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';
|
|
@@ -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
|
package/dist/util/object.util.js
CHANGED
|
@@ -9,6 +9,9 @@ export function clone(value) {
|
|
|
9
9
|
}
|
|
10
10
|
/** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */
|
|
11
11
|
export function chunk(items, size) {
|
|
12
|
+
if (!(size >= 1)) {
|
|
13
|
+
throw new RangeError(`a chunk holds at least one item, not ${size}`);
|
|
14
|
+
}
|
|
12
15
|
const chunks = [];
|
|
13
16
|
for (let start = 0; start < items.length; start += size) {
|
|
14
17
|
chunks.push(items.slice(start, start + size));
|
package/dist/util/sql.util.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
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. */
|
|
4
|
-
export declare function unflatObjects<T extends object>(objects: RawRow[]): T[];
|
|
5
3
|
/** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
|
|
6
4
|
export declare function unflatObject<T extends object>(row: RawRow, attrsPaths: Record<string, string[]>): T;
|
|
7
5
|
export declare function obtainAttrsPaths<T extends object>(row: T): {
|
package/dist/util/sql.util.js
CHANGED
|
@@ -3,12 +3,6 @@ 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. */
|
|
7
|
-
export function unflatObjects(objects) {
|
|
8
|
-
const [first] = objects;
|
|
9
|
-
const attrsPaths = first ? obtainAttrsPaths(first) : {};
|
|
10
|
-
return objects.map((row) => unflatObject(row, attrsPaths));
|
|
11
|
-
}
|
|
12
6
|
/** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
|
|
13
7
|
export function unflatObject(row, attrsPaths) {
|
|
14
8
|
if (!hasKeys(attrsPaths)) {
|
|
@@ -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.1",
|
|
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';
|
|
@@ -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,17 +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
|
|
|
131
|
-
A `findManyStream` holds its querier until the loop ends, which refuses any other statement meanwhile: inside the loop, run them on another connection
|
|
133
|
+
A `findManyStream` holds its querier until the loop ends, which refuses any other statement meanwhile: inside the loop, run them on another connection; inside a transaction, or on SQLite and PGlite (one shared connection), run them after the loop. That includes an `@AfterLoad` querying through its `querier` on a streamed row. A statement binding more values than the engine takes (100 on D1, 2098 on SQL Server) is refused too: split a long `$in`.
|
|
132
134
|
|
|
133
135
|
## Migrations
|
|
134
136
|
|
|
135
|
-
`npx uql-migrate` reads `uql.config.ts
|
|
137
|
+
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
136
138
|
|
|
137
139
|
- `sync` applies what the entities imply (development only).
|
|
138
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.
|
|
139
141
|
- `up` and `down` apply and revert migrations.
|
|
140
142
|
- `generate:from-db` writes entity classes from an existing database.
|
|
141
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).
|
|
142
145
|
|
|
143
146
|
Triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
|
|
144
147
|
|