uql-orm 0.91.0 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/browser/http/bus.js +3 -4
  2. package/dist/browser/http/http.d.ts +1 -2
  3. package/dist/browser/http/http.js +8 -7
  4. package/dist/browser/index.d.ts +0 -1
  5. package/dist/browser/index.js +0 -1
  6. package/dist/browser/querier/httpQuerier.d.ts +18 -20
  7. package/dist/browser/querier/httpQuerier.js +20 -56
  8. package/dist/browser/type/index.d.ts +0 -1
  9. package/dist/browser/type/index.js +0 -1
  10. package/dist/browser/uql-browser.min.js +2 -2
  11. package/dist/browser/uql-browser.min.js.map +11 -12
  12. package/dist/cockroachdb/cockroachDialect.d.ts +4 -1
  13. package/dist/cockroachdb/cockroachDialect.js +5 -1
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +24 -28
  17. package/dist/dialect/abstractSqlDialect.js +47 -45
  18. package/dist/dialect/aliases.d.ts +4 -1
  19. package/dist/dialect/aliases.js +5 -2
  20. package/dist/dialect/hydrateColumn.js +3 -10
  21. package/dist/dialect/jsonSql.d.ts +4 -1
  22. package/dist/dialect/jsonSql.js +4 -1
  23. package/dist/dialect/mergeSqlDialect.d.ts +4 -3
  24. package/dist/dialect/mergeSqlDialect.js +5 -4
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -21
  26. package/dist/dialect/mysqlLikeSqlDialect.js +9 -36
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +3 -7
  28. package/dist/dialect/pgLikeSqlDialect.js +11 -21
  29. package/dist/http/contract.d.ts +4 -0
  30. package/dist/http/contract.js +1 -0
  31. package/dist/http/handler.d.ts +2 -2
  32. package/dist/http/handler.js +17 -19
  33. package/dist/http/query.d.ts +5 -3
  34. package/dist/http/query.js +42 -42
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/maria/mariaDialect.d.ts +2 -3
  38. package/dist/maria/mariaDialect.js +1 -5
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/expressions.d.ts +12 -18
  42. package/dist/migrate/builder/expressions.js +39 -42
  43. package/dist/migrate/builder/migrationBuilder.d.ts +3 -11
  44. package/dist/migrate/builder/migrationBuilder.js +41 -81
  45. package/dist/migrate/builder/tableBuilder.d.ts +0 -7
  46. package/dist/migrate/builder/tableBuilder.js +17 -28
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +7 -13
  49. package/dist/migrate/codegen/entityTypes.js +6 -20
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +27 -12
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/index.d.ts +2 -4
  54. package/dist/migrate/ddl/index.js +14 -5
  55. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  56. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  57. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  58. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  59. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  60. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  61. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  62. package/dist/migrate/ddl/tableDdl.js +31 -32
  63. package/dist/migrate/drift/driftDetector.js +46 -59
  64. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  65. package/dist/migrate/generator/definitionToNode.js +27 -34
  66. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  67. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  68. package/dist/migrate/index.js +1 -1
  69. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  70. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +10 -0
  71. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  72. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  73. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  74. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  75. package/dist/migrate/introspection/mysqlIntrospector.js +25 -11
  76. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  77. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  78. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  79. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  80. package/dist/migrate/migrationTarget.js +3 -3
  81. package/dist/migrate/schemaGenerator.d.ts +8 -12
  82. package/dist/migrate/schemaGenerator.js +35 -61
  83. package/dist/migrate/triggerSql.d.ts +1 -1
  84. package/dist/migrate/triggerSql.js +8 -6
  85. package/dist/mongo/mongoDialect.d.ts +4 -3
  86. package/dist/mongo/mongoDialect.js +52 -38
  87. package/dist/mongo/mongoIntrospector.js +1 -1
  88. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  89. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  90. package/dist/mongo/mongodbQuerier.d.ts +2 -3
  91. package/dist/mongo/mongodbQuerier.js +9 -28
  92. package/dist/mssql/mssqlDialect.d.ts +4 -5
  93. package/dist/mssql/mssqlDialect.js +9 -7
  94. package/dist/postgres/postgresDialect.js +2 -2
  95. package/dist/querier/abstractQuerier.d.ts +16 -11
  96. package/dist/querier/abstractQuerier.js +74 -26
  97. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  98. package/dist/querier/abstractQuerierPool.js +26 -64
  99. package/dist/querier/abstractSqlQuerier.d.ts +2 -3
  100. package/dist/querier/abstractSqlQuerier.js +8 -26
  101. package/dist/querier/cursor.d.ts +10 -0
  102. package/dist/querier/cursor.js +81 -0
  103. package/dist/querier/keyset.d.ts +19 -0
  104. package/dist/querier/keyset.js +198 -0
  105. package/dist/schema/canonicalType.d.ts +3 -3
  106. package/dist/schema/canonicalType.js +13 -12
  107. package/dist/schema/indexDifferences.d.ts +14 -7
  108. package/dist/schema/indexDifferences.js +7 -5
  109. package/dist/schema/schemaAST.d.ts +0 -1
  110. package/dist/schema/schemaAST.js +0 -2
  111. package/dist/schema/schemaASTBuilder.js +28 -20
  112. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  113. package/dist/schema/schemaASTDiffer.js +54 -107
  114. package/dist/schema/sqlExpression.d.ts +22 -0
  115. package/dist/schema/sqlExpression.js +28 -0
  116. package/dist/schema/types.d.ts +48 -105
  117. package/dist/sqlite/sqliteDialect.d.ts +9 -13
  118. package/dist/sqlite/sqliteDialect.js +10 -29
  119. package/dist/type/dialect.d.ts +20 -3
  120. package/dist/type/entity.d.ts +7 -20
  121. package/dist/type/migration.d.ts +7 -7
  122. package/dist/type/querier.d.ts +19 -26
  123. package/dist/type/query.d.ts +104 -24
  124. package/dist/type/query.js +21 -28
  125. package/dist/type/universalQuerier.d.ts +31 -5
  126. package/dist/type/utility.d.ts +10 -0
  127. package/dist/util/bytes.d.ts +7 -0
  128. package/dist/util/bytes.js +22 -0
  129. package/dist/util/date.d.ts +5 -0
  130. package/dist/util/date.js +5 -0
  131. package/dist/util/dialect.util.d.ts +1 -25
  132. package/dist/util/dialect.util.js +4 -50
  133. package/dist/util/field.util.d.ts +9 -0
  134. package/dist/util/field.util.js +15 -0
  135. package/dist/util/fieldOption.util.js +2 -2
  136. package/dist/util/index.d.ts +1 -0
  137. package/dist/util/index.js +1 -0
  138. package/dist/util/object.util.d.ts +0 -2
  139. package/dist/util/object.util.js +0 -7
  140. package/dist/util/query.util.d.ts +40 -0
  141. package/dist/util/query.util.js +76 -0
  142. package/dist/util/raw.d.ts +5 -0
  143. package/dist/util/raw.js +5 -0
  144. package/dist/util/relationQuery.util.js +18 -16
  145. package/dist/util/rowKey.util.js +2 -3
  146. package/dist/util/sql.util.d.ts +8 -2
  147. package/dist/util/sql.util.js +16 -17
  148. package/dist/util/sqlLiteral.js +2 -12
  149. package/dist/util/string.util.d.ts +5 -0
  150. package/dist/util/string.util.js +12 -0
  151. package/package.json +1 -1
  152. package/skills/uql-orm/SKILL.md +22 -11
  153. package/dist/browser/options.d.ts +0 -4
  154. package/dist/browser/options.js +0 -13
  155. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  156. package/dist/browser/type/clientQuerierPool.js +0 -1
