uql-orm 0.91.1 → 0.93.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 (165) 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 +6 -2
  14. package/dist/dialect/abstractDialect.d.ts +1 -1
  15. package/dist/dialect/abstractDialect.js +4 -1
  16. package/dist/dialect/abstractSqlDialect.d.ts +68 -37
  17. package/dist/dialect/abstractSqlDialect.js +185 -107
  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 +14 -4
  24. package/dist/dialect/mergeSqlDialect.js +32 -15
  25. package/dist/dialect/mysqlLikeSqlDialect.d.ts +16 -24
  26. package/dist/dialect/mysqlLikeSqlDialect.js +38 -52
  27. package/dist/dialect/pgLikeSqlDialect.d.ts +8 -8
  28. package/dist/dialect/pgLikeSqlDialect.js +19 -22
  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 +2 -2
  36. package/dist/index.js +2 -2
  37. package/dist/maria/mariaDialect.d.ts +4 -3
  38. package/dist/maria/mariaDialect.js +4 -6
  39. package/dist/migrate/builder/columnBuilder.d.ts +5 -15
  40. package/dist/migrate/builder/columnBuilder.js +50 -86
  41. package/dist/migrate/builder/index.d.ts +0 -1
  42. package/dist/migrate/builder/index.js +0 -1
  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 +19 -30
  47. package/dist/migrate/builder/types.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +3 -3
  49. package/dist/migrate/codegen/entityTypes.js +2 -2
  50. package/dist/migrate/codegen/fieldOptionsSource.d.ts +2 -2
  51. package/dist/migrate/codegen/fieldOptionsSource.js +22 -14
  52. package/dist/migrate/codegen/indexDecoratorSource.js +64 -41
  53. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  54. package/dist/migrate/ddl/defaultSql.js +109 -0
  55. package/dist/migrate/ddl/index.d.ts +2 -4
  56. package/dist/migrate/ddl/index.js +14 -5
  57. package/dist/migrate/ddl/mssqlTableDdl.d.ts +1 -0
  58. package/dist/migrate/ddl/mssqlTableDdl.js +4 -1
  59. package/dist/migrate/ddl/mysqlTableDdl.d.ts +17 -0
  60. package/dist/migrate/ddl/mysqlTableDdl.js +33 -0
  61. package/dist/migrate/ddl/pgTableDdl.d.ts +7 -0
  62. package/dist/migrate/ddl/pgTableDdl.js +17 -0
  63. package/dist/migrate/ddl/tableDdl.d.ts +15 -10
  64. package/dist/migrate/ddl/tableDdl.js +31 -32
  65. package/dist/migrate/drift/driftDetector.js +46 -59
  66. package/dist/migrate/generator/definitionToNode.d.ts +11 -7
  67. package/dist/migrate/generator/definitionToNode.js +27 -34
  68. package/dist/migrate/generator/indexNodeToSchema.d.ts +3 -3
  69. package/dist/migrate/generator/indexNodeToSchema.js +5 -4
  70. package/dist/migrate/index.js +1 -1
  71. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +10 -5
  72. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +9 -0
  73. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -1
  74. package/dist/migrate/introspection/baseSqlIntrospector.js +6 -8
  75. package/dist/migrate/introspection/mssqlIntrospector.js +3 -8
  76. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -4
  77. package/dist/migrate/introspection/mysqlIntrospector.js +27 -11
  78. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  79. package/dist/migrate/introspection/postgresIntrospector.js +3 -3
  80. package/dist/migrate/introspection/sqliteIntrospector.d.ts +1 -1
  81. package/dist/migrate/introspection/sqliteIntrospector.js +7 -10
  82. package/dist/migrate/migrationTarget.js +3 -3
  83. package/dist/migrate/schemaGenerator.d.ts +8 -12
  84. package/dist/migrate/schemaGenerator.js +36 -62
  85. package/dist/migrate/storage/databaseStorage.js +2 -2
  86. package/dist/migrate/triggerSql.d.ts +1 -1
  87. package/dist/migrate/triggerSql.js +17 -8
  88. package/dist/mongo/mongoDialect.d.ts +4 -3
  89. package/dist/mongo/mongoDialect.js +52 -38
  90. package/dist/mongo/mongoIntrospector.js +1 -1
  91. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -4
  92. package/dist/mongo/mongoSchemaGenerator.js +18 -21
  93. package/dist/mongo/mongodbQuerier.d.ts +15 -8
  94. package/dist/mongo/mongodbQuerier.js +48 -33
  95. package/dist/mssql/mssqlDialect.d.ts +9 -5
  96. package/dist/mssql/mssqlDialect.js +23 -8
  97. package/dist/postgres/postgresDialect.d.ts +5 -2
  98. package/dist/postgres/postgresDialect.js +6 -6
  99. package/dist/querier/abstractQuerier.d.ts +20 -15
  100. package/dist/querier/abstractQuerier.js +93 -41
  101. package/dist/querier/abstractQuerierPool.d.ts +26 -24
  102. package/dist/querier/abstractQuerierPool.js +26 -64
  103. package/dist/querier/abstractSqlQuerier.d.ts +5 -6
  104. package/dist/querier/abstractSqlQuerier.js +15 -33
  105. package/dist/querier/cursor.d.ts +10 -0
  106. package/dist/querier/cursor.js +81 -0
  107. package/dist/querier/keyset.d.ts +19 -0
  108. package/dist/querier/keyset.js +198 -0
  109. package/dist/schema/canonicalType.d.ts +3 -3
  110. package/dist/schema/canonicalType.js +13 -12
  111. package/dist/schema/indexDifferences.d.ts +14 -7
  112. package/dist/schema/indexDifferences.js +7 -5
  113. package/dist/schema/schemaAST.d.ts +0 -1
  114. package/dist/schema/schemaAST.js +0 -2
  115. package/dist/schema/schemaASTBuilder.js +14 -20
  116. package/dist/schema/schemaASTDiffer.d.ts +7 -9
  117. package/dist/schema/schemaASTDiffer.js +54 -107
  118. package/dist/schema/sqlExpression.d.ts +28 -0
  119. package/dist/schema/sqlExpression.js +42 -0
  120. package/dist/schema/types.d.ts +48 -105
  121. package/dist/sqlite/sqliteDialect.d.ts +10 -13
  122. package/dist/sqlite/sqliteDialect.js +19 -30
  123. package/dist/type/dialect.d.ts +46 -11
  124. package/dist/type/dialect.js +2 -0
  125. package/dist/type/entity.d.ts +18 -3
  126. package/dist/type/migration.d.ts +7 -7
  127. package/dist/type/querier.d.ts +19 -26
  128. package/dist/type/query.d.ts +116 -25
  129. package/dist/type/query.js +21 -28
  130. package/dist/type/universalQuerier.d.ts +33 -7
  131. package/dist/type/utility.d.ts +10 -0
  132. package/dist/util/bytes.d.ts +7 -0
  133. package/dist/util/bytes.js +22 -0
  134. package/dist/util/date.d.ts +5 -0
  135. package/dist/util/date.js +5 -0
  136. package/dist/util/dialect.util.d.ts +1 -25
  137. package/dist/util/dialect.util.js +4 -50
  138. package/dist/util/field.util.d.ts +9 -0
  139. package/dist/util/field.util.js +15 -0
  140. package/dist/util/fieldOption.util.js +2 -2
  141. package/dist/util/index.d.ts +2 -1
  142. package/dist/util/index.js +2 -1
  143. package/dist/util/object.util.d.ts +0 -2
  144. package/dist/util/object.util.js +0 -7
  145. package/dist/util/query.util.d.ts +40 -0
  146. package/dist/util/query.util.js +76 -0
  147. package/dist/util/raw.d.ts +16 -1
  148. package/dist/util/raw.js +31 -0
  149. package/dist/util/relationQuery.util.js +18 -16
  150. package/dist/util/rowKey.util.js +2 -3
  151. package/dist/util/sql.util.d.ts +8 -2
  152. package/dist/util/sql.util.js +16 -17
  153. package/dist/util/sqlLiteral.js +2 -12
  154. package/dist/util/string.util.d.ts +5 -0
  155. package/dist/util/string.util.js +12 -0
  156. package/dist/util/triggerWrite.d.ts +11 -1
  157. package/dist/util/triggerWrite.js +14 -0
  158. package/package.json +1 -1
  159. package/skills/uql-orm/SKILL.md +22 -10
  160. package/dist/browser/options.d.ts +0 -4
  161. package/dist/browser/options.js +0 -13
  162. package/dist/browser/type/clientQuerierPool.d.ts +0 -4
  163. package/dist/browser/type/clientQuerierPool.js +0 -1
  164. package/dist/migrate/builder/expressions.d.ts +0 -69
  165. package/dist/migrate/builder/expressions.js +0 -145
