uql-orm 0.102.4 → 0.102.5

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.
@@ -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
- * Every clause that names such a field needs the expression itself, never the output alias: an
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
- if (isInlinedExpression(field)) {
280
- // Qualified even when nothing else in this statement is: the expression is spliced in, and one
281
- // that opens a correlated subquery has the inner table's columns in scope, so a bare `"id"`
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 (this.inlinedOperand(ctx, field, opts.prefix ?? this.resolveTableAlias(meta), entity) ??
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
- * Every clause that names such a field needs the expression itself, never the output alias: an
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, field, prefix, entity) {
649
- const inlined = field && isInlinedExpression(field) ? field.computed : undefined;
650
- return inlined ? this.rawFragment(ctx, inlined, prefix, entity) : undefined;
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, field, prefix ?? this.resolveTableAlias(meta), meta.entity) ??
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 field = getMeta(entity).fields[key];
1138
- return {
1139
- sql: this.resolveOperandField(ctx, entity, key, { prefix }),
1140
- bare: field === undefined || !isInlinedExpression(field),
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
@@ -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 one no entity names with the
75
- * same columns, which may be the table renamed. That one is never renamed here: it may be another's.
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
  /**
@@ -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, reverseDiff, sides, withoutRebuild } from './schemaChange.js';
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(reverseDiff(diff))),
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 one no entity names with the
204
- * same columns, which may be the table renamed. That one is never renamed here: it may be another's.
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 { tableName, columns = [] } of altered) {
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 = Boolean(rebuild || diff.renamedColumns?.length || sides(columns, 'from').length);
158
- const triggers = (diff.triggers ?? []).filter(({ from, to }) => moved || !from || !to);
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
+ }
@@ -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 the diff reversed, see `reverseDiff`. */
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
@@ -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
- scope.ctx.append('(');
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.4",
6
+ "version": "0.102.5",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"