@@ -1,20 +1,19 @@
1
1
  import { getMeta } from '../entity/index.js';
2
- import { utcTimestamp } from '../util/date.js';
3
2
  import { textSearchFields } from '../util/index.js';
4
3
  import { escapeMysqlSqlLiteral, escapeSingleQuotes } from '../util/sqlLiteral.js';
5
4
  import { AbstractSqlDialect, } from './abstractSqlDialect.js';
6
5
  import { AGGREGATE_VALUE_ALIAS } from './aliases.js';
7
6
  import { BYTES_PREFIX } from './hydrateColumn.js';
8
- import { jsonSetCall, jsonPath, jsonRemoveCall, jsonSetTarget } from './jsonSql.js';
7
+ import { jsonPath } from './jsonSql.js';
9
8
  import { aggregatesRelations } from './queryJoins.js';
10
9
  /**
11
10
  * The largest `BIGINT UNSIGNED`: the row count MySQL's manual gives for "all rows from the offset on",
12
11
  * and the largest `group_concat_max_len` either engine takes.
13
12
  */
14
13
  const MAX_LIMIT = BigInt.asUintN(64, -1n);
15
- /** What the MySQL-family engines have. */
16
14
  /** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
17
15
  export const MYSQL_ROW_LOCKS = { of: true, withWindow: true, placement: 'suffix' };
16
+ /** The features of MySQL, which MariaDB starts from. */
18
17
  export const MYSQL_FEATURES = {
19
18
  indexIfNotExists: false,
20
19
  schemas: true,
@@ -30,6 +29,7 @@ export const MYSQL_FEATURES = {
30
29
  serverSideCursors: false,
31
30
  correlatedWrites: true,
32
31
  rowLocks: MYSQL_ROW_LOCKS,
32
+ nullsSortLowest: true,
33
33
  nullsOrdering: 'expression',
34
34
  textScoreIndexes: true,
35
35
  orderedUpsertReturning: true,
@@ -38,7 +38,6 @@ export const MYSQL_FEATURES = {
38
38
  vectorTuningNeedsTransaction: false,
39
39
  serialDeclaresPrimaryKey: false,
40
40
  triggers: {
41
- preamble: '',
42
41
  assignsRow: true,
43
42
  body: 'inline',
44
43
  fires: 'eachRowIf',
@@ -74,26 +73,15 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
74
73
  ctx.append(' AND TABLE_NAME = ');
75
74
  ctx.addValue(this.resolveTableAlias(meta));
76
75
  }
77
- /** `OFFSET` is only legal after a `LIMIT` here, so a bare `$skip` needs one. */
78
- pager(ctx, opts) {
79
- if (opts.$limit === undefined && opts.$skip !== undefined) {
80
- ctx.append(` LIMIT ${MAX_LIMIT}`);
81
- }
82
- super.pager(ctx, opts);
83
- }
76
+ unboundedLimit = String(MAX_LIMIT);
84
77
  /** A signed key, so a foreign key taking its type from it matches, as MySQL refuses an `UNSIGNED` mismatch. */
85
78
  autoIncrementSuffix = 'AUTO_INCREMENT';
86
79
  escapeIdChar = '`';
87
- tableOptions = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
88
80
  beginTransactionCommand = 'START TRANSACTION';
89
- commitTransactionCommand = 'COMMIT';
90
- rollbackTransactionCommand = 'ROLLBACK';
91
81
  isolationLevelStrategy = 'set-before';
92
- dropForeignKeySyntax = 'DROP FOREIGN KEY';
93
- dropPrimaryKeySyntax = 'DROP PRIMARY KEY';
94
- dropIndexSyntax = 'on-table';
95
- alterColumnSyntax = 'MODIFY COLUMN';
96
82
  booleanLiteral = 'integer';
83
+ /** `(3)` keeps milliseconds; a bare `CURRENT_TIMESTAMP` has whole seconds only. */
84
+ currentTimestamp = 'CURRENT_TIMESTAMP(3)';
97
85
  // No `RETURNING` support, so multi-row insert IDs are inferred from the header - see the
98
86
  // `innodb_autoinc_lock_mode` caveat on `buildUpdateResult` in `util/sql.util.ts`.
99
87
  insertIdSource = 'firstId';
@@ -106,7 +94,8 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
106
94
  const alias = this.upsertNewRowAlias && this.escapeId(this.upsertNewRowAlias, true);
107
95
  const updateCtx = this.createContext();
108
96
  const update = this.getUpsertUpdateAssignments(updateCtx, meta, conflictPaths, payload, (name) => alias ? `${alias}.${name}` : `VALUE(${name})`);
109
- const returning = this.upsertReturning(meta);
97
+ const idReturning = this.insertedIdReturning(meta);
98
+ const returning = idReturning && ` ${idReturning}`;
110
99
  if (update) {
111
100
  this.appendInsertValues(ctx, entity, payload);
112
101
  ctx.append(`${alias ? ` AS ${alias}` : ''} ON DUPLICATE KEY UPDATE ${update}${returning}`);
@@ -119,10 +108,6 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
119
108
  ctx.append(returning);
120
109
  ctx.pushValue(...insertCtx.values);
121
110
  }
122
- /** Appended to both branches above: empty on MySQL, which has no `INSERT ... RETURNING`. */
123
- upsertReturning(_meta) {
124
- return '';
125
- }
126
111
  /**
127
112
  * The alias the inserted row is given after the values list, and read back by the assignments.
128
113
  * Undefined where the dialect has no such syntax - MariaDB, which reads that row through
@@ -186,9 +171,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
186
171
  return escapeMysqlSqlLiteral(value);
187
172
  }
188
173
  /** A date as UTC text, which a `DATETIME` stores as is, where a driver would convert it to its own zone. */
189
- normalizeValue(value) {
190
- return value instanceof Date ? utcTimestamp(value) : super.normalizeValue(value);
191
- }
174
+ dateZone = '';
192
175
  /**
193
176
  * `MATCH(cols) AGAINST(?)`, which needs a `FULLTEXT` index over exactly those columns: without one
194
177
  * the server answers "Can't find FULLTEXT index matching the column list". Declare it with
@@ -214,13 +197,6 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
214
197
  // MySQL/MariaDB null-safe inequality: true when values differ or one side is NULL.
215
198
  return `NOT (${field} <=> ${ph})`;
216
199
  }
217
- /**
218
- * Omitting the `COALESCE` on a NOT NULL column keeps MySQL's partial in-place JSON update
219
- * applicable: it requires the target column as the direct `JSON_SET` input.
220
- */
221
- jsonSet(ctx, expr, set, field) {
222
- return jsonSetCall((value) => this.jsonScalarParam(ctx, value), jsonSetTarget(expr, field, `'{}'`), set, this.maxFunctionArgs);
223
- }
224
200
  /**
225
201
  * `JSON_MERGE_PRESERVE` concatenates arrays and creates absent keys, so every pushed key is
226
202
  * handled in one call that references `expr` once - unlike `JSON_ARRAY_APPEND`, which needs a
@@ -241,9 +217,6 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
241
217
  jsonContains(ctx, slot, values) {
242
218
  return `JSON_CONTAINS(${this.jsonValue(slot)}, ${this.addValue(ctx, JSON.stringify(values))})`;
243
219
  }
244
- jsonUnset(_ctx, expr, unset) {
245
- return jsonRemoveCall(expr, unset, this.maxFunctionArgs);
246
- }
247
220
  /** Only an array's, where `JSON_LENGTH` counts a scalar as 1 and an object by its keys. */
248
221
  jsonLength(slot) {
249
222
  return `CASE WHEN ${this.jsonIsArray(slot)} THEN JSON_LENGTH(${this.jsonValue(slot)}) END`;
@@ -22,11 +22,6 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
22
22
  readonly features: SqlDialectFeatures;
23
23
  readonly escapeIdChar = "\"";
24
24
  readonly autoIncrementSuffix: string;
25
- readonly tableOptions = "";
26
- readonly beginTransactionCommand = "BEGIN";
27
- readonly commitTransactionCommand = "COMMIT";
28
- readonly rollbackTransactionCommand = "ROLLBACK";
29
- readonly alterColumnStrategy = "separate-clauses";
30
25
  /**
31
26
  * `JSON_AGG` of each row whole, read through a LATERAL projection of the columns it answers under:
32
27
  * the sort terms carried out beside them order it without joining the object, and no function call
@@ -45,7 +40,6 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
45
40
  };
46
41
  /** `$N` placeholders carry their own index, so the upsert's assignments need no scratch context. */
47
42
  protected readonly upsertUpdateBindsInPlace = true;
48
- readonly insertIdSource = "returning";
49
43
  readonly maxBindValues: number;
50
44
  readonly vectorMetrics: ReadonlyMap<VectorDistance, VectorMetric>;
51
45
  /**
@@ -59,6 +53,8 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
59
53
  * by distance, which would otherwise drop rows the candidate list missed.
60
54
  */
61
55
  vectorTuningStatements<E>(meta: EntityMeta<E>, q: Query<E>): readonly string[];
56
+ /** Binds a date as UTC text, which a zoneless `TIMESTAMP` stores as is, instead of each driver picking a zone. */
57
+ protected readonly dateZone = "+00";
62
58
  normalizeValue(value: unknown): unknown;
63
59
  placeholder(index: number): string;
64
60
  /**
@@ -97,7 +93,7 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
97
93
  protected jsonPathReading(escapedColumn: string, path: string, mode: 'json' | 'text'): string;
98
94
  /** A number only where the value is one: the cast throws on any other text, failing the whole read. */
99
95
  jsonPathExpr(escapedColumn: string, path: string, mode: JsonAccessMode): string;
100
- protected get regexpOp(): string;
96
+ protected regexCondition(operand: string, placeholder: string): string;
101
97
  protected readonly caseInsensitiveMatch = "ilike";
102
98
  neExpr(field: string, ph: string): string;
103
99
  /**
@@ -1,5 +1,5 @@
1
1
  import { QueryRaw, } from '../type/index.js';
2
- import { utcTimestamp } from '../util/date.js';
2
+ import { bytesToHex } from '../util/bytes.js';
3
3
  import { fulltextConfig, fulltextIndexOver, hasVectorNear, textSearchFields } from '../util/dialect.util.js';
4
4
  import { escapePgSqlLiteral, escapeSingleQuotes, PG_UTC } from '../util/sqlLiteral.js';
5
5
  import { AbstractSqlDialect } from './abstractSqlDialect.js';
@@ -32,6 +32,7 @@ export const PG_FEATURES = {
32
32
  serverSideCursors: true,
33
33
  correlatedWrites: true,
34
34
  rowLocks: { of: true, withWindow: false, placement: 'suffix' },
35
+ nullsSortLowest: false,
35
36
  nullsOrdering: 'clause',
36
37
  textScoreIndexes: false,
37
38
  orderedUpsertReturning: true,
@@ -40,7 +41,6 @@ export const PG_FEATURES = {
40
41
  vectorTuningNeedsTransaction: true,
41
42
  serialDeclaresPrimaryKey: false,
42
43
  triggers: {
43
- preamble: '',
44
44
  assignsRow: true,
45
45
  body: 'function',
46
46
  fires: 'eachRowWhen',
@@ -68,11 +68,6 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
68
68
  // `SERIAL` (CockroachDB's `unique_rowid()`, a ~64-bit value that overflows JS's safe-integer
69
69
  // range). High-throughput CockroachDB users should override this per-entity with a UUID PK.
70
70
  autoIncrementSuffix = 'GENERATED BY DEFAULT AS IDENTITY';
71
- tableOptions = '';
72
- beginTransactionCommand = 'BEGIN';
73
- commitTransactionCommand = 'COMMIT';
74
- rollbackTransactionCommand = 'ROLLBACK';
75
- alterColumnStrategy = 'separate-clauses';
76
71
  /**
77
72
  * `JSON_AGG` of each row whole, read through a LATERAL projection of the columns it answers under:
78
73
  * the sort terms carried out beside them order it without joining the object, and no function call
@@ -97,7 +92,6 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
97
92
  };
98
93
  /** `$N` placeholders carry their own index, so the upsert's assignments need no scratch context. */
99
94
  upsertUpdateBindsInPlace = true;
100
- insertIdSource = 'returning';
101
95
  maxBindValues = 65535;
102
96
  vectorMetrics = PG_VECTOR_METRICS;
103
97
  /**
@@ -125,12 +119,14 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
125
119
  }
126
120
  return statements;
127
121
  }
122
+ /** Binds a date as UTC text, which a zoneless `TIMESTAMP` stores as is, instead of each driver picking a zone. */
123
+ dateZone = PG_UTC;
128
124
  normalizeValue(value) {
129
125
  if (Array.isArray(value)) {
130
- const values = value.map(utcDate);
126
+ const values = value.map((item) => super.normalizeValue(item));
131
127
  return this.driverCapabilities.nativeArrays ? values : toPgArray(values);
132
128
  }
133
- return super.normalizeValue(utcDate(value));
129
+ return super.normalizeValue(value);
134
130
  }
135
131
  placeholder(index) {
136
132
  return `$${index}`;
@@ -221,8 +217,8 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
221
217
  }
222
218
  return `CASE WHEN JSONB_TYPEOF(${this.jsonValue({ base: escapedColumn, path })}) = 'number' THEN ${read} END`;
223
219
  }
224
- get regexpOp() {
225
- return '~';
220
+ regexCondition(operand, placeholder) {
221
+ return `${operand} ~ ${placeholder}`;
226
222
  }
227
223
  caseInsensitiveMatch = 'ilike';
228
224
  neExpr(field, ph) {
@@ -308,10 +304,6 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
308
304
  return this.driverCapabilities.explicitJsonCast ? `(${ph}::text)::${type}` : `${ph}::${type}`;
309
305
  }
310
306
  }
311
- /** A date as UTC text, which a zoneless `TIMESTAMP` stores as is, where each driver would pick its own zone. */
312
- function utcDate(value) {
313
- return value instanceof Date ? utcTimestamp(value, PG_UTC) : value;
314
- }
315
307
  /**
316
308
  * Converts a JS array to a Postgres array literal string: `{"val1","val2"}`.
317
309
  * Safely handles nesting and escaping of special characters.
@@ -324,11 +316,9 @@ function toPgArray(arr) {
324
316
  return toPgArray(val);
325
317
  if (typeof val === 'boolean')
326
318
  return val ? 'true' : 'false';
327
- if (val instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(val))) {
328
- const hex = Array.from(val)
329
- .map((b) => b.toString(16).padStart(2, '0'))
330
- .join('');
331
- return `"\\\\x${hex}"`;
319
+ // A Node `Buffer` is a `Uint8Array` too.
320
+ if (val instanceof Uint8Array) {
321
+ return `"\\\\x${bytesToHex(val)}"`;
332
322
  }
333
323
  const str = String(val);
334
324
  const escaped = str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
@@ -9,6 +9,10 @@ export declare const CRUD_ROUTES: {
9
9
  readonly method: 'GET';
10
10
  readonly path: '';
11
11
  };
12
+ readonly findManyPage: {
13
+ readonly method: 'GET';
14
+ readonly path: '/page';
15
+ };
12
16
  readonly findOne: {
13
17
  readonly method: 'GET';
14
18
  readonly path: '/one';
@@ -9,6 +9,7 @@ import { kebabCase } from '../util/string.util.js';
9
9
  */
10
10
  export const CRUD_ROUTES = {
11
11
  findMany: { method: 'GET', path: '' },
12
+ findManyPage: { method: 'GET', path: '/page' },
12
13
  findOne: { method: 'GET', path: '/one' },
13
14
  count: { method: 'GET', path: '/count' },
14
15
  findOneById: { method: 'GET', path: '/:id' },
@@ -1,6 +1,6 @@
1
1
  import type { EntityMeta, QuerierPool, Query, RequestSuccessResponse, Type, UqlContext } from '../type/index.js';
2
2
  import { type CrudOperation, type HttpMethod } from './contract.js';
3
- import { type WireFlags } from './query.js';
3
+ import { type WireCursors, type WireFlags } from './query.js';
4
4
  /**
5
5
  * Framework-normalized request: adapters (express, fetch, ...) reduce their native
6
6
  * request to this shape and get back a status + JSON body.
@@ -31,7 +31,7 @@ export type HookContext<E extends object, Ctx = unknown> = {
31
31
  readonly op: CrudOperation;
32
32
  readonly method: HttpMethod;
33
33
  /** The parsed query, to reshape in place. Scope rows with a `security` filter instead, which a client cannot override. */
34
- query: Query<E> & WireFlags;
34
+ query: Query<E> & WireFlags & WireCursors;
35
35
  /**
36
36
  * request payload - reassignable for sanitization or field injection.
37
37
  */
@@ -1,6 +1,6 @@
1
1
  import { withContext } from '../context/context.js';
2
2
  import { getMeta, soleIdOf } from '../entity/index.js';
3
- import { whereIds, whereWith } from '../util/dialect.util.js';
3
+ import { whereWith } from '../util/query.util.js';
4
4
  import { UqlUsageError } from '../util/uqlError.js';
5
5
  import { CRUD_ROUTES, entityPath, matchRoute, } from './contract.js';
6
6
  import { parseQueryParams } from './query.js';
@@ -77,12 +77,20 @@ export function createRequestHandler(opts) {
77
77
  return { data: count, count };
78
78
  }
79
79
  case 'findMany': {
80
- const [data, count] = await Promise.all([
81
- querier.findMany(entity, query),
82
- counts ? querier.count(entity, query) : undefined,
83
- ]);
80
+ if (!counts) {
81
+ return { data: await querier.findMany(entity, query) };
82
+ }
83
+ // `findManyAndCount` counts every matching row, whereas `count` would count only the page `$limit` takes.
84
+ const [data, count] = await querier.findManyAndCount(entity, query);
84
85
  return { data, count };
85
86
  }
87
+ case 'findManyPage': {
88
+ const { $limit } = query;
89
+ if ($limit === undefined) {
90
+ throw new UqlUsageError('a page names how many rows it holds in $limit');
91
+ }
92
+ return { data: await querier.findManyPage(entity, { ...query, $limit }) };
93
+ }
86
94
  case 'insertOne':
87
95
  return { data: await querier.insertOne(entity, body), count: 1 };
88
96
  case 'saveOne':
@@ -95,26 +103,16 @@ export function createRequestHandler(opts) {
95
103
  const data = await querier.saveMany(entity, body);
96
104
  return { data, count: data.length };
97
105
  }
106
+ // A write returns how many rows it changed, and the querier still refuses a delete that names no rows.
98
107
  case 'updateMany':
99
108
  case 'updateOneById': {
100
109
  const count = await querier.updateMany(entity, scoped, body);
101
- return { data: id ?? count, count };
110
+ return { data: count, count };
102
111
  }
112
+ case 'deleteMany':
103
113
  case 'deleteOneById': {
104
114
  const count = await querier.deleteMany(entity, scoped, { hardDelete });
105
- return { data: id, count };
106
- }
107
- case 'deleteMany': {
108
- const founds = await querier.findMany(entity, query);
109
- if (!founds.length) {
110
- return { data: [], count: 0 };
111
- }
112
- const idKey = soleIdOf(meta, 'the HTTP handler');
113
- const ids = founds.map((found) => found[idKey]);
114
- return {
115
- data: ids,
116
- count: await querier.deleteMany(entity, { $where: whereIds(meta, ids) }, { hardDelete }),
117
- };
115
+ return { data: count, count };
118
116
  }
119
117
  }
120
118
  }
@@ -1,15 +1,17 @@
1
- import type { WireQuery } from '../type/index.js';
1
+ import type { QueryKeyset, WireQuery } from '../type/index.js';
2
2
  /** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */
3
3
  declare const WIRE_FLAGS: ["hardDelete", "count"];
4
4
  /** {@link WIRE_FLAGS} as the booleans {@link parseQueryParams} decodes them to, where a hook may also set them. */
5
5
  export type WireFlags = {
6
6
  readonly [K in (typeof WIRE_FLAGS)[number]]?: boolean;
7
7
  };
8
+ /** The cursors a page request carries; only `findManyPage` reads them. */
9
+ export type WireCursors = Pick<QueryKeyset<unknown>, '$after' | '$before'>;
8
10
  /**
9
11
  * Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query
10
- * object. Symmetric counterpart of {@link stringifyQuery}. Only {@link ALLOWED_QUERY_KEYS} are honored.
12
+ * object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.
11
13
  */
12
- export declare function parseQueryParams<E = unknown>(params?: unknown): WireQuery<E> & WireFlags;
14
+ export declare function parseQueryParams<E = unknown>(params?: unknown): WireQuery<E> & WireFlags & WireCursors;
13
15
  /**
14
16
  * Serialize a UQL query object into a percent-encoded query string where object values
15
17
  * are JSON-stringified. Symmetric counterpart of {@link parseQueryParams}.
@@ -1,5 +1,5 @@
1
- // the clause lists themselves, not the barrel: this module is in the browser bundle's graph
2
- import { QUERY_BOOLEAN_CLAUSES, QUERY_NUMBER_CLAUSES, QUERY_OBJECT_CLAUSES, QUERY_ROOT_NUMBER_CLAUSES, QUERY_ROOT_OBJECT_CLAUSES, } from '../type/query.js';
1
+ // the clause table itself, not the barrel: this module is in the browser bundle's graph
2
+ import { QUERY_CLAUSES } from '../type/query.js';
3
3
  // the brand alone, not the class: importing `QueryRaw` for an `instanceof` kept it, and `ColumnRef`
4
4
  // with it, in the browser bundle, which is on a size budget
5
5
  import { RAW_VALUE } from '../type/queryRaw.js';
@@ -9,20 +9,6 @@ import { getKeys, isRecord, isWhereMap } from '../util/object.util.js';
9
9
  import { UqlUsageError } from '../util/uqlError.js';
10
10
  /** The flags a request carries beside its query: `hardDelete` on a delete, `count` on a `findMany`. */
11
11
  const WIRE_FLAGS = ['hardDelete', 'count'];
12
- /**
13
- * Keys accepted from the wire - query structure ({@link Query}) plus the {@link WIRE_FLAGS}. Anything else
14
- * (e.g. `filters`, `context`, `$entity`) is dropped so a remote client can't bypass a security filter or
15
- * inject ambient context - those are server-only. The `satisfies` ties
16
- * every entry to a real query/option key, so a typo or a renamed option fails to compile.
17
- */
18
- const ALLOWED_QUERY_KEYS = new Set([
19
- ...QUERY_OBJECT_CLAUSES,
20
- ...QUERY_ROOT_OBJECT_CLAUSES,
21
- ...QUERY_NUMBER_CLAUSES,
22
- ...QUERY_ROOT_NUMBER_CLAUSES,
23
- ...QUERY_BOOLEAN_CLAUSES,
24
- ...WIRE_FLAGS,
25
- ]);
26
12
  /**
27
13
  * Keys that mean something locally but that this transport can never honor, so they are rejected
28
14
  * rather than dropped like the rest. Each request runs on its own auto-committing connection, so a
@@ -30,9 +16,18 @@ const ALLOWED_QUERY_KEYS = new Set([
30
16
  * and ignoring it would hand the caller a read they believe is serialized and is not.
31
17
  */
32
18
  const REJECTED_QUERY_KEYS = new Set(['$lock']);
19
+ /**
20
+ * The keys accepted from the wire, mapped to how each value is decoded: every query clause ({@link QUERY_CLAUSES})
21
+ * plus the {@link WIRE_FLAGS}. Anything else (e.g. `filters`, `context`, `$entity`) is dropped, so a remote
22
+ * client can't bypass a security filter or inject ambient context.
23
+ */
24
+ const WIRE_VALUES = new Map([
25
+ ...getKeys(QUERY_CLAUSES).map((key) => [key, QUERY_CLAUSES[key].value]),
26
+ ...WIRE_FLAGS.map((flag) => [flag, 'boolean']),
27
+ ]);
33
28
  /**
34
29
  * Parse raw query-string entries (with JSON-stringified values), or a `QUERY` body, into a UQL query
35
- * object. Symmetric counterpart of {@link stringifyQuery}. Only {@link ALLOWED_QUERY_KEYS} are honored.
30
+ * object. Symmetric counterpart of {@link stringifyQuery}. Only the keys in {@link WIRE_VALUES} are honored.
36
31
  */
37
32
  export function parseQueryParams(params = {}) {
38
33
  if (!isRecord(params)) {
@@ -43,39 +38,44 @@ export function parseQueryParams(params = {}) {
43
38
  if (REJECTED_QUERY_KEYS.has(key)) {
44
39
  throw new UqlUsageError(`'${key}' is not supported over HTTP`);
45
40
  }
46
- if (ALLOWED_QUERY_KEYS.has(key)) {
47
- query[key] = params[key];
48
- }
49
- }
50
- for (const key of [...QUERY_OBJECT_CLAUSES, ...QUERY_ROOT_OBJECT_CLAUSES]) {
51
- const value = query[key];
52
- if (typeof value === 'string') {
53
- try {
54
- query[key] = JSON.parse(value);
55
- }
56
- catch {
57
- throw new UqlUsageError(`invalid JSON in '${key}'`);
58
- }
41
+ const shape = WIRE_VALUES.get(key);
42
+ if (shape && params[key] !== undefined) {
43
+ query[key] = decodeWireValue(key, shape, params[key]);
59
44
  }
60
45
  }
61
46
  query['$where'] ??= {};
62
47
  if (!isWhereMap(query['$where'])) {
63
48
  throw new UqlUsageError("'$where' must be a JSON object");
64
49
  }
65
- // A query string carries every value as text, so what decodes a clause is the shape its group
66
- // declares. `'false'` is the reason the boolean pass exists rather than the raw value being taken:
67
- // it is a non-empty string, so a `$distinct=false` would otherwise read as asking for one.
68
- for (const key of [...QUERY_NUMBER_CLAUSES, ...QUERY_ROOT_NUMBER_CLAUSES]) {
69
- if (query[key] !== undefined) {
70
- query[key] = Number(query[key]);
71
- }
50
+ return query;
51
+ }
52
+ /**
53
+ * Decodes a value to the type its clause declares. A query string carries every value as text, so a boolean
54
+ * must be decoded: `'false'` is a non-empty string, and taken as is, `$distinct=false` would turn it on.
55
+ */
56
+ function decodeWireValue(key, shape, value) {
57
+ switch (shape) {
58
+ case 'object':
59
+ return typeof value === 'string' ? parseJson(key, value) : value;
60
+ case 'number':
61
+ return Number(value);
62
+ case 'boolean':
63
+ return value === true || value === 'true';
64
+ case 'string':
65
+ // A cursor arrives as the exact text a page handed out, never as JSON, so any other value is not a cursor.
66
+ if (typeof value !== 'string') {
67
+ throw new UqlUsageError(`'${key}' must be a cursor a page handed out`);
68
+ }
69
+ return value;
72
70
  }
73
- for (const key of [...QUERY_BOOLEAN_CLAUSES, ...WIRE_FLAGS]) {
74
- if (query[key] !== undefined) {
75
- query[key] = query[key] === true || query[key] === 'true';
76
- }
71
+ }
72
+ function parseJson(key, text) {
73
+ try {
74
+ return JSON.parse(text);
75
+ }
76
+ catch {
77
+ throw new UqlUsageError(`invalid JSON in '${key}'`);
77
78
  }
78
- return query;
79
79
  }
80
80
  /**
81
81
  * Serialize a UQL query object into a percent-encoded query string where object values
package/dist/index.d.ts CHANGED
@@ -7,6 +7,6 @@ export * from './type/index.js';
7
7
  export { withDeleted } from './util/filters.util.js';
8
8
  export type { HookContext } from './util/hook.util.js';
9
9
  export { DefaultLogger } from './util/logger.js';
10
- export { raw, refs } from './util/raw.js';
10
+ export { currentTimestamp, raw, refs } from './util/raw.js';
11
11
  export { deleteFrom, insertInto, updateTable } from './util/triggerWrite.js';
12
12
  export * from './util/uqlError.js';
package/dist/index.js CHANGED
@@ -6,6 +6,6 @@ export * from './querier/index.js';
6
6
  export * from './type/index.js';
7
7
  export { withDeleted } from './util/filters.util.js';
8
8
  export { DefaultLogger } from './util/logger.js';
9
- export { raw, refs } from './util/raw.js';
9
+ export { currentTimestamp, raw, refs } from './util/raw.js';
10
10
  export { deleteFrom, insertInto, updateTable } from './util/triggerWrite.js';
11
11
  export * from './util/uqlError.js';
@@ -1,7 +1,7 @@
1
1
  import { type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode } from '../dialect/jsonSql.js';
3
3
  import { MysqlLikeSqlDialect } from '../dialect/mysqlLikeSqlDialect.js';
4
- import type { EntityMeta, FieldOptions, Query, QueryContext, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
4
+ import type { FieldOptions, Query, QueryContext, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
5
5
  export declare class MariaDialect extends MysqlLikeSqlDialect {
6
6
  readonly dialectName = "mariadb";
7
7
  readonly insertIdSource = "returning";
@@ -16,7 +16,6 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
16
16
  * related table itself, and orders and pages inside `JSON_ARRAYAGG`, which takes both.
17
17
  */
18
18
  protected appendRelationArray(ctx: QueryContext, { entity, query, alias, joins }: RelationRows): void;
19
- protected upsertReturning<E>(meta: EntityMeta<E>): string;
20
19
  /**
21
20
  * `JSON_EXTRACT` for the value and `JSON_VALUE` for its text, which every version has: MySQL's `->`/`->>`
22
21
  * arrive only in 13.1.
@@ -44,7 +43,7 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
44
43
  /** `SET STATEMENT ... FOR`, which scopes a variable to the statement it prefixes. */
45
44
  protected applySettings(sql: string, settings: readonly string[]): string;
46
45
  /**
47
- * The reverse: a `VECTOR` column reads back as its packed bytes in hex, which every driver hands over
46
+ * Reads a `VECTOR` column back as its packed bytes in hex, which every driver hands over
48
47
  * alike, and never through `VEC_ToText`, which keeps six of the nine digits a float32 needs.
49
48
  */
50
49
  protected selectFieldExpr(escapedColumn: string, field: FieldOptions): string;
@@ -37,10 +37,6 @@ export class MariaDialect extends MysqlLikeSqlDialect {
37
37
  const rows = `${query.$distinct ? 'DISTINCT ' : ''}${object}${order}${page}`;
38
38
  ctx.append(`COALESCE((SELECT JSON_ARRAYAGG(${rows}) FROM ${this.tableRef(meta, alias).ref}${from}), JSON_ARRAY())`);
39
39
  }
40
- upsertReturning(meta) {
41
- const returning = this.returningId(meta);
42
- return returning ? ` ${returning}` : '';
43
- }
44
40
  /**
45
41
  * `JSON_EXTRACT` for the value and `JSON_VALUE` for its text, which every version has: MySQL's `->`/`->>`
46
42
  * arrive only in 13.1.
@@ -86,7 +82,7 @@ export class MariaDialect extends MysqlLikeSqlDialect {
86
82
  return `SET STATEMENT ${settings.join(', ')} FOR ${sql}`;
87
83
  }
88
84
  /**
89
- * The reverse: a `VECTOR` column reads back as its packed bytes in hex, which every driver hands over
85
+ * Reads a `VECTOR` column back as its packed bytes in hex, which every driver hands over
90
86
  * alike, and never through `VEC_ToText`, which keeps six of the nine digits a float32 needs.
91
87
  */
92
88
  selectFieldExpr(escapedColumn, field) {
@@ -4,26 +4,16 @@
4
4
  * Fluent API for defining columns in migrations.
5
5
  */
6
6
  import type { EnumValues } from '../../schema/types.js';
7
- import type { CanonicalType, ForeignKeyAction } from '../../schema/types.js';
7
+ import { type CanonicalType, type ForeignKeyAction } from '../../schema/types.js';
8
8
  import type { BaseColumnOptions, FullColumnDefinition, IColumnBuilder, IForeignKeyBuilder } from './types.js';
9
9
  /**
10
- * Builder for column definitions with a fluent API.
11
- * Columns are NOT NULL by default (safer).
10
+ * Builder for column definitions with a fluent API. Each call replaces the definition it holds, and `build`
11
+ * returns it. Columns are NOT NULL by default (safer).
12
12
  */
13
13
  export declare class ColumnBuilder implements IColumnBuilder, IForeignKeyBuilder {
14
- private _name;
15
- private _type;
16
- private _nullable;
17
- private _defaultValue?;
18
- private _primaryKey;
19
- private _autoIncrement;
20
- private _unique;
21
- private _enum?;
22
- private _generatedAs?;
23
- private _comment?;
24
- private _index?;
25
- private _foreignKey?;
14
+ private column;
26
15
  constructor(name: string, type: CanonicalType, options?: BaseColumnOptions);
16
+ private set;
27
17
  /**
28
18
  * Make the column nullable or not nullable.
29
19
  */