@@ -1,4 +1,4 @@
1
- import { QUERY_BOOLEAN_CLAUSES, QUERY_NUMBER_CLAUSES, QUERY_OBJECT_CLAUSES, QUERY_STATEMENT_CLAUSES, } from '../type/query.js';
1
+ import { QUERY_CLAUSES } from '../type/query.js';
2
2
  import { getKeys, isRecord, someKey } from './object.util.js';
3
3
  import { UqlUsageError } from './uqlError.js';
4
4
  /** What a query populating nothing requests, shared: most reads populate nothing, and ask on every one. */
@@ -119,17 +119,18 @@ export function countedRelations(meta, counts) {
119
119
  return [{ relKey, relation, where: where ?? {} }];
120
120
  });
121
121
  }
122
- // Taken from the clause groups declared beside `Query` itself, so a renamed clause fails to compile
123
- // here instead of quietly narrowing what a relation query accepts. `$required` is the one key that
124
- // is not a `Query` clause at all - it says how the relation joins, not what it selects.
125
- const RELATION_QUERY_BOOLEAN_KEYS = new Set([...QUERY_BOOLEAN_CLAUSES, '$required']);
126
- const RELATION_QUERY_OBJECT_KEYS = new Set(QUERY_OBJECT_CLAUSES);
127
- const RELATION_QUERY_NUMBER_KEYS = new Set(QUERY_NUMBER_CLAUSES);
128
- const RELATION_QUERY_ALLOWED_KEYS = new Set([
129
- ...RELATION_QUERY_BOOLEAN_KEYS,
130
- ...RELATION_QUERY_OBJECT_KEYS,
131
- ...RELATION_QUERY_NUMBER_KEYS,
122
+ /**
123
+ * The value type each key of a relation query takes: the clauses scoped to a relation, plus `$required`,
124
+ * which is not a clause. It says how the relation joins, not what it selects.
125
+ */
126
+ const RELATION_QUERY_VALUES = new Map([
127
+ ...getKeys(QUERY_CLAUSES)
128
+ .filter((key) => QUERY_CLAUSES[key].scope === 'relation')
129
+ .map((key) => [key, QUERY_CLAUSES[key].value]),
130
+ ['$required', 'boolean'],
132
131
  ]);
132
+ /** Clauses only a top-level statement takes. A populated relation's query rejects them, naming the clause. */
133
+ const STATEMENT_CLAUSES = getKeys(QUERY_CLAUSES).filter((key) => QUERY_CLAUSES[key].scope === 'statement');
133
134
  function isRelationQueryObject(value) {
134
135
  return isRecord(value) && isValidRelationQueryShape(value);
135
136
  }
@@ -137,7 +138,7 @@ export function parseRelationQueryValue(value) {
137
138
  // Caught before the shape check so the message names the key, rather than reporting the whole
138
139
  // object as an unrecognized relation query value.
139
140
  if (isRecord(value)) {
140
- const statementOnly = QUERY_STATEMENT_CLAUSES.find((clause) => clause in value);
141
+ const statementOnly = STATEMENT_CLAUSES.find((clause) => clause in value);
141
142
  if (statementOnly) {
142
143
  throw new UqlUsageError(`'${statementOnly}' applies to the whole statement, not to a populated relation. Move it to the top level of the query.`);
143
144
  }
@@ -172,17 +173,18 @@ function isBooleanLikeValue(value) {
172
173
  function isValidRelationQueryShape(query) {
173
174
  let hasKnownKey = false;
174
175
  for (const [key, value] of Object.entries(query)) {
175
- if (!RELATION_QUERY_ALLOWED_KEYS.has(key)) {
176
+ const shape = RELATION_QUERY_VALUES.get(key);
177
+ if (shape === undefined) {
176
178
  return false;
177
179
  }
178
180
  hasKnownKey = true;
179
- if (RELATION_QUERY_BOOLEAN_KEYS.has(key) && !isBooleanLikeValue(value)) {
181
+ if (shape === 'boolean' && !isBooleanLikeValue(value)) {
180
182
  return false;
181
183
  }
182
- if (RELATION_QUERY_OBJECT_KEYS.has(key) && !isRecord(value) && !(key === '$select' && Array.isArray(value))) {
184
+ if (shape === 'object' && !isRecord(value) && !(key === '$select' && Array.isArray(value))) {
183
185
  return false;
184
186
  }
185
- if (RELATION_QUERY_NUMBER_KEYS.has(key) && (typeof value !== 'number' || !Number.isFinite(value))) {
187
+ if (shape === 'number' && (typeof value !== 'number' || !Number.isFinite(value))) {
186
188
  return false;
187
189
  }
188
190
  }
@@ -1,3 +1,4 @@
1
+ import { bytesToHex } from './bytes.js';
1
2
  /** Separates the parts of a composite key: a unit separator, which no column value carries. */
2
3
  const KEY_SEPARATOR = '\u001f';
3
4
  /**
@@ -19,10 +20,8 @@ function keyPart(value) {
19
20
  if (value instanceof Date) {
20
21
  return value.toISOString();
21
22
  }
22
- // Hex by hand rather than through `Buffer`, which is undefined on the browser and edge runtimes
23
- // this module reaches through `AbstractQuerier`.
24
23
  if (value instanceof Uint8Array) {
25
- return Array.from(value, (byte) => byte.toString(16).padStart(2, '0')).join('');
24
+ return bytesToHex(value);
26
25
  }
27
26
  return String(value);
28
27
  }
@@ -16,9 +16,15 @@ export declare function obtainAttrsPaths<T extends object>(row: T): {
16
16
  * `sales.Order_total_idx` is a syntax error.
17
17
  */
18
18
  export declare function qualifyName(name: string, schema?: string): string;
19
+ /** Reverses {@link qualifyName}: splits at the last dot into the schema, if any, and the name. */
20
+ export declare function splitQualifiedName(qualified: string): {
21
+ readonly name: string;
22
+ readonly schema?: string;
23
+ };
19
24
  /**
20
- * The name a derived index or constraint gets, `Order__total_idx`, kind last as Postgres names its own.
21
- * One rule for the AST, the DDL and a `DROP`; not a naming strategy hook, since `name:` already overrides it.
25
+ * The name of a derived index or constraint, such as `Order__total_idx`, with the kind last as Postgres names
26
+ * its own. It leaves out the table's schema, since it is a single identifier. The AST, the DDL and a `DROP`
27
+ * all use this one rule.
22
28
  */
23
29
  export declare function derivedConstraintName(table: string, parts: readonly (string | number)[], kind: ConstraintKind): string;
24
30
  /** The kinds of derived name, which is also what `indexNameStem` strips to compare them. */
@@ -1,5 +1,6 @@
1
- import { OWNED_PREFIX } from '../dialect/aliases.js';
1
+ import { OWNED_PREFIX, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
2
2
  import { hasKeys } from './object.util.js';
3
+ import { fnv1a } from './string.util.js';
3
4
  /** Pre-computed regex for each SQL identifier escape character to avoid per-call allocation. */
4
5
  const escapeIdRegexCache = { '`': /`/g, '"': /"/g };
5
6
  export function unflatObjects(objects) {
@@ -58,6 +59,11 @@ export function obtainAttrsPaths(row) {
58
59
  export function qualifyName(name, schema) {
59
60
  return schema ? `${schema}.${name}` : name;
60
61
  }
62
+ /** Reverses {@link qualifyName}: splits at the last dot into the schema, if any, and the name. */
63
+ export function splitQualifiedName(qualified) {
64
+ const dot = qualified.lastIndexOf('.');
65
+ return dot < 0 ? { name: qualified } : { name: qualified.slice(dot + 1), schema: qualified.slice(0, dot) };
66
+ }
61
67
  /**
62
68
  * The longest identifier every engine here accepts. Postgres truncates silently at 63 bytes and
63
69
  * MySQL errors at 64, so one conservative limit needs no per-dialect plumbing to be safe on both -
@@ -67,11 +73,13 @@ const MAX_IDENTIFIER_LENGTH = 63;
67
73
  /** Hex chars of hash kept when a name has to be shortened. 24 bits over one table's constraints. */
68
74
  const NAME_HASH_LENGTH = 6;
69
75
  /**
70
- * The name a derived index or constraint gets, `Order__total_idx`, kind last as Postgres names its own.
71
- * One rule for the AST, the DDL and a `DROP`; not a naming strategy hook, since `name:` already overrides it.
76
+ * The name of a derived index or constraint, such as `Order__total_idx`, with the kind last as Postgres names
77
+ * its own. It leaves out the table's schema, since it is a single identifier. The AST, the DDL and a `DROP`
78
+ * all use this one rule.
72
79
  */
73
80
  export function derivedConstraintName(table, parts, kind) {
74
- const body = parts.length ? `${table}${TABLE_SEPARATOR}${parts.join('_')}` : table;
81
+ const { name } = splitQualifiedName(table);
82
+ const body = parts.length ? `${name}${TABLE_SEPARATOR}${parts.join('_')}` : name;
75
83
  return clampIdentifier(`${body}_${kind}`);
76
84
  }
77
85
  /** Between table and columns, doubled: index names share one namespace per database, where `a` + `b_c` and `a_b` + `c` would collide. */
@@ -104,18 +112,9 @@ function clampIdentifier(name, reserved = 0) {
104
112
  const suffix = `_${hashIdentifier(name)}`;
105
113
  return name.slice(0, max - suffix.length) + suffix;
106
114
  }
107
- /**
108
- * FNV-1a, by hand: the package ships zero runtime dependencies, and `node:crypto` is not reachable
109
- * from the browser and edge entries this module is bundled into. Not a security hash - it only has
110
- * to spread the names of one table's constraints.
111
- */
115
+ /** A short hash that keeps one table's constraint names apart; it needs to do nothing more. */
112
116
  function hashIdentifier(value) {
113
- let hash = 0x811c9dc5;
114
- for (let i = 0; i < value.length; i++) {
115
- hash ^= value.charCodeAt(i);
116
- hash = Math.imul(hash, 0x01000193) >>> 0;
117
- }
118
- return hash.toString(16).padStart(NAME_HASH_LENGTH, '0').slice(-NAME_HASH_LENGTH);
117
+ return fnv1a(value).toString(16).padStart(NAME_HASH_LENGTH, '0').slice(-NAME_HASH_LENGTH);
119
118
  }
120
119
  /**
121
120
  * The name a derived index gets when nothing named it: `Order__total_idx`, or `Order__total_uk` for a
@@ -181,9 +180,9 @@ export function buildUpdateResult(payload) {
181
180
  ids = sequentialIds(id, changes, stride);
182
181
  }
183
182
  }
184
- // Whether the row was created: Postgres's `_created` column, or MySQL's 1/2/0 `affectedRows`,
183
+ // Whether the row was created: Postgres's created flag, or MySQL's 1/2/0 `affectedRows`,
185
184
  // which is unreliable under `RETURNING`, so those dialects report nothing.
186
- const created = (rows?.length === 1 ? rows[0]?.['_created'] : undefined) ??
185
+ const created = (rows?.length === 1 ? rows[0]?.[UPSERT_CREATED_ALIAS] : undefined) ??
187
186
  (insertIdSource !== 'returning' && typeof upsertStatus === 'number' && upsertStatus >= 0 && upsertStatus <= 2
188
187
  ? upsertStatus === 1
189
188
  : undefined);
@@ -1,6 +1,7 @@
1
1
  // SQL literal escaping for `Dialect.escape`: ANSI quote doubling, or MySQL's backslashes. UQL binds
2
2
  // values instead, so this is the hand-written-SQL hatch, and inline MySQL literals break under
3
3
  // `NO_BACKSLASH_ESCAPES` or a GBK-like charset: prefer bound parameters. Postgres arrays are separate.
4
+ import { bytesToHex } from './bytes.js';
4
5
  import { utcTimestamp } from './date.js';
5
6
  import { UqlUsageError } from './uqlError.js';
6
7
  const SINGLE_QUOTE = /'/g;
@@ -29,17 +30,6 @@ export function unescapeMysqlString(body) {
29
30
  return body.replace(/\\(.)|''/gs, (_, char) => char === undefined ? "'" : (MYSQL_UNESCAPES[char] ?? char));
30
31
  }
31
32
  const mysqlStringLiteral = (val) => `'${val.replace(MYSQL_SPECIALS, (char) => MYSQL_ESCAPES[char])}'`;
32
- const HEX_BYTES = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, '0'));
33
- /** Native hex encoder where available (~130x faster on 4 KB); lookup table for browsers. */
34
- function bytesToHexLiteral(bytes) {
35
- if (typeof Buffer !== 'undefined') {
36
- return `X'${Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex')}'`;
37
- }
38
- let hex = '';
39
- for (let i = 0; i < bytes.length; i++)
40
- hex += HEX_BYTES[bytes[i]];
41
- return `X'${hex}'`;
42
- }
43
33
  /**
44
34
  * A factory, not a function taking `escapeString` as an argument: threading it through every call
45
35
  * measured 1.1-1.5x slower. Rejects unsupported types rather than stringifying them into SQL.
@@ -66,7 +56,7 @@ function createEscaper(escapeString, zone = '') {
66
56
  }
67
57
  // A Node `Buffer` is a `Uint8Array` too.
68
58
  if (value instanceof Uint8Array) {
69
- return bytesToHexLiteral(value);
59
+ return `X'${bytesToHex(value)}'`;
70
60
  }
71
61
  if ('toSqlString' in value && typeof value.toSqlString === 'function') {
72
62
  return String(value.toSqlString());
@@ -26,3 +26,8 @@ export declare function singularize(name: string): string;
26
26
  * @example 'category' -> 'categories'
27
27
  */
28
28
  export declare function pluralize(name: string): string;
29
+ /**
30
+ * The FNV-1a hash of `value`, written by hand because the package has zero runtime dependencies and the
31
+ * browser and edge entries cannot reach `node:crypto`. It is not a security hash; it only tells inputs apart.
32
+ */
33
+ export declare function fnv1a(value: string): number;
@@ -89,3 +89,15 @@ export function pluralize(name) {
89
89
  }
90
90
  return name + 's';
91
91
  }
92
+ /**
93
+ * The FNV-1a hash of `value`, written by hand because the package has zero runtime dependencies and the
94
+ * browser and edge entries cannot reach `node:crypto`. It is not a security hash; it only tells inputs apart.
95
+ */
96
+ export function fnv1a(value) {
97
+ let hash = 0x811c9dc5;
98
+ for (let i = 0; i < value.length; i++) {
99
+ hash ^= value.charCodeAt(i);
100
+ hash = Math.imul(hash, 0x01000193) >>> 0;
101
+ }
102
+ return hash;
103
+ }
@@ -1,10 +1,15 @@
1
- import { type EntityPredicate, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
1
+ import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type UpsertOptions, type WritableKey, type WriteRow } from '../type/index.js';
2
2
  /**
3
3
  * A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
4
4
  * Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
5
5
  * set-based trigger included, where it inserts one row for each the statement touched.
6
6
  */
7
7
  export declare function insertInto<E extends object>(entity: Type<E>, row: WriteRow<E>): QueryRaw;
8
+ /**
9
+ * A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
10
+ * does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { update: { count: { $inc: 1 } } })`.
11
+ */
12
+ export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, { update }?: UpsertOptions<E, UpdatePayload<E, QueryRaw, WritableKey<E>, never>>): QueryRaw;
8
13
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
9
14
  export declare function updateTable<E extends object>(entity: Type<E>, q: {
10
15
  readonly $where: EntityPredicate<E>;
@@ -13,5 +18,10 @@ export declare function updateTable<E extends object>(entity: Type<E>, q: {
13
18
  export declare function deleteFrom<E extends object>(entity: Type<E>, q: {
14
19
  readonly $where: EntityPredicate<E>;
15
20
  }): QueryRaw;
21
+ /**
22
+ * Fails the write that fired the trigger, with `message` as the error: a table kept append-only refuses its
23
+ * updates and deletes, and a `where` narrows it to the rows a rule forbids.
24
+ */
25
+ export declare function refuse(message: string): QueryRaw;
16
26
  /** A write in a trigger's body, as every helper here and a stamp render one. */
17
27
  export declare function written(write: TriggerWrite): QueryRaw;
@@ -7,6 +7,13 @@ import { TriggerWriteRaw, } from '../type/index.js';
7
7
  export function insertInto(entity, row) {
8
8
  return written({ kind: 'insert', entity, row });
9
9
  }
10
+ /**
11
+ * A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
12
+ * does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { update: { count: { $inc: 1 } } })`.
13
+ */
14
+ export function upsertInto(entity, conflictPaths, row, { update } = {}) {
15
+ return written({ kind: 'upsert', entity, conflictPaths, row, update });
16
+ }
10
17
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
11
18
  export function updateTable(entity, q, set) {
12
19
  return written({ kind: 'update', entity, set, where: q.$where });
@@ -15,6 +22,13 @@ export function updateTable(entity, q, set) {
15
22
  export function deleteFrom(entity, q) {
16
23
  return written({ kind: 'delete', entity, where: q.$where });
17
24
  }
25
+ /**
26
+ * Fails the write that fired the trigger, with `message` as the error: a table kept append-only refuses its
27
+ * updates and deletes, and a `where` narrows it to the rows a rule forbids.
28
+ */
29
+ export function refuse(message) {
30
+ return written({ kind: 'refuse', message });
31
+ }
18
32
  /** A write in a trigger's body, as every helper here and a stamp render one. */
19
33
  export function written(write) {
20
34
  return new TriggerWriteRaw(({ ctx, dialect, rows }) => dialect.triggerWrite(ctx, write, rows));
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Deno, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.91.1",
6
+ "version": "0.93.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=24"
@@ -74,18 +74,20 @@ export class Post {
74
74
  }
75
75
  ```
76
76
 
77
- - Every `@Field` states its `type` (`String`, `Number`, `Boolean`, `Date` (an instant, bound and read as UTC on every engine; `TIMESTAMPTZ` on Postgres and CockroachDB, `DATETIME(3)` on MySQL and MariaDB; `precision` sets its fractional-second digits), `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`), except a foreign key, which takes `references` and inherits the target key's type.
77
+ - Every `@Field` states its `type`: `String`, `Number`, `Boolean`, `Date`, `BigInt`, or a column type such as `'uuid'`, `'text'`, `'jsonb'`. A foreign key takes `references` instead and inherits the target key's type. A `Date` is an instant, stored in UTC to the millisecond on every engine; `precision` sets other fractional digits.
78
78
  - A column is nullable unless it says `nullable: false`, and its property must admit `null` to match: `title?: string | null`. A property typed without `| null` on a nullable column is a compile error.
79
79
  - Declare a `nullable: false` column `!` (`email!: string`): reads have it and inserts must name it, except a single-column key and a `version`, which uql fills. Declare `?` whatever an insert may leave out: a nullable, `onInsert`, `defaultValue`, `eager: false` or `computed` field, and relations.
80
80
  - An engine's own column type is a `raw` constant, ``columnType: raw`tsvector` ``, rendered verbatim and carrying its own `length`/`precision`: never a bare string.
81
+ - `defaultValue` is a value of the field's type, or SQL the database evaluates per row: one of `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``raw`...` ``. A string is always text, `'CURRENT_TIMESTAMP'` included. The migration builder takes the same.
82
+ - `currentTimestamp` is the database clock, UTC to the millisecond on every engine, where a raw `CURRENT_TIMESTAMP` is not on SQLite, MySQL or SQL Server. Use it for a default, a stamp, `onUpdate` or `$where`.
81
83
  - Members are named by callbacks, never by strings: `mappedBy: (post) => post.author`, `references: (post) => post.authorId`.
82
84
  - `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names its junction entity.
83
85
  - `@Index((post) => [post.authorId], { where: { archived: { $ne: true } } })` states a partial index's filter as the predicate the query passes, never as `raw`: a planner matches the two by shape, so `raw` that means the same thing leaves the index unused.
84
86
  - `@Field({ type: Number, version: true })`, with `[versionKey]?: 'version'` on the class, is an optimistic lock:
85
87
  an update must carry the version it read (a compile error otherwise), and one against a row someone else moved on throws `UqlOptimisticLockError` (kind `optimisticLock`, HTTP 409). Its updates name one row by its id; save and upsert are refused.
86
88
  - `@Field({ computed })` is a value the database produces, on a `readonly` property: SQL over the row, ``(u) => raw`${u.first} || ' ' || ${u.last}` ``, or a relation aggregate, `(order) => order.items.count()`.
87
- `stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, a trigger writing it on those events whoever writes the row (``computed: raw`CURRENT_TIMESTAMP` ``), where `onUpdate` covers only uql's own writes.
88
- - `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires (`defineEntity`'s `triggers` or `defineTrigger` without decorators); `where` holds a `$where` predicate per row it names, or SQL off the rows. `run` takes `(newRow, oldRow)`, each only where the event has it (no `oldRow` on insert, no `newRow` on delete), and returns the body: `insertInto(Audit, { postId: newRow.id })`, `updateTable(Audit, { $where: { postId: newRow.id } }, { status: newRow.status })` or `deleteFrom(Audit, { $where: { postId: oldRow.id } })`, typed by the entity written and rendered on every engine (no `onInsert`/`onUpdate` fills, so an insert names each field uql fills on insert unless its column has a `defaultValue`; `$where` reads the entity's own fields; no entity filters, security ones included, so a soft-delete entity is hard-deleted; an update or delete naming no rows is refused; no `$inc`/`$mul`/`$push` on SQL Server), several joined in one `raw`. Anything else is `raw` SQL over the refs, one body for every engine or `{ postgres, mssql, ... }` where they differ (SQL Server fires per statement, reading `inserted`/`deleted` as tables, with no `before*`; `of` and `where` narrow what the write helpers read there, so SQL of its own is refused beside them). MongoDB has none, and refuses a write to an entity declaring one.
89
+ `stored: true` makes the SQL a generated column; `stored: ['insert', 'update']` makes it a stamp, which a trigger writes on those events whoever writes the row (`computed: currentTimestamp`), where `onUpdate` covers only uql's own writes.
90
+ - `@Trigger({ on: 'afterUpdate', of: (post) => [post.status], where: { $old: { status: 'draft' } }, run })` is a trigger the database fires. `run(newRow, oldRow)` returns the body, written with `insertInto`, `upsertInto` (as `upsertOne` takes it), `updateTable`, `deleteFrom` and `refuse(message)` (fails the write), which are typed by the entity written and render on every engine; `deferred: true` fires an after trigger at commit, on Postgres only; anything else is `raw` SQL over the rows, per engine where they differ. A trigger's writes skip uql's fills and entity filters, soft delete included. MongoDB has none. Details, SQL Server's per-statement shape included: https://uql-orm.dev/entities/triggers.md
89
91
  - `defineEntity` defines the same entity without decorators: https://uql-orm.dev/entities/imperative.md
90
92
 
91
93
  ## Queries
@@ -108,8 +110,12 @@ const users = await pool.findMany(User, {
108
110
  `$count: { posts: true }` tallies a to-many under `_count` without loading it.
109
111
  - `$sort` takes `'asc'`/`1` or `'desc'`/`-1`, and `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'` or
110
112
  `'descNullsLast'` to say where nulls land, which reads the same on every engine (emulated where there is no
111
- `NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres and CockroachDB sort nulls last on `asc`,
112
- the rest sort them first.
113
+ `NULLS FIRST`). Unqualified, each engine keeps its own answer: Postgres sorts nulls last on `asc`, the rest sort them first.
114
+ - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000
115
+ costs what page 1 does, and answers `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`: pass
116
+ `endCursor` as `$after`, or `startCursor` as `$before` to go back. `$sort` must include the key or a unique
117
+ `nullable: false` field, uses the entity's own fields, and takes no `$skip`. A nullable leading sort key pages
118
+ correctly but cannot use an index.
113
119
  - `$where` takes a value for equality or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$in`,
114
120
  `$nin`, `$between`, `$like`, `$ilike`, `$regex`, `$startsWith`, `$endsWith`, `$includes`, `$isNull`,
115
121
  `$isNotNull`. `$and`, `$or`, `$not` and `$nor` combine clauses.
@@ -122,9 +128,10 @@ const users = await pool.findMany(User, {
122
128
  - `$populate` loads relations in the same statement. Nothing is lazy: a relation not populated is not there.
123
129
  - A query is plain data, so it can be built dynamically, stored, or sent from a browser to `uql-orm/http`,
124
130
  whose handler serves only the entities its required `include` names.
125
- - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyStream`, `count`, `exists`,
131
+ - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`,
126
132
  `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`,
127
133
  `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first.
134
+ - `upsertOne(Entity, { email: true }, row, { update })`: a conflicting row takes `update`, an update's payload with its operators, instead of `row`; a new one inserts `row`. `{ update: {} }` leaves a conflicting row as it is: insert if absent.
128
135
  - `updateMany` and `deleteMany` naming no rows - no `$where` holding a value (an `undefined` or an empty group holds none), no `$limit` - throw; `{ unfiltered: true }` means the whole table.
129
136
  - An update takes `{ stock: { $inc: -1 } }` to add, or `$mul` to multiply, in the statement, a NULL counting as 0,
130
137
  so a guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. JSON fields take `$set`, `$unset`,
@@ -154,10 +161,15 @@ transaction. A querier from `pool.getQuerier()` is yours to release: bind it wit
154
161
 
155
162
  ## Migrations
156
163
 
157
- `npx uql-migrate` reads `uql.config.ts`. `sync` creates what the entities imply (development only);
158
- `generate:entities` writes the diff as a migration file to review, renaming a column its field was renamed from, printing `renameTable` for a table that may have been, rebuilding a SQLite table for what it cannot alter, and refusing a required column with no default on a table holding rows; `up` applies migrations; `generate:from-db`
159
- writes entity classes from an existing database; `drift:check` fails when the database no longer matches.
160
- Triggers are part of the diff: uql installs its own under `_uql_`-prefixed names and never touches another.
164
+ `npx uql-migrate` reads `uql.config.ts`:
165
+
166
+ - `sync` applies what the entities imply (development only).
167
+ - `generate:entities` writes the diff as a migration file to review. It renames a column whose field was renamed and refuses a required column with no default on a table holding rows.
168
+ - `up` and `down` apply and revert migrations.
169
+ - `generate:from-db` writes entity classes from an existing database.
170
+ - `drift:check` fails when the database no longer matches.
171
+
172
+ Triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
161
173
 
162
174
  ## Where to read more
163
175
 
@@ -1,4 +0,0 @@
1
- import type { ClientQuerier, ClientQuerierPool } from './type/index.js';
2
- export declare function setQuerierPool<T extends ClientQuerierPool>(pool: T): void;
3
- export declare function getQuerierPool(): ClientQuerierPool;
4
- export declare function getQuerier(): ClientQuerier;
@@ -1,13 +0,0 @@
1
- import { HttpQuerier } from './querier/httpQuerier.js';
2
- let defaultPool = {
3
- getQuerier: () => new HttpQuerier('/api'),
4
- };
5
- export function setQuerierPool(pool) {
6
- defaultPool = pool;
7
- }
8
- export function getQuerierPool() {
9
- return defaultPool;
10
- }
11
- export function getQuerier() {
12
- return getQuerierPool().getQuerier();
13
- }
@@ -1,4 +0,0 @@
1
- import type { ClientQuerier } from './clientQuerier.js';
2
- export type ClientQuerierPool = {
3
- getQuerier(): ClientQuerier;
4
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,69 +0,0 @@
1
- import type { AbstractSqlDialect } from '../../dialect/index.js';
2
- import type { SqlDialectName } from '../../type/index.js';
3
- /**
4
- * A {@link ColumnSchema.defaultValue} that is SQL rather than a literal. Kinds are symbolic: the
5
- * dialect names the spelling and {@link formatDefaultValue} renders one at DDL time.
6
- */
7
- export type SqlExpressionKind = 'now' | 'currentDate' | 'currentTime' | 'uuid' | 'uuidv7' | 'onUpdateNow' | 'raw';
8
- /** Every kind's DDL spelling, `null` where an engine has none. `raw` carries its own text instead. */
9
- export type SqlExpressionMap = Readonly<Record<Exclude<SqlExpressionKind, 'raw'>, string | null>>;
10
- /** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
11
- export type DialectDefaults = {
12
- /** Spelling of each kind, `null` where the engine has none. */
13
- readonly expressions: SqlExpressionMap;
14
- /** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
15
- readonly wrapTypes?: RegExp;
16
- /** Column types whose `CURRENT_TIMESTAMP` default must repeat their precision, captured by the pattern. */
17
- readonly preciseTypes?: RegExp;
18
- };
19
- /**
20
- * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
21
- * bundle - the same split that keeps `CANONICAL_TO_SQL` in `schema/canonicalType.ts`. `uuidv7()` is
22
- * Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
23
- * not being knowable here.
24
- */
25
- export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
26
- /**
27
- * A DDL default that is SQL rather than a literal. A class, not a plain object, so a JSON default
28
- * cannot masquerade as one: `defaultValue` accepts `unknown`.
29
- */
30
- export declare class SqlExpression {
31
- readonly kind: SqlExpressionKind;
32
- readonly sql?: string | undefined;
33
- /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
34
- constructor(kind: SqlExpressionKind, sql?: string | undefined);
35
- static isExpression(value: unknown): value is SqlExpression;
36
- }
37
- /**
38
- * Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
39
- * `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
40
- *
41
- * Use in migrations: `t.timestamp('createdAt', { defaultValue: expr.now() })`
42
- */
43
- export declare const expr: {
44
- /** Current timestamp. */
45
- now: () => SqlExpression;
46
- /** Current date. */
47
- currentDate: () => SqlExpression;
48
- /** Current time. */
49
- currentTime: () => SqlExpression;
50
- /** Generated UUID. SQLite has no built-in one and throws; pass `expr.raw` there. */
51
- uuid: () => SqlExpression;
52
- /**
53
- * Time-ordered UUID, which indexes far better than a random one as a key. Postgres 18+ and
54
- * MariaDB 11.7+ only; MySQL, SQLite and CockroachDB have no such function and throw.
55
- */
56
- uuidv7: () => SqlExpression;
57
- /** MySQL's `ON UPDATE CURRENT_TIMESTAMP`. Throws on dialects without it. */
58
- onUpdateNow: () => SqlExpression;
59
- /** SQL taken verbatim, for anything the kinds above do not cover. Not portable by definition. */
60
- raw: (sql: string) => SqlExpression;
61
- };
62
- /**
63
- * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
64
- * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
65
- * the result needs wrapping, which MySQL demands on its large types whatever the value.
66
- */
67
- export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
68
- /** Whether a stored default is the declared one, as the engine reprints it: `'a'::character varying` is `'a'`. */
69
- export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
@@ -1,145 +0,0 @@
1
- import { UqlUsageError } from '../../util/uqlError.js';
2
- const ANSI = {
3
- now: 'CURRENT_TIMESTAMP',
4
- currentDate: 'CURRENT_DATE',
5
- currentTime: 'CURRENT_TIME',
6
- uuid: null,
7
- uuidv7: null,
8
- onUpdateNow: null,
9
- };
10
- const PG = { ...ANSI, uuid: 'gen_random_uuid()' };
11
- const MYSQL = {
12
- ...ANSI,
13
- uuid: 'UUID()',
14
- onUpdateNow: 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
15
- };
16
- /** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
17
- const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
18
- /** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
19
- const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
20
- /**
21
- * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
22
- * bundle - the same split that keeps `CANONICAL_TO_SQL` in `schema/canonicalType.ts`. `uuidv7()` is
23
- * Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
24
- * not being knowable here.
25
- */
26
- export const DIALECT_DEFAULTS = {
27
- postgres: { expressions: { ...PG, uuidv7: 'uuidv7()' } },
28
- cockroachdb: { expressions: PG },
29
- mysql: { expressions: MYSQL, wrapTypes: MYSQL_LARGE_TYPES, preciseTypes: MYSQL_PRECISE_TYPES },
30
- mariadb: {
31
- expressions: { ...MYSQL, uuidv7: 'UUID_v7()' },
32
- wrapTypes: MYSQL_LARGE_TYPES,
33
- preciseTypes: MYSQL_PRECISE_TYPES,
34
- },
35
- sqlite: { expressions: ANSI },
36
- // `SYSUTCDATETIME()` over `CURRENT_TIMESTAMP`, which is local time in the server's zone. No
37
- // `uuidv7`: `NEWSEQUENTIALID()` is an ordered v4 GUID, so it carries no readable timestamp and
38
- // does not sort the way a v7 does elsewhere - a `uuidv7()` default is refused rather than served
39
- // something that only looks like one.
40
- mssql: { expressions: { ...ANSI, now: 'SYSUTCDATETIME()', uuid: 'NEWID()' } },
41
- };
42
- /**
43
- * A DDL default that is SQL rather than a literal. A class, not a plain object, so a JSON default
44
- * cannot masquerade as one: `defaultValue` accepts `unknown`.
45
- */
46
- export class SqlExpression {
47
- kind;
48
- sql;
49
- /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
50
- constructor(kind, sql) {
51
- this.kind = kind;
52
- this.sql = sql;
53
- }
54
- static isExpression(value) {
55
- return value instanceof SqlExpression;
56
- }
57
- }
58
- /**
59
- * Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
60
- * `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
61
- *
62
- * Use in migrations: `t.timestamp('createdAt', { defaultValue: expr.now() })`
63
- */
64
- export const expr = {
65
- /** Current timestamp. */
66
- now: () => new SqlExpression('now'),
67
- /** Current date. */
68
- currentDate: () => new SqlExpression('currentDate'),
69
- /** Current time. */
70
- currentTime: () => new SqlExpression('currentTime'),
71
- /** Generated UUID. SQLite has no built-in one and throws; pass `expr.raw` there. */
72
- uuid: () => new SqlExpression('uuid'),
73
- /**
74
- * Time-ordered UUID, which indexes far better than a random one as a key. Postgres 18+ and
75
- * MariaDB 11.7+ only; MySQL, SQLite and CockroachDB have no such function and throw.
76
- */
77
- uuidv7: () => new SqlExpression('uuidv7'),
78
- /** MySQL's `ON UPDATE CURRENT_TIMESTAMP`. Throws on dialects without it. */
79
- onUpdateNow: () => new SqlExpression('onUpdateNow'),
80
- /** SQL taken verbatim, for anything the kinds above do not cover. Not portable by definition. */
81
- raw: (sql) => new SqlExpression('raw', sql),
82
- };
83
- /**
84
- * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
85
- * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
86
- * the result needs wrapping, which MySQL demands on its large types whatever the value.
87
- */
88
- export function formatDefaultValue(value, dialect, columnType) {
89
- const sql = defaultLiteral(value, dialect, columnType);
90
- const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
91
- return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
92
- }
93
- /** Whether a stored default is the declared one, as the engine reprints it: `'a'::character varying` is `'a'`. */
94
- export function sameDefault(desired, current, dialect) {
95
- if (current === desired)
96
- return true;
97
- // Both spellings of "no default" are the same fact, and engines disagree on which they report:
98
- // MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
99
- // `MODIFY` every nullable column, on every sync, forever.
100
- if (current == null || desired == null)
101
- return current == null && desired == null;
102
- const normalize = (value) => {
103
- // Render first: the desired side may be a symbolic expression, the current side is always the
104
- // engine's own text, and `{"kind":"now"}` matches no spelling of `CURRENT_TIMESTAMP`.
105
- const val = SqlExpression.isExpression(value) ? formatDefaultValue(value, dialect) : value;
106
- if (typeof val === 'string') {
107
- let s = val.replace(/::[a-z_]+(\s+[a-z_]+)*(\[\])?$/i, '');
108
- s = s.replace(/^'(.*)'$/, '$1');
109
- if (s.toLowerCase() === 'null')
110
- return 'null';
111
- return s;
112
- }
113
- return typeof val === 'object' ? JSON.stringify(val) : String(val);
114
- };
115
- return normalize(current) === normalize(desired);
116
- }
117
- /**
118
- * Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
119
- * it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the cases `escape`
120
- * cannot serve stay here: a boolean is `1` where booleans are integers, and a plain object or array
121
- * is JSON rather than the throw and the IN-list `escape` gives them.
122
- */
123
- function defaultLiteral(value, dialect, columnType) {
124
- if (value === undefined || value === null) {
125
- return 'NULL';
126
- }
127
- if (SqlExpression.isExpression(value)) {
128
- return expressionSql(value, dialect, columnType);
129
- }
130
- if (typeof value === 'boolean') {
131
- return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
132
- }
133
- return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
134
- }
135
- function expressionSql(expression, dialect, columnType) {
136
- const { expressions, preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
137
- const raw = expression.kind === 'raw';
138
- const sql = raw ? expression.sql : expressions[expression.kind];
139
- if (sql == null) {
140
- throw new UqlUsageError(`${dialect.dialectName} has no '${expression.kind}' default; pass expr.raw(...) with SQL this engine accepts`);
141
- }
142
- // A raw default is the caller's SQL, never rewritten.
143
- const precision = raw || columnType === undefined ? undefined : preciseTypes?.exec(columnType)?.[1];
144
- return precision === undefined ? sql : sql.replaceAll('CURRENT_TIMESTAMP', `CURRENT_TIMESTAMP(${precision})`);
145
- }