uql-orm 0.102.4 → 0.102.6
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/dialect/abstractSqlDialect.d.ts +3 -4
- package/dist/dialect/abstractSqlDialect.js +18 -23
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definition.d.ts +6 -1
- package/dist/entity/metadata/definition.js +8 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/migrate/migrator.d.ts +2 -2
- package/dist/migrate/migrator.js +9 -5
- package/dist/migrate/schemaChange.d.ts +10 -0
- package/dist/migrate/schemaChange.js +17 -0
- package/dist/migrate/schemaGenerator.js +8 -4
- package/dist/migrate/triggerSql.d.ts +2 -0
- package/dist/migrate/triggerSql.js +14 -0
- package/dist/type/migration.d.ts +1 -1
- package/dist/util/sql.d.ts +6 -1
- package/dist/util/sql.js +9 -4
- package/package.json +4 -4
- package/skills/uql-orm/SKILL.md +56 -51
|
@@ -287,10 +287,9 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
|
|
|
287
287
|
*/
|
|
288
288
|
protected resolveOperandField<E>(ctx: QueryContext, entity: Type<E>, key: string, opts: QueryRenderOptions): string;
|
|
289
289
|
/**
|
|
290
|
-
* The expression an inlined computed field stands for, or nothing when the field is a real column.
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
* alias exists only when the field was also selected, which `$where` and `$sort` cannot assume.
|
|
290
|
+
* The expression an inlined computed field stands for, or nothing when the field is a real column. Every
|
|
291
|
+
* clause names it by the expression, never the output alias, which exists only when it was selected; and
|
|
292
|
+
* qualified even when nothing else is, since one opening a correlated subquery has the inner table in scope.
|
|
294
293
|
*/
|
|
295
294
|
private inlinedOperand;
|
|
296
295
|
/** {@link fieldCondition}, appended. */
|
|
@@ -2,7 +2,7 @@ import { fieldOf, getMeta, relationOf } from '../entity/index.js';
|
|
|
2
2
|
import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
|
|
3
3
|
import { utcTimestamp } from '../util/date.js';
|
|
4
4
|
import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
|
|
5
|
-
import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
5
|
+
import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
|
|
6
6
|
import { isJsonScalar } from '../util/object.util.js';
|
|
7
7
|
import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
|
|
8
8
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
@@ -276,12 +276,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
276
276
|
fieldTerm(ctx, meta, key, opts) {
|
|
277
277
|
const field = fieldOf(meta, key);
|
|
278
278
|
const kind = this.fieldKind(meta, field, opts.json);
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
// would bind to *that* table instead of this one.
|
|
283
|
-
const sql = this.rawFragment(ctx, field.computed, opts.prefix ?? this.resolveTableAlias(meta), meta.entity);
|
|
284
|
-
return { sql: opts.json ? this.carried(`(${sql})`, field) : sql, key, kind };
|
|
279
|
+
const inlined = this.inlinedOperand(ctx, meta, key, opts.prefix);
|
|
280
|
+
if (inlined) {
|
|
281
|
+
return { sql: opts.json ? this.carried(inlined, field) : inlined, key, kind };
|
|
285
282
|
}
|
|
286
283
|
const columnName = this.resolveColumnName(key, field);
|
|
287
284
|
const column = this.escapeId(opts.prefix, true, true) + this.escapeId(columnName);
|
|
@@ -636,18 +633,18 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
636
633
|
resolveOperandField(ctx, entity, key, opts) {
|
|
637
634
|
const meta = getMeta(entity);
|
|
638
635
|
const field = meta.fields[key];
|
|
639
|
-
return
|
|
640
|
-
this.columnWithPrefix(key, field, opts));
|
|
636
|
+
return this.inlinedOperand(ctx, meta, key, opts.prefix) ?? this.columnWithPrefix(key, field, opts);
|
|
641
637
|
}
|
|
642
638
|
/**
|
|
643
|
-
* The expression an inlined computed field stands for, or nothing when the field is a real column.
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
* alias exists only when the field was also selected, which `$where` and `$sort` cannot assume.
|
|
639
|
+
* The expression an inlined computed field stands for, or nothing when the field is a real column. Every
|
|
640
|
+
* clause names it by the expression, never the output alias, which exists only when it was selected; and
|
|
641
|
+
* qualified even when nothing else is, since one opening a correlated subquery has the inner table in scope.
|
|
647
642
|
*/
|
|
648
|
-
inlinedOperand(ctx,
|
|
649
|
-
const
|
|
650
|
-
return
|
|
643
|
+
inlinedOperand(ctx, meta, key, prefix) {
|
|
644
|
+
const field = meta.fields[key];
|
|
645
|
+
return field && isInlinedExpression(field)
|
|
646
|
+
? this.rawFragment(ctx, columnRef(meta.entity, key), prefix ?? this.resolveTableAlias(meta), meta.entity)
|
|
647
|
+
: undefined;
|
|
651
648
|
}
|
|
652
649
|
/** {@link fieldCondition}, appended. */
|
|
653
650
|
compareFieldOperator(ctx, entity, key, op, val, opts = {}) {
|
|
@@ -947,8 +944,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
947
944
|
sortColumns(ctx, meta, key, prefix) {
|
|
948
945
|
const field = meta.fields[key];
|
|
949
946
|
if (field) {
|
|
950
|
-
const expr = this.inlinedOperand(ctx,
|
|
951
|
-
this.columnWithPrefix(key, field, { prefix });
|
|
947
|
+
const expr = this.inlinedOperand(ctx, meta, key, prefix) ?? this.columnWithPrefix(key, field, { prefix });
|
|
952
948
|
return [{ expr, output: false }];
|
|
953
949
|
}
|
|
954
950
|
const json = this.resolveJsonDotPath(meta, key, prefix);
|
|
@@ -1134,11 +1130,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1134
1130
|
}
|
|
1135
1131
|
/** A field as an aggregate reads it: its column, or the expression an inlined one stands for. */
|
|
1136
1132
|
aggregateOperand(ctx, entity, key, prefix) {
|
|
1137
|
-
const
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
};
|
|
1133
|
+
const meta = getMeta(entity);
|
|
1134
|
+
const field = meta.fields[key];
|
|
1135
|
+
const inlined = this.inlinedOperand(ctx, meta, key, prefix);
|
|
1136
|
+
return { sql: inlined ?? this.columnWithPrefix(key, field, { prefix }), bare: !inlined };
|
|
1142
1137
|
}
|
|
1143
1138
|
/**
|
|
1144
1139
|
* ORDER BY for aggregate queries - handles both entity-field and alias references. A grouped
|
package/dist/entity/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export * from './decorator/entity.js';
|
|
2
2
|
export * from './decorator/members.js';
|
|
3
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
|
|
3
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
|
package/dist/entity/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export * from './decorator/entity.js';
|
|
2
2
|
export * from './decorator/members.js';
|
|
3
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
|
|
3
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
|
|
1
|
+
import type { EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
|
|
2
2
|
export declare function defineField<E>(entity: Type<E>, key: string, opts?: FieldOptions): EntityMeta<E>;
|
|
3
3
|
export declare function defineId<E>(entity: Type<E>, key: string, opts: FieldOptions): EntityMeta<E>;
|
|
4
4
|
/** `T` is the relation's target, independent of the owner `E`. */
|
|
@@ -9,6 +9,11 @@ export declare function defineRelation<E, T extends object>(entity: Type<E>, key
|
|
|
9
9
|
* exist, and the registry holds data alone.
|
|
10
10
|
*/
|
|
11
11
|
export declare function relationRegistration<T extends object, O>({ mappedBy, references, ...opts }: RelationOptions<T, O>): RelationRegistration;
|
|
12
|
+
/**
|
|
13
|
+
* The member `pick` reads, `keyOf((post: KeyMap<Post>) => post.title)` answering `'title'`: how code generic over its
|
|
14
|
+
* entity names one, since a selector follows a rename and a string does not.
|
|
15
|
+
*/
|
|
16
|
+
export declare function keyOf<E, K extends keyof E>(pick: (keys: KeyMap<E>) => K): K;
|
|
12
17
|
export declare function defineHook<E>(entity: Type<E>, methodName: string, event: HookEvent): EntityMeta<E>;
|
|
13
18
|
/**
|
|
14
19
|
* Declares a composite index, its columns read off the entity's refs. `unique` and the authored column
|
|
@@ -64,7 +64,7 @@ export function relationRegistration({ mappedBy, references, ...opts }) {
|
|
|
64
64
|
const joined = references?.(keyMap(), keyMap());
|
|
65
65
|
return {
|
|
66
66
|
...opts,
|
|
67
|
-
...(mappedBy && { mappedBy: mappedBy
|
|
67
|
+
...(mappedBy && { mappedBy: keyOf(mappedBy) }),
|
|
68
68
|
...(joined && { references: typeof joined === 'string' ? joined : [...joined] }),
|
|
69
69
|
};
|
|
70
70
|
}
|
|
@@ -72,6 +72,13 @@ export function relationRegistration({ mappedBy, references, ...opts }) {
|
|
|
72
72
|
function keyMap() {
|
|
73
73
|
return KEY_MAP;
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* The member `pick` reads, `keyOf((post: KeyMap<Post>) => post.title)` answering `'title'`: how code generic over its
|
|
77
|
+
* entity names one, since a selector follows a rename and a string does not.
|
|
78
|
+
*/
|
|
79
|
+
export function keyOf(pick) {
|
|
80
|
+
return pick(keyMap());
|
|
81
|
+
}
|
|
75
82
|
const KEY_MAP = new Proxy({}, { get: (_, key) => key });
|
|
76
83
|
function addRelation(entity, key, registration) {
|
|
77
84
|
if (!registration.entity) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
export { captureContext, getContext, withContext } from './context/context.js';
|
|
2
2
|
export * from './entity/decorator/entity.js';
|
|
3
3
|
export * from './entity/decorator/members.js';
|
|
4
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
|
|
4
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, keyOf, removeEntity, } from './entity/metadata/definition.js';
|
|
5
5
|
export * from './namingStrategy/index.js';
|
|
6
6
|
export { type QueryError, queryErrorKind } from './querier/queryError.js';
|
|
7
7
|
export type * from './type/index.js';
|
|
8
8
|
export { idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
9
9
|
export { withDeleted } from './util/filters.util.js';
|
|
10
|
+
export { sortOf } from './util/query.util.js';
|
|
10
11
|
export type { HookContext } from './util/hook.util.js';
|
|
11
12
|
export { DefaultLogger } from './util/logger.js';
|
|
12
13
|
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, uuid, uuidv7 } from './util/sql.js';
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
export { captureContext, getContext, withContext } from './context/context.js';
|
|
2
2
|
export * from './entity/decorator/entity.js';
|
|
3
3
|
export * from './entity/decorator/members.js';
|
|
4
|
-
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, removeEntity, } from './entity/metadata/definition.js';
|
|
4
|
+
export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getMeta, idOf, keyOf, removeEntity, } from './entity/metadata/definition.js';
|
|
5
5
|
export * from './namingStrategy/index.js';
|
|
6
6
|
export { queryErrorKind } from './querier/queryError.js';
|
|
7
7
|
export { idKey, isSqlQuerier, versionKey } from './type/index.js';
|
|
8
8
|
export { withDeleted } from './util/filters.util.js';
|
|
9
|
+
export { sortOf } from './util/query.util.js';
|
|
9
10
|
export { DefaultLogger } from './util/logger.js';
|
|
10
11
|
export { currentDate, currentTime, currentTimestamp, raw, refs, sql, uuid, uuidv7 } from './util/sql.js';
|
|
11
12
|
export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './util/triggerWrite.js';
|
|
@@ -71,8 +71,8 @@ export declare class Migrator {
|
|
|
71
71
|
generateFromEntities(name: string): Promise<string>;
|
|
72
72
|
/**
|
|
73
73
|
* What a generated migration does that its reader must not miss: each column it drops or retypes, which
|
|
74
|
-
* can lose data, and each table it creates empty while the database holds
|
|
75
|
-
* same columns, which may be the table renamed
|
|
74
|
+
* can lose data, or its rollback puts back nullable; and each table it creates empty while the database holds
|
|
75
|
+
* one no entity names with the same columns, which may be the table renamed, never renamed here.
|
|
76
76
|
*/
|
|
77
77
|
private noteChanges;
|
|
78
78
|
/**
|
package/dist/migrate/migrator.js
CHANGED
|
@@ -13,7 +13,7 @@ import { buildMigrationModule } from './codegen/migrationFile.js';
|
|
|
13
13
|
import { introspectorFor } from './introspection/registry.js';
|
|
14
14
|
import { DEFAULT_LOCK_TIMEOUT } from './migrationLock.js';
|
|
15
15
|
import { migrationBuilderFor, migrationTargetFor, } from './migrationTarget.js';
|
|
16
|
-
import { dropped, lacksValue, newlyRequired, nonEmpty,
|
|
16
|
+
import { dropped, lacksValue, newlyRequired, nonEmpty, rollbackDiff, sides, unfillableRestores, withoutRebuild, } from './schemaChange.js';
|
|
17
17
|
import { constraintNameOf, dropsForeignKeysFirst } from './schemaGenerator.js';
|
|
18
18
|
import { DEFAULT_MIGRATIONS_TABLE } from './storage/databaseStorage.js';
|
|
19
19
|
/**
|
|
@@ -186,7 +186,7 @@ export class Migrator {
|
|
|
186
186
|
}
|
|
187
187
|
// Diff by diff in reverse, each rolled back in the order its generator wrote it.
|
|
188
188
|
const down = [
|
|
189
|
-
...altered.toReversed().flatMap((diff) => generator.generateAlterTable(
|
|
189
|
+
...altered.toReversed().flatMap((diff) => generator.generateAlterTable(rollbackDiff(diff))),
|
|
190
190
|
...generator.generateDropSchema(this.createdEntities(created), { ifExists: true }),
|
|
191
191
|
];
|
|
192
192
|
const { emit } = this.target.source;
|
|
@@ -200,16 +200,20 @@ export class Migrator {
|
|
|
200
200
|
}
|
|
201
201
|
/**
|
|
202
202
|
* What a generated migration does that its reader must not miss: each column it drops or retypes, which
|
|
203
|
-
* can lose data, and each table it creates empty while the database holds
|
|
204
|
-
* same columns, which may be the table renamed
|
|
203
|
+
* can lose data, or its rollback puts back nullable; and each table it creates empty while the database holds
|
|
204
|
+
* one no entity names with the same columns, which may be the table renamed, never renamed here.
|
|
205
205
|
*/
|
|
206
206
|
async noteChanges(generator, created, altered) {
|
|
207
|
-
for (const
|
|
207
|
+
for (const diff of altered) {
|
|
208
|
+
const { tableName, columns = [] } = diff;
|
|
208
209
|
for (const { from, to } of columns.filter((change) => change.isBreaking)) {
|
|
209
210
|
this.logger.logWarn(to
|
|
210
211
|
? `Retypes "${tableName}"."${to.name}" from ${from?.type} to ${to.type}: a value that does not fit is lost or refused.`
|
|
211
212
|
: `Drops "${tableName}"."${from?.name}", losing what it holds.`);
|
|
212
213
|
}
|
|
214
|
+
for (const column of unfillableRestores(diff)) {
|
|
215
|
+
this.logger.logWarn(`Rolls "${tableName}"."${column.name}" back nullable, with nothing to fill it: require it in the down once filled.`);
|
|
216
|
+
}
|
|
213
217
|
}
|
|
214
218
|
for (const { from, to } of await this.renamedTables(generator, created)) {
|
|
215
219
|
this.logger.logWarn(`Creates "${to}" empty, while "${from}", which no entity names, holds the same columns. If it was ` +
|
|
@@ -18,6 +18,16 @@ export declare function lacksValue(column: ColumnSchema): boolean;
|
|
|
18
18
|
export declare function needsRebuild(diff: SchemaDiff): boolean;
|
|
19
19
|
/** `diff` less its rebuild and everything only a rebuild makes: what an `ALTER` can still apply alone. */
|
|
20
20
|
export declare function withoutRebuild(diff: SchemaDiff): SchemaDiff;
|
|
21
|
+
/**
|
|
22
|
+
* The columns `diff` drops that its rollback puts back nullable: required, with nothing to fill the rows. A
|
|
23
|
+
* rebuild restores its table verbatim instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare function unfillableRestores(diff: SchemaDiff): ColumnSchema[];
|
|
26
|
+
/**
|
|
27
|
+
* `diff` as a rollback runs it: reversed, its {@link unfillableRestores} put back nullable, since no engine
|
|
28
|
+
* adds a required column to rows holding none.
|
|
29
|
+
*/
|
|
30
|
+
export declare function rollbackDiff(diff: SchemaDiff): SchemaDiff;
|
|
21
31
|
/** `items`, or nothing where it has none, so an empty change list is left off a diff. */
|
|
22
32
|
export declare function nonEmpty<T>(items: readonly T[]): readonly T[] | undefined;
|
|
23
33
|
/**
|
|
@@ -44,6 +44,23 @@ export function withoutRebuild(diff) {
|
|
|
44
44
|
rebuild: undefined,
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* The columns `diff` drops that its rollback puts back nullable: required, with nothing to fill the rows. A
|
|
49
|
+
* rebuild restores its table verbatim instead.
|
|
50
|
+
*/
|
|
51
|
+
export function unfillableRestores(diff) {
|
|
52
|
+
return diff.rebuild ? [] : dropped(diff.columns).filter(lacksValue);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* `diff` as a rollback runs it: reversed, its {@link unfillableRestores} put back nullable, since no engine
|
|
56
|
+
* adds a required column to rows holding none.
|
|
57
|
+
*/
|
|
58
|
+
export function rollbackDiff(diff) {
|
|
59
|
+
const unfillable = new Set(unfillableRestores(diff));
|
|
60
|
+
const reversed = reverseDiff(diff);
|
|
61
|
+
const columns = reversed.columns?.map((change) => change.to && unfillable.has(change.to) ? { ...change, to: { ...change.to, nullable: true } } : change);
|
|
62
|
+
return { ...reversed, columns };
|
|
63
|
+
}
|
|
47
64
|
/** `items`, or nothing where it has none, so an empty change list is left off a diff. */
|
|
48
65
|
export function nonEmpty(items) {
|
|
49
66
|
return items.length ? items : undefined;
|
|
@@ -17,7 +17,7 @@ import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, table
|
|
|
17
17
|
import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
|
|
18
18
|
import { assertIndexPredicate } from './indexPredicate.js';
|
|
19
19
|
import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
|
|
20
|
-
import { dropTrigger, dropTriggerBody, renderTrigger, stampTriggers } from './triggerSql.js';
|
|
20
|
+
import { dropTrigger, dropTriggerBody, namesAny, renderTrigger, stampTriggers } from './triggerSql.js';
|
|
21
21
|
/** The SQL schema generator, one for every SQL engine, its spellings taken from the dialect and its DDL classes. */
|
|
22
22
|
export class SqlSchemaGenerator {
|
|
23
23
|
dialect;
|
|
@@ -154,8 +154,12 @@ export class SqlSchemaGenerator {
|
|
|
154
154
|
generateAlterTable(diff) {
|
|
155
155
|
const { tableName, primaryKey, columns, rebuild } = diff;
|
|
156
156
|
const fills = this.defaultFills(columns);
|
|
157
|
-
const moved =
|
|
158
|
-
|
|
157
|
+
const moved = [
|
|
158
|
+
...sides(columns, 'from').map(({ name }) => name),
|
|
159
|
+
...(diff.renamedColumns ?? []).flatMap(({ from, to }) => [from, to]),
|
|
160
|
+
];
|
|
161
|
+
// A rebuild drops every trigger with its table; an alter, only a kept one naming a column it moves.
|
|
162
|
+
const triggers = (diff.triggers ?? []).filter(({ from, to }) => rebuild || !from || !to || to.statements.some((statement) => namesAny(statement, moved)));
|
|
159
163
|
const triggerDrops = terminated(sides(triggers, 'from').flatMap((trigger) => dropTrigger(this.dialect, tableName, trigger.name)));
|
|
160
164
|
const triggerCreates = terminated(sides(triggers, 'to').flatMap((trigger) => trigger.statements));
|
|
161
165
|
if (rebuild) {
|
|
@@ -266,7 +270,7 @@ export class SqlSchemaGenerator {
|
|
|
266
270
|
}))),
|
|
267
271
|
foreignKeys: nonEmpty(foreignKeys),
|
|
268
272
|
checks: nonEmpty(tableDiff?.checks ?? []),
|
|
269
|
-
// A kept trigger as both sides, which the alter cycles only where a column moves under it.
|
|
273
|
+
// A kept trigger as both sides, which the alter cycles only where a column it names moves under it.
|
|
270
274
|
triggers: nonEmpty([
|
|
271
275
|
...(tableDiff?.triggers ?? []),
|
|
272
276
|
...matchByKey(desired.triggers, currentTable.triggers, (it) => it.name).matched.map(([to, from]) => ({
|
|
@@ -20,3 +20,5 @@ export declare function dropTriggerBody(dialect: AbstractSqlDialect, schema: str
|
|
|
20
20
|
* one declaration.
|
|
21
21
|
*/
|
|
22
22
|
export declare function stampTriggers<E extends object>(dialect: AbstractSqlDialect, meta: EntityMeta<E>): EntityTriggerMeta<E>[];
|
|
23
|
+
/** Whether `statement` names any of `columns` as a whole identifier, quoted or not, in any case. */
|
|
24
|
+
export declare function namesAny(statement: string, columns: readonly string[]): boolean;
|
|
@@ -245,3 +245,17 @@ function rowsFrom(dialect, meta, operation, { $new, $old }, filter) {
|
|
|
245
245
|
const from = operation === 'UPDATE' ? `${$new} JOIN ${$old} ON ${keyed.join(' AND ')}` : operation === 'INSERT' ? $new : $old;
|
|
246
246
|
return { from, where: filter || undefined };
|
|
247
247
|
}
|
|
248
|
+
const IDENTIFIER_CHAR = /[\p{L}\p{N}_$]/u;
|
|
249
|
+
/** Whether `statement` names any of `columns` as a whole identifier, quoted or not, in any case. */
|
|
250
|
+
export function namesAny(statement, columns) {
|
|
251
|
+
const text = statement.toLowerCase();
|
|
252
|
+
return columns.some((column) => {
|
|
253
|
+
const name = column.toLowerCase();
|
|
254
|
+
for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1)) {
|
|
255
|
+
if (!IDENTIFIER_CHAR.test(text.charAt(at - 1)) && !IDENTIFIER_CHAR.test(text.charAt(at + name.length))) {
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return false;
|
|
260
|
+
});
|
|
261
|
+
}
|
package/dist/type/migration.d.ts
CHANGED
|
@@ -257,7 +257,7 @@ export interface SchemaGenerator {
|
|
|
257
257
|
* rejected once the foreign keys are really there.
|
|
258
258
|
*/
|
|
259
259
|
generateDropSchema(entities: readonly Type<object>[], options?: DropSchemaOptions): string[];
|
|
260
|
-
/** The statements taking a table through `diff`; its rollback is
|
|
260
|
+
/** The statements taking a table through `diff`; its rollback is `rollbackDiff(diff)`. */
|
|
261
261
|
generateAlterTable(diff: SchemaDiff): string[];
|
|
262
262
|
/**
|
|
263
263
|
* The statements one migration builder operation runs as, one string each. An operation the engine
|
package/dist/util/sql.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EntitySql, type EntityWhere, type EntityWhereMeta, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type Type } from '../type/index.js';
|
|
1
|
+
import { ColumnRef, type EntitySql, type EntityWhere, type EntityWhereMeta, QuerySql, type QuerySqlFn, type ComputedRefs, type RefMap, type SqlArg, type SqlStatement, type SqlValueName, type TriggerRowName, type Type } from '../type/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Raw SQL, where an interpolated value binds, a `refs` field renders its column, and a `sql` renders
|
|
4
4
|
* in place: `sql`GREATEST(0, ${user.credits} - ${amount})``. A callback writes whatever it writes, so
|
|
@@ -54,5 +54,10 @@ export declare function entityWhere<E>(where: EntityWhere<E>): EntityWhereMeta<E
|
|
|
54
54
|
* Columns only: a relation's aggregate is a subquery, and a trigger fires on one row, not over a table.
|
|
55
55
|
*/
|
|
56
56
|
export declare function rowRefs<E>(entity: Type<E>, qualifier: TriggerRowName): RefMap<E>;
|
|
57
|
+
/**
|
|
58
|
+
* One field as SQL, against its own entity or, read off a definition, the entity rendering it. A
|
|
59
|
+
* `qualifier` names the row it reads from, `NEW` or `OLD`, instead of the alias in scope.
|
|
60
|
+
*/
|
|
61
|
+
export declare function columnRef(entity: Type<unknown> | undefined, key: string, qualifier?: string): ColumnRef;
|
|
57
62
|
/** @deprecated Renamed to {@link sql}, the tag editors recognise for SQL highlighting. */
|
|
58
63
|
export declare const raw: typeof sql;
|
package/dist/util/sql.js
CHANGED
|
@@ -155,7 +155,7 @@ export function rowRefs(entity, qualifier) {
|
|
|
155
155
|
* One field as SQL, against its own entity or, read off a definition, the entity rendering it. A
|
|
156
156
|
* `qualifier` names the row it reads from, `NEW` or `OLD`, instead of the alias in scope.
|
|
157
157
|
*/
|
|
158
|
-
function columnRef(entity, key, qualifier) {
|
|
158
|
+
export function columnRef(entity, key, qualifier) {
|
|
159
159
|
return new ColumnRef(key, (opts) => {
|
|
160
160
|
const owner = entity ?? opts.entity;
|
|
161
161
|
if (!owner) {
|
|
@@ -178,13 +178,18 @@ function renderColumn(meta, key, opts, qualifier) {
|
|
|
178
178
|
throw new UqlUsageError(`'${entityName(meta)}.${key}' reads a relation, which a trigger's row cannot: it fires on one row, ` +
|
|
179
179
|
'with no table in scope to correlate a subquery to. Name the columns it is derived from instead.');
|
|
180
180
|
}
|
|
181
|
-
|
|
182
|
-
field.computed.render(scope);
|
|
183
|
-
scope.ctx.append(')');
|
|
181
|
+
grouped(field.computed).render(scope);
|
|
184
182
|
return;
|
|
185
183
|
}
|
|
186
184
|
scope.ctx.append(scope.escapedPrefix + scope.dialect.escapeId(scope.dialect.columnOf(meta, key), true));
|
|
187
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* An inlined computed field's expression as every clause splices it: grouped, so a comparison inside cannot
|
|
188
|
+
* chain with one around it (`a <= b = ?`). A relation aggregate is a subquery, grouped already.
|
|
189
|
+
*/
|
|
190
|
+
function grouped(computed) {
|
|
191
|
+
return computed instanceof RelationAggregate ? computed : sql `(${computed})`;
|
|
192
|
+
}
|
|
188
193
|
/** @deprecated Renamed to {@link sql}, the tag editors recognise for SQL highlighting. */
|
|
189
194
|
export const raw = sql;
|
|
190
195
|
/** A tag call passes the frozen strings array, which carries its own `sql` counterpart. */
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"homepage": "https://uql-orm.dev",
|
|
4
4
|
"description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"version": "0.102.
|
|
6
|
+
"version": "0.102.6",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"engines": {
|
|
9
9
|
"node": ">=22.18"
|
|
@@ -126,8 +126,8 @@
|
|
|
126
126
|
}
|
|
127
127
|
},
|
|
128
128
|
"devDependencies": {
|
|
129
|
-
"@electric-sql/pglite": "0.5.
|
|
130
|
-
"@electric-sql/pglite-pgvector": "0.0.
|
|
129
|
+
"@electric-sql/pglite": "0.5.10",
|
|
130
|
+
"@electric-sql/pglite-pgvector": "0.0.11",
|
|
131
131
|
"@libsql/client": "^0.18.0",
|
|
132
132
|
"@neondatabase/serverless": "^1.2.0",
|
|
133
133
|
"@nestjs/common": "^12.1.3",
|
|
@@ -144,7 +144,7 @@
|
|
|
144
144
|
"express": "^5.3.0",
|
|
145
145
|
"mariadb": "^3.5.4",
|
|
146
146
|
"mongodb": "^7.7.0",
|
|
147
|
-
"mssql": "^12.7.
|
|
147
|
+
"mssql": "^12.7.9",
|
|
148
148
|
"mysql2": "^3.24.6",
|
|
149
149
|
"pg": "^8.23.1",
|
|
150
150
|
"pg-query-stream": "^4.17.1",
|
package/skills/uql-orm/SKILL.md
CHANGED
|
@@ -10,9 +10,9 @@ description: >
|
|
|
10
10
|
|
|
11
11
|
# UQL
|
|
12
12
|
|
|
13
|
-
Entities are classes
|
|
13
|
+
Entities are classes. A query is a JSON object checked key by key against the entity, and it runs the same on every supported database. There is no schema file, no generated client and no query builder.
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
Full docs are Markdown: the index at https://uql-orm.dev/llms.txt, and each page at its URL plus `.md`. Read the page for the task before guessing an option. The whole site is one file at https://uql-orm.dev/llms-full.txt (about 530 KB), too large to load for one task.
|
|
16
16
|
|
|
17
17
|
## Setup
|
|
18
18
|
|
|
@@ -20,11 +20,11 @@ The full docs are Markdown at https://uql-orm.dev/llms.txt, one page per URL. Re
|
|
|
20
20
|
npm install uql-orm pg # or mysql2, mariadb, better-sqlite3, mongodb, @libsql/client, ...
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
ESM only (a CommonJS app loads it through `require(esm)`). Node 22.18+, Bun or an edge runtime, TypeScript 5.7+.
|
|
23
|
+
ESM only (a CommonJS app loads it through `require(esm)`). Needs Node 22.18+, Bun or an edge runtime, and TypeScript 5.7+.
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
Decorators are TC39 standard. Never enable `experimentalDecorators` or `emitDecoratorMetadata`, and never import `reflect-metadata`. In `tsconfig.json`, `module` is `nodenext` or `preserve`, and `target` is dated (`es2022`+), not `esnext`. A project already on legacy decorators (NestJS, Angular) keeps its config and defines entities with `defineEntity`. NestJS: https://uql-orm.dev/nestjs.md
|
|
26
26
|
|
|
27
|
-
Node's type stripping runs no decorators
|
|
27
|
+
Node's type stripping runs no decorators, so on Node add `tsx` (`npm i -D tsx`); `uql-migrate` loads `uql.config.ts` through it. Next.js needs `@babel/plugin-proposal-decorators` at `version: '2023-11'` in `babel.config.json`. A bundler that minifies class names needs `@Entity({ name: 'todo' })`, since the table name defaults to the class name.
|
|
28
28
|
|
|
29
29
|
```ts
|
|
30
30
|
// uql.config.ts
|
|
@@ -37,7 +37,7 @@ export const pool = new PgQuerierPool({ connectionString: process.env.DATABASE_U
|
|
|
37
37
|
export default { pool, entities: [User, Post] } satisfies Config;
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
Driver entry points: `uql-orm/postgres`, `mysql`, `mariadb`, `sqlite`, `mongodb`, `libsql`, `turso`, `neon`, `d1`, `pglite`, `bun-sql`, `mssql`, `cockroachdb`. Build the pool once per process and import it.
|
|
41
41
|
|
|
42
42
|
## Entities
|
|
43
43
|
|
|
@@ -72,20 +72,21 @@ export class Post {
|
|
|
72
72
|
}
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
- A class inherits
|
|
76
|
-
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references`
|
|
77
|
-
- A column is nullable unless it says `nullable: false
|
|
78
|
-
-
|
|
79
|
-
-
|
|
80
|
-
- `defaultValue` is a value of the field's type
|
|
81
|
-
- `currentTimestamp` is the database clock, UTC to the millisecond on every engine
|
|
82
|
-
-
|
|
83
|
-
-
|
|
84
|
-
-
|
|
85
|
-
-
|
|
86
|
-
-
|
|
87
|
-
- `@Field({
|
|
88
|
-
-
|
|
75
|
+
- A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. The base needs no `@Entity()` unless it is a table. A child entry with the same name replaces the base's.
|
|
76
|
+
- Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` and inherits the target's type. A field read off `refs(Entity)` carries its type too. A JSON column of no fixed shape is a bare `Json`.
|
|
77
|
+
- A column is nullable unless it says `nullable: false`. Its property must admit `null`: `title?: string | null`. A property without `| null` on a nullable column is a compile error.
|
|
78
|
+
- `Date` is an instant, stored in UTC to the millisecond on every engine; `precision` sets other fractional digits. `'decimal'` is exact text (`price?: string | null`). `type: Number` with `precision`/`scale` opts into a rounding JS number.
|
|
79
|
+
- Declare a `nullable: false` column with `!` (`email!: string`). Declare `?` for anything an insert may omit: nullable, `onInsert`, `defaultValue`, `eager: false`, `computed` fields, and relations. A single-column key and a `version` are filled by uql.
|
|
80
|
+
- `defaultValue` is a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included.
|
|
81
|
+
- `currentTimestamp` is the database clock, UTC to the millisecond on every engine. Use it for defaults, stamps, `onUpdate` and `$where`, not a raw `CURRENT_TIMESTAMP`.
|
|
82
|
+
- An engine's own column type is a `sql` constant: ``columnType: sql`tsvector` ``.
|
|
83
|
+
- Members are named by callbacks, never strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
|
|
84
|
+
- `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity.
|
|
85
|
+
- `cascade: true` writes related rows in the same transaction. A to-one holding the key takes `'persist'`, and `{ id }` links an existing row. An update replaces a to-many's rows: listed ones are saved or kept, the rest removed.
|
|
86
|
+
- Partial index: `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })`. Write the predicate as a query, not `sql`, so the planner can match it. An unnamed partial index carries a hash of its `where` in its name, so editing the predicate replaces it.
|
|
87
|
+
- Optimistic lock: `@Field({ type: Number, version: true })` with `[versionKey]?: 'version'` on the class. An update must carry the version it read (a compile error otherwise). A stale one throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409). A versioned update names one row by its id. Save and upsert are refused for such an entity.
|
|
88
|
+
- Computed: `@Field({ computed })` on a `readonly` property, as SQL over the row ``(u) => sql`${u.first} || ' ' || ${u.last}` `` or a relation aggregate `(order) => order.items.count()`. `stored: true` makes a generated column. `stored: ['insert', 'update']` makes a stamp that a database trigger writes whoever writes the row. `onUpdate` covers only uql's own writes.
|
|
89
|
+
- `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`, or raw `sql`. The builders are typed by the entity written and render on every engine. `deferred: true` fires an after trigger at commit, on Postgres only. A trigger's writes skip uql's fills and entity filters. A `deleteFrom` in a trigger deletes outright, even on a soft-delete entity: write a soft delete as an `updateTable`. MongoDB has no triggers. Details: https://uql-orm.dev/entities/triggers.md
|
|
89
90
|
- `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
|
|
90
91
|
|
|
91
92
|
## Queries
|
|
@@ -104,28 +105,30 @@ const users = await pool.findMany(User, {
|
|
|
104
105
|
});
|
|
105
106
|
```
|
|
106
107
|
|
|
107
|
-
-
|
|
108
|
-
-
|
|
109
|
-
-
|
|
110
|
-
- `$
|
|
111
|
-
-
|
|
112
|
-
-
|
|
113
|
-
- `$
|
|
114
|
-
-
|
|
115
|
-
- `$
|
|
116
|
-
-
|
|
117
|
-
-
|
|
118
|
-
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update
|
|
119
|
-
-
|
|
120
|
-
-
|
|
121
|
-
-
|
|
122
|
-
-
|
|
123
|
-
-
|
|
124
|
-
-
|
|
108
|
+
- Query keys: `$select`, `$exclude`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
|
|
109
|
+
- Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first, or the query's `$entity`. Signatures: https://uql-orm.dev/querying/methods.md
|
|
110
|
+
- Results are narrowed to what the query selected and populated. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`.
|
|
111
|
+
- `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent.
|
|
112
|
+
- In code generic over its entity, `{ [key]: 'asc' }` widens to an index signature. Take the member as a selector, `since: (keys: KeyMap<E>) => K`, read it with `keyOf(since)`, and sort with `sortOf<E>([[key, 'asc']])`. A selector follows a rename; a string key does not. `$where` and writes by a constant have no such builder: take a callback the caller writes against its own entity, `(state) => ({ state })`.
|
|
113
|
+
- `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, plus `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`, which behave the same on every engine. Unqualified, each engine keeps its own null order.
|
|
114
|
+
- `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`, `$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`, `$isNotNull`. Combine with `$and`, `$or`, `$not`, `$nor`. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
|
|
115
|
+
- An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
|
|
116
|
+
- NULL compares as the engine does: on SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`. Ask for NULL with `{ col: null }` and its absence with `{ col: { $ne: null } }`.
|
|
117
|
+
- Full-text: `$text: { $value }` in `$where`, through an `@Index(..., { type: 'fulltext', config })`. `$sort: { $text: 'desc' }` ranks by relevance, and `{ $text: { $project: 'score' } }` returns the score, typed `WithProjection<E, 'score'>`.
|
|
118
|
+
- `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does. It returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. Pass `endCursor` as `$after`, or `startCursor` as `$before`. `$sort` must end in the key or a unique `nullable: false` field, and takes no `$skip`. A nullable leading sort key pages correctly but cannot use an index.
|
|
119
|
+
- `upsertOne(Entity, { email: true }, row, update?)`: a conflicting row takes `update`, an update payload with operators (`{ uses: { $inc: 1 } }`). An empty `{}` leaves a conflicting row alone. Cascaded relations write on either branch. Resolves to the row's id.
|
|
120
|
+
- Writes take `{ returning: { id: true } }` as their last argument and resolve to those rows, read back in the same transaction. Without it, inserts and upserts resolve to ids, and updates and deletes to a count. An update or delete writes exactly the rows it reports. One that reads its rows first holds them, so a racing writer waits for the commit. SQLite and MongoDB have no row locks and fail the racing writer with a retryable error instead.
|
|
121
|
+
- A query is plain data, so it can be sent from a browser to `uql-orm/http`. Its handler serves only the entities its required `include` names.
|
|
122
|
+
- `updateMany` and `deleteMany` that name no rows throw: no `$where` holding a value, and no `$limit`. Pass `{ unfiltered: true }` to mean the whole table.
|
|
123
|
+
- Updates use operators in the statement: `{ stock: { $inc: -1 } }` or `$mul`, with NULL counted as 0. Put a guard in `$where` (`stock: { $gte: 1 }`) to make a decrement race-safe. On SQL the step can be a ref or `sql` (`{ total: { $inc: newRow.amount } }` in a trigger).
|
|
124
|
+
- JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order on one value. `$set` and `$unset` take keys or dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`. A JSON array (`tags?: Json<string[]>`) takes lists: `{ tags: { $pull: ['old'], $addToSet: ['new'] } }`.
|
|
125
|
+
- `$lock: true` locks the rows a read returns, and `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. It needs an open transaction. SQLite, libSQL, Turso, D1 and MongoDB have no row lock and refuse it.
|
|
126
|
+
- `queryErrorKind(err)` names a failure the same on every engine: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code. Every error UQL raises is a `UqlError`.
|
|
127
|
+
- Raw SQL: ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object (bind `JSON.stringify(doc)`). `sql` builds a fragment, and `sql.join(fragments, ' AND ')` joins them. `sql.text(s)` runs trusted SQL held in a string. Never build it from user input. `sql` is a tag: ``sql(`...`)`` does not compile. `raw` is its deprecated name.
|
|
125
128
|
|
|
126
129
|
## Connections and transactions
|
|
127
130
|
|
|
128
|
-
Every method is on
|
|
131
|
+
Every method is on the pool and on a querier. A pool call takes a connection for that call. To run several operations on one connection, or atomically, use a transaction:
|
|
129
132
|
|
|
130
133
|
```ts
|
|
131
134
|
await pool.transaction(async (querier) => {
|
|
@@ -134,29 +137,31 @@ await pool.transaction(async (querier) => {
|
|
|
134
137
|
});
|
|
135
138
|
```
|
|
136
139
|
|
|
137
|
-
The callback commits when it returns and rolls back when it throws
|
|
140
|
+
The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A transaction holds its connection: a statement from outside its callback waits for it. A nested `transaction()` is a savepoint, whose failure undoes its own writes alone; MongoDB refuses it. For a transaction that opens in one place and ends in another, use `beginTransaction`, `commitTransaction` and `rollbackTransaction`. `{ readOnly: true }` opens a read-only transaction: Postgres, CockroachDB, MySQL and MariaDB refuse its writes, and libSQL and Turso skip the write lock they take at `BEGIN`. `querier.onCommit(fn)` runs `fn` after the outermost commit and never on rollback: use it for mail and queued jobs. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
|
|
138
141
|
|
|
139
|
-
A `findManyStream` holds its querier until the loop ends,
|
|
142
|
+
A `findManyStream` holds its querier until the loop ends, and other statements on it are refused 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: split a long `$in`.
|
|
140
143
|
|
|
141
144
|
## Migrations
|
|
142
145
|
|
|
143
146
|
`npx uql-migrate` reads `uql.config.ts` (`bun --bun uql-migrate` on Bun):
|
|
144
147
|
|
|
145
|
-
- `sync
|
|
146
|
-
- `generate:entities
|
|
147
|
-
- `up` and `down
|
|
148
|
-
- `generate:from-db
|
|
149
|
-
- `drift:check
|
|
150
|
-
- `sync --dry-run
|
|
148
|
+
- `sync`: applies what the entities imply. Development only.
|
|
149
|
+
- `generate:entities`: writes the diff as a migration file to review. A renamed column is a drop and an add, unless a naming strategy maps it (`firstName` to `first_name`), or you write `renameColumn(table, from, to)`. It refuses a required column with no default on a table that holds rows.
|
|
150
|
+
- `up` and `down`: each migration runs in its own transaction, under a lock so concurrent instances run it once. From code, `await new Migrator(pool, { migrationsPath }).up()` before the app starts. It rejects with the first failing migration's error; the ones before it stay applied. `down()` reverts the last one, and `down({ step: Infinity })` reverts every one.
|
|
151
|
+
- `generate:from-db`: writes entity classes from an existing database.
|
|
152
|
+
- `drift:check`: fails when the database no longer matches. Index expressions and stored computed expressions are not compared, so change those by hand in the migration.
|
|
153
|
+
- `sync --dry-run`: prints only SQL on stdout, for a migration file another tool applies, such as wrangler on Cloudflare D1 (https://uql-orm.dev/cloudflare-d1.md).
|
|
151
154
|
|
|
152
|
-
|
|
155
|
+
In a migration, ``querier.run /*sql*/ `CREATE TABLE ...` `` marks the SQL: the comment is what es6-string-html highlights.
|
|
156
|
+
|
|
157
|
+
Checks, enums and triggers are part of the diff. uql owns the `_uql_`-prefixed checks and triggers and never touches another. On MongoDB, checks and enums are the collection's validator, which uql owns whole: a check fails a document that lacks the field it compares.
|
|
153
158
|
|
|
154
159
|
## Where to read more
|
|
155
160
|
|
|
156
|
-
- Operators
|
|
161
|
+
- Operators and per-dialect SQL: https://uql-orm.dev/querying/comparison-operators.md
|
|
157
162
|
- Relations and deep `$populate`: https://uql-orm.dev/querying/relations.md
|
|
158
163
|
- Computed fields and stamps: https://uql-orm.dev/entities/computed-fields.md
|
|
159
164
|
- Triggers: https://uql-orm.dev/entities/triggers.md
|
|
160
|
-
-
|
|
161
|
-
-
|
|
165
|
+
- Coming from Prisma, Drizzle, TypeORM, MikroORM or Mongoose: https://uql-orm.dev/switching-to-uql.md
|
|
166
|
+
- Moving data off MongoDB: https://uql-orm.dev/mongodb.md#moving-to-sql
|
|
162
167
|
- Breaking changes by version: https://uql-orm.dev/upgrade-guide.md
|