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
@@ -21,11 +21,16 @@ export declare class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospect
21
21
  protected mapIndexesResult(_read: TableRowReader, _tableName: string, results: MysqlIndexRow[]): Promise<IndexSchema[]>;
22
22
  protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: JoinedForeignKeyRow[]): Promise<ForeignKeySchema[]>;
23
23
  /**
24
- * MariaDB prints a string default as the literal it is (`'it''s'`). MySQL prints one bare, save an
25
- * expression default (`DEFAULT ('x')`, what a `TEXT` column takes), which comes with a charset
26
- * introducer and every quote and backslash escaped once more: `_utf8mb4\'x\'`.
24
+ * MySQL prints a literal default unquoted, except one wrapped as `DEFAULT ('x')`, the form a `TEXT`
25
+ * column takes. That one comes with a charset introducer and every quote and backslash escaped again:
26
+ * `_utf8mb4\'x\'`.
27
27
  */
28
- protected parseDefaultValue(defaultValue: string | null): unknown;
28
+ protected parseDefaultValue(defaultValue: string | null, extra?: string): unknown;
29
+ /**
30
+ * A default's SQL, or `undefined` for a literal. MySQL flags a SQL default `DEFAULT_GENERATED` and prints
31
+ * it escaped like a literal, with charset introducers on its strings: `lower(_utf8mb4\'A\')`.
32
+ */
33
+ protected sqlText(defaultValue: string, extra: string): string | undefined;
29
34
  }
30
35
  type MysqlColumnRow = {
31
36
  column_name: string;
@@ -51,6 +56,8 @@ type MysqlColumnRow = {
51
56
  * JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
52
57
  */
53
58
  export declare class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
59
+ /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
60
+ protected sqlText(defaultValue: string): string | undefined;
54
61
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
55
62
  readonly indexFacets: ReadonlySet<IndexFacet>;
56
63
  /**
@@ -1,4 +1,5 @@
1
1
  import { unescapeMysqlString } from '../../util/sqlLiteral.js';
2
+ import { expr } from '../builder/expressions.js';
2
3
  import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
3
4
  /**
4
5
  * MySQL/MariaDB schema introspector.
@@ -108,7 +109,7 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
108
109
  name: row.column_name,
109
110
  type: row.column_type.toUpperCase(),
110
111
  nullable: row.is_nullable === 'YES',
111
- defaultValue: this.parseDefaultValue(row.column_default),
112
+ defaultValue: this.parseDefaultValue(row.column_default, row.extra),
112
113
  isPrimaryKey: row.column_key === 'PRI',
113
114
  isAutoIncrement: row.extra.toLowerCase().includes('auto_increment'),
114
115
  isUnique: row.column_key === 'UNI',
@@ -136,30 +137,39 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
136
137
  return this.joinedForeignKeys(results);
137
138
  }
138
139
  /**
139
- * MariaDB prints a string default as the literal it is (`'it''s'`). MySQL prints one bare, save an
140
- * expression default (`DEFAULT ('x')`, what a `TEXT` column takes), which comes with a charset
141
- * introducer and every quote and backslash escaped once more: `_utf8mb4\'x\'`.
140
+ * MySQL prints a literal default unquoted, except one wrapped as `DEFAULT ('x')`, the form a `TEXT`
141
+ * column takes. That one comes with a charset introducer and every quote and backslash escaped again:
142
+ * `_utf8mb4\'x\'`.
142
143
  */
143
- parseDefaultValue(defaultValue) {
144
+ parseDefaultValue(defaultValue, extra = '') {
144
145
  if (defaultValue === null) {
145
146
  return undefined;
146
147
  }
147
- const normalized = defaultValue.toUpperCase();
148
- if (normalized === 'NULL') {
148
+ if (defaultValue.toUpperCase() === 'NULL') {
149
149
  return null;
150
150
  }
151
- // Whatever precision it repeats from its column, which the column's own type already states.
152
- if (/^CURRENT_TIMESTAMP(?:\(\d?\))?$/.test(normalized)) {
153
- return 'CURRENT_TIMESTAMP';
154
- }
155
151
  if (/^-?\d+(\.\d+)?$/.test(defaultValue)) {
156
152
  return Number(defaultValue);
157
153
  }
158
154
  const introduced = /^_\w+(\\'.*\\')$/s.exec(defaultValue);
155
+ const sql = introduced ? undefined : this.sqlText(defaultValue, extra);
156
+ if (sql !== undefined) {
157
+ // Any precision here repeats the column's own, which the column type already states.
158
+ return /^CURRENT_TIMESTAMP(?:\(\d?\))?$/i.test(sql) ? expr.now() : this.sqlDefault(sql);
159
+ }
159
160
  const literal = introduced ? unescapeMysqlString(introduced[1]) : defaultValue;
160
161
  const quoted = /^'(.*)'$/s.exec(literal);
161
162
  return quoted ? unescapeMysqlString(quoted[1]) : literal;
162
163
  }
164
+ /**
165
+ * A default's SQL, or `undefined` for a literal. MySQL flags a SQL default `DEFAULT_GENERATED` and prints
166
+ * it escaped like a literal, with charset introducers on its strings: `lower(_utf8mb4\'A\')`.
167
+ */
168
+ sqlText(defaultValue, extra) {
169
+ return extra.includes('DEFAULT_GENERATED')
170
+ ? unescapeMysqlString(defaultValue).replace(/(?<![\w'])_[a-z0-9]+(?=')/gi, '')
171
+ : undefined;
172
+ }
163
173
  }
164
174
  const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
165
175
  /**
@@ -171,6 +181,10 @@ const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
171
181
  * JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
172
182
  */
173
183
  export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
184
+ /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
185
+ sqlText(defaultValue) {
186
+ return defaultValue.startsWith("'") ? undefined : defaultValue;
187
+ }
174
188
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
175
189
  indexFacets = new Set(['vector', 'distance']);
176
190
  /**
@@ -62,8 +62,8 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
62
62
  protected normalizeType(dataType: string, udtName: string): string;
63
63
  /**
64
64
  * Postgres quotes a negative number (`'-3'::integer`); CockroachDB parenthesizes one (`(-3)`) and
65
- * writes a quote-bearing string in escape syntax (`e'it\'s'`). Any other cast is dropped, and a
66
- * function call (`now()`, `nextval(...)`) is returned as written.
65
+ * writes a string containing a quote in escape syntax (`e'it\'s'`). Other casts are dropped, and a
66
+ * default that is not a literal is SQL, such as `now()` or `nextval(...)`.
67
67
  */
68
68
  protected parseDefaultValue(defaultValue: string | null): unknown;
69
69
  protected isAutoIncrement(columnDefault: string | null, isIdentity: string): boolean;
@@ -255,8 +255,8 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
255
255
  }
256
256
  /**
257
257
  * Postgres quotes a negative number (`'-3'::integer`); CockroachDB parenthesizes one (`(-3)`) and
258
- * writes a quote-bearing string in escape syntax (`e'it\'s'`). Any other cast is dropped, and a
259
- * function call (`now()`, `nextval(...)`) is returned as written.
258
+ * writes a string containing a quote in escape syntax (`e'it\'s'`). Other casts are dropped, and a
259
+ * default that is not a literal is SQL, such as `now()` or `nextval(...)`.
260
260
  */
261
261
  parseDefaultValue(defaultValue) {
262
262
  if (!defaultValue) {
@@ -278,7 +278,7 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
278
278
  if (cleaned === 'true' || cleaned === 'false') {
279
279
  return cleaned === 'true';
280
280
  }
281
- return cleaned === 'NULL' ? null : cleaned;
281
+ return cleaned === 'NULL' ? null : this.sqlDefault(cleaned);
282
282
  }
283
283
  isAutoIncrement(columnDefault, isIdentity) {
284
284
  // PostgreSQL identity columns (GENERATED ... AS IDENTITY)
@@ -7,8 +7,8 @@ import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSq
7
7
  export declare class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
8
8
  /** Whether an index is libSQL's vector index, where the engine has one; elsewhere a declared one is built plain. */
9
9
  readonly indexFacets: ReadonlySet<IndexFacet>;
10
- /** Not SQLite's own tables, nor the ones libSQL keeps a vector index in: its metadata and `<index>_shadow`. */
11
10
  protected triggersQuery(): string;
11
+ /** User tables only: skips SQLite's own and libSQL's vector index tables (its metadata and `<index>_shadow`). */
12
12
  protected getTableNamesQuery(): string;
13
13
  protected tableExistsQuery(): string;
14
14
  protected parseTableExistsResult([row]: SqliteCountRow[]): boolean;
@@ -6,10 +6,10 @@ import { AbstractSqlSchemaIntrospector } from './abstractSqlSchemaIntrospector.j
6
6
  export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
7
7
  /** Whether an index is libSQL's vector index, where the engine has one; elsewhere a declared one is built plain. */
8
8
  indexFacets = new Set(this.dialect.hasVectorIndex() ? ['vector', 'distance'] : []);
9
- /** Not SQLite's own tables, nor the ones libSQL keeps a vector index in: its metadata and `<index>_shadow`. */
10
9
  triggersQuery() {
11
10
  return /*sql*/ `SELECT name, sql AS definition FROM sqlite_master WHERE type = 'trigger' AND tbl_name = ?`;
12
11
  }
12
+ /** User tables only: skips SQLite's own and libSQL's vector index tables (its metadata and `<index>_shadow`). */
13
13
  getTableNamesQuery() {
14
14
  return /*sql*/ `
15
15
  SELECT name
@@ -38,16 +38,16 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
38
38
  * SQLite cannot do to an existing table anyway. PRAGMA takes no bound parameters, hence the splice.
39
39
  */
40
40
  getColumnsQuery(tableName) {
41
- return /*sql*/ `PRAGMA table_xinfo(${this.escapeId(tableName)})`;
41
+ return /*sql*/ `PRAGMA table_xinfo(${this.dialect.escapeId(tableName)})`;
42
42
  }
43
43
  getIndexesQuery(tableName) {
44
- return /*sql*/ `PRAGMA index_list(${this.escapeId(tableName)})`;
44
+ return /*sql*/ `PRAGMA index_list(${this.dialect.escapeId(tableName)})`;
45
45
  }
46
46
  getForeignKeysQuery(tableName) {
47
- return /*sql*/ `PRAGMA foreign_key_list(${this.escapeId(tableName)})`;
47
+ return /*sql*/ `PRAGMA foreign_key_list(${this.dialect.escapeId(tableName)})`;
48
48
  }
49
49
  getPrimaryKeyQuery(tableName) {
50
- return /*sql*/ `PRAGMA table_info(${this.escapeId(tableName)})`;
50
+ return /*sql*/ `PRAGMA table_info(${this.dialect.escapeId(tableName)})`;
51
51
  }
52
52
  getColumnsParams(_tableName) {
53
53
  return [];
@@ -185,7 +185,7 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
185
185
  };
186
186
  }
187
187
  getIndexColumns(read, indexName) {
188
- return read(/*sql*/ `PRAGMA index_info(${this.escapeId(indexName)})`);
188
+ return read(/*sql*/ `PRAGMA index_info(${this.dialect.escapeId(indexName)})`);
189
189
  }
190
190
  normalizeType(type) {
191
191
  // Extract base type without length/precision
@@ -203,9 +203,6 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
203
203
  if (defaultValue === 'NULL') {
204
204
  return null;
205
205
  }
206
- if (defaultValue === 'CURRENT_TIMESTAMP' || defaultValue === 'CURRENT_DATE' || defaultValue === 'CURRENT_TIME') {
207
- return defaultValue;
208
- }
209
206
  if (/^'.*'$/.test(defaultValue)) {
210
207
  return defaultValue.slice(1, -1).replaceAll("''", "'");
211
208
  }
@@ -220,7 +217,7 @@ export class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
220
217
  return 1;
221
218
  if (upper === 'FALSE')
222
219
  return 0;
223
- return defaultValue;
220
+ return this.sqlDefault(defaultValue);
224
221
  }
225
222
  }
226
223
  /** `PRAGMA table_xinfo`'s `hidden` for a column the engine stores rather than recomputes on each read. */
@@ -45,9 +45,9 @@ const mongoSession = (querier) => ({
45
45
  transaction: (work) => work(),
46
46
  });
47
47
  /** Imported on use, so the optional `mongodb` peer loads only on MongoDB. */
48
- async function mongoSchemaGenerator(namingStrategy, defaultForeignKeyAction) {
48
+ async function mongoSchemaGenerator(namingStrategy) {
49
49
  const { MongoSchemaGenerator } = await import('../mongo/mongoSchemaGenerator.js');
50
- return new MongoSchemaGenerator(namingStrategy, defaultForeignKeyAction);
50
+ return new MongoSchemaGenerator(namingStrategy);
51
51
  }
52
52
  export function migrationTargetFor(pool, defaultForeignKeyAction) {
53
53
  const { dialect } = pool;
@@ -55,7 +55,7 @@ export function migrationTargetFor(pool, defaultForeignKeyAction) {
55
55
  return {
56
56
  source: migrationSource.MongoQuerier,
57
57
  storage: (tableName) => new MongoMigrationStorage(pool, { tableName }),
58
- generator: () => mongoSchemaGenerator(dialect.namingStrategy, defaultForeignKeyAction),
58
+ generator: () => mongoSchemaGenerator(dialect.namingStrategy),
59
59
  withSession: (task) => withMongoQuerierForMigrations(pool, 'Migrator', (querier) => task(mongoSession(querier))),
60
60
  };
61
61
  }
@@ -2,9 +2,9 @@ import type { AbstractSqlDialect } from '../dialect/index.js';
2
2
  import type { SchemaAST } from '../schema/schemaAST.js';
3
3
  import { type BuildSchemaASTOptions } from '../schema/schemaASTBuilder.js';
4
4
  import { type DiffOptions } from '../schema/schemaASTDiffer.js';
5
- import type { CanonicalType, ColumnNode, ForeignKeyAction, IndexNode, TableNode } from '../schema/types.js';
6
- import type { ColumnSchema, CreateSchemaOptions, DialectFeatures, DropSchemaOptions, EntityMeta, InstalledTriggers, EntityWhereMeta, FieldMeta, FieldOptions, ForeignKeySchema, IndexSchema, Rename, NamingStrategy, SchemaDiff, SchemaGenerator, Type } from '../type/index.js';
7
- import type { AnyMigrationOperation, FullColumnDefinition, IndexDefinition, TableDefinition } from './builder/types.js';
5
+ import { type CanonicalType, type ColumnNode, type ForeignKeyAction, type IndexNode, type TableNode } from '../schema/types.js';
6
+ import type { ColumnSchema, CreateSchemaOptions, DialectFeatures, DropSchemaOptions, EntityMeta, InstalledTriggers, EntityWhereMeta, FieldOptions, ForeignKeySchema, IndexSchema, Rename, NamingStrategy, SchemaDiff, SchemaGenerator, Type } from '../type/index.js';
7
+ import type { AnyMigrationOperation, FullColumnDefinition, TableDefinition } from './builder/types.js';
8
8
  import { type IndexDdl, type TableDdl } from './ddl/index.js';
9
9
  /**
10
10
  * Unified SQL schema generator.
@@ -34,7 +34,7 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
34
34
  */
35
35
  protected serialType(type: CanonicalType): string;
36
36
  /** The SQL type a column is spelled with: the generated-key form for an auto-increment key, the canonical type otherwise. */
37
- protected columnSqlType(col: ColumnNode): string;
37
+ protected columnSqlType(col: Pick<ColumnNode, 'type' | 'isPrimaryKey' | 'isAutoIncrement'>): string;
38
38
  protected canonicalTypeToSql(type: CanonicalType): string;
39
39
  /** The entity side as an AST, carrying this generator's default referential action. */
40
40
  buildAST(entities: readonly Type<object>[]): SchemaAST;
@@ -106,11 +106,6 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
106
106
  * a unique index, which the table creates beside it. An enum's `CHECK` comes last, the only place MariaDB takes it.
107
107
  */
108
108
  private renderColumn;
109
- /**
110
- * The column type a field gets, resolved as its table resolves it. A field alone cannot tell that it is
111
- * one column of a composite key, which its table never makes serial.
112
- */
113
- getSqlType(field: FieldMeta): string;
114
109
  /** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
115
110
  generateColumnComment(comment: string): string;
116
111
  /** The `COMMENT ON` statements a table and its columns need, after the `CREATE TABLE`, where the engine uses them. */
@@ -132,6 +127,8 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
132
127
  */
133
128
  private rebuildOf;
134
129
  diffOptions(): DiffOptions;
130
+ /** Converts a builder's column to the `ColumnSchema` its DDL is rendered from. */
131
+ private definitionColumn;
135
132
  /** Spread, not copied field by field, so a field the node gains cannot go missing here. */
136
133
  private columnNodeToSchema;
137
134
  /** Whether a column's stored default is the one the entity declares, as this engine reprints it. */
@@ -140,8 +137,8 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
140
137
  ifNotExists?: boolean;
141
138
  }): string[];
142
139
  /**
143
- * Generate a column definition from a ColumnNode. A composite key is declared as a table constraint,
144
- * so only a lone primary key column carries `PRIMARY KEY` inline.
140
+ * Generate a column definition from a ColumnNode. The primary key is never inline: it is always a table
141
+ * constraint, so a later `DROP` can name it.
145
142
  */
146
143
  protected generateColumnFromNode(col: ColumnNode): string;
147
144
  /**
@@ -154,7 +151,6 @@ export declare class SqlSchemaGenerator implements SchemaGenerator {
154
151
  generateCreateTableFromDefinition(table: TableDefinition, options?: {
155
152
  ifNotExists?: boolean;
156
153
  }): string[];
157
- generateCreateIndexFromDefinition(tableName: string, index: IndexDefinition): string;
158
154
  generateRenameTableSql(oldName: string, newName: string): string;
159
155
  /** `raw` is split, being the one SQL no generator wrote. */
160
156
  generateOperation(operation: AnyMigrationOperation): string[];
@@ -1,9 +1,10 @@
1
1
  import { getMeta } from '../entity/index.js';
2
- import { canonicalToSql, engineType, isVectorCategory, resolveColumnCanonicalType } from '../schema/canonicalType.js';
2
+ import { canonicalToSql, engineType, isVectorCategory } from '../schema/canonicalType.js';
3
3
  import { indexChanges } from '../schema/indexDifferences.js';
4
4
  import { buildSchemaAST } from '../schema/schemaASTBuilder.js';
5
5
  import { diffRelationshipNodes, diffTable } from '../schema/schemaASTDiffer.js';
6
- import { isAutoIncrement, qualifyName } from '../util/index.js';
6
+ import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
7
+ import { qualifyName } from '../util/index.js';
7
8
  import { derivedCheckName, derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName } from '../util/sql.util.js';
8
9
  import { UqlUsageError } from '../util/uqlError.js';
9
10
  import { formatDefaultValue, sameDefault } from './builder/expressions.js';
@@ -11,7 +12,7 @@ import { splitSqlStatements } from './builder/splitSqlStatements.js';
11
12
  import { indexDdlFor, tableDdlFor } from './ddl/index.js';
12
13
  import { sizedType } from './ddl/tableDdl.js';
13
14
  import { rebuildTable } from './ddl/tableRebuild.js';
14
- import { columnForeignKey, columnIndex, fullColumnDefinitionToNode, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
15
+ import { columnForeignKey, columnIndex, bareColumn, renderIndexDefinition, tableDefinitionToNode, } from './generator/definitionToNode.js';
15
16
  import { indexNodeToSchema } from './generator/indexNodeToSchema.js';
16
17
  import { assertIndexPredicate } from './indexPredicate.js';
17
18
  import { added, alterations, dropped, needsRebuild, newlyRequired, nonEmpty, sides } from './schemaChange.js';
@@ -27,7 +28,7 @@ export class SqlSchemaGenerator {
27
28
  indexDdl;
28
29
  /** The `ALTER TABLE` statements this dialect spells its own way, the migrator's for the same reason. */
29
30
  tableDdl;
30
- constructor(dialect, defaultForeignKeyAction = 'NO ACTION') {
31
+ constructor(dialect, defaultForeignKeyAction = DEFAULT_FOREIGN_KEY_ACTION) {
31
32
  this.dialect = dialect;
32
33
  this.defaultForeignKeyAction = defaultForeignKeyAction;
33
34
  this.indexDdl = indexDdlFor(dialect);
@@ -242,10 +243,7 @@ export class SqlSchemaGenerator {
242
243
  * operand instead, which is already qualified.
243
244
  */
244
245
  generateDropIndex(tableName, indexName, schema) {
245
- if (this.dialect.dropIndexSyntax === 'on-table') {
246
- return `DROP INDEX ${this.escapeId(indexName)} ON ${this.escapeId(tableName)};`;
247
- }
248
- return `DROP INDEX IF EXISTS ${this.dialect.escapeQualifiedId(indexName, schema)};`;
246
+ return this.tableDdl.dropIndex(tableName, indexName, schema);
249
247
  }
250
248
  /**
251
249
  * A column definition from a {@link ColumnSchema}, whose type is already the engine's spelling. Apart from
@@ -278,16 +276,6 @@ export class SqlSchemaGenerator {
278
276
  }
279
277
  return def;
280
278
  }
281
- /**
282
- * The column type a field gets, resolved as its table resolves it. A field alone cannot tell that it is
283
- * one column of a composite key, which its table never makes serial.
284
- */
285
- getSqlType(field) {
286
- const canonical = resolveColumnCanonicalType(field);
287
- return isAutoIncrement(field, field.isId === true)
288
- ? this.serialType(canonical)
289
- : this.canonicalTypeToSql(canonical);
290
- }
291
279
  /** The inline ` COMMENT '...'` a column declaration carries, where the engine takes one there. */
292
280
  generateColumnComment(comment) {
293
281
  return this.features.commentSyntax === 'inline' ? ` COMMENT ${this.dialect.escape(comment)}` : '';
@@ -335,44 +323,36 @@ export class SqlSchemaGenerator {
335
323
  // restated `CHECK` by adding a *second* constraint rather than replacing the first, so the column
336
324
  // would accumulate one per alter. An enum's values reach the database with the column and are never
337
325
  // restated - which is also why changing them is a hand-written migration. See architecture/roadmap.md.
338
- const columns = (tableDiff?.columnDiffs ?? []).map((it) => {
339
- if (it.type === 'add') {
340
- return { to: this.columnNodeToSchema(it.expected) };
326
+ const columns = (tableDiff?.columns ?? []).map((it) => {
327
+ if (it.from === undefined) {
328
+ return { to: this.columnNodeToSchema(it.to) };
341
329
  }
342
- if (it.type === 'drop') {
343
- return { from: this.columnNodeToSchema(it.actual), isBreaking: true };
330
+ if (it.to === undefined) {
331
+ return { from: this.columnNodeToSchema(it.from), isBreaking: true };
344
332
  }
345
333
  return {
346
- from: this.columnNodeToSchema(it.actual),
347
- to: { ...this.columnNodeToSchema(it.expected), enum: undefined },
334
+ from: this.columnNodeToSchema(it.from),
335
+ to: { ...this.columnNodeToSchema(it.to), enum: undefined },
348
336
  isBreaking: it.isBreaking,
349
337
  };
350
338
  });
351
- const keyDiff = tableDiff?.primaryKeyDiff;
339
+ const keyDiff = tableDiff?.primaryKey;
352
340
  // The key added named as this generator names it, so the rollback can drop it by that name.
353
341
  const primaryKey = keyDiff && {
354
- from: keyDiff.actual,
355
- to: keyDiff.expected && {
356
- columns: keyDiff.expected.columns,
357
- name: derivedPrimaryKeyName(tableName, keyDiff.expected.columns),
358
- },
342
+ from: keyDiff.from,
343
+ to: keyDiff.to && { columns: keyDiff.to.columns, name: derivedPrimaryKeyName(tableName, keyDiff.to.columns) },
359
344
  };
360
- const relationDiffs = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations, this.diffOptions());
361
- const foreignKeys = relationDiffs.map(({ actual, expected }) => ({
362
- from: actual && foreignKeyOf(actual),
363
- to: expected && foreignKeyOf(expected),
364
- }));
345
+ const foreignKeys = diffRelationshipNodes(desired.outgoingRelations, currentTable.outgoingRelations).map(({ from, to }) => ({ from: from && foreignKeyOf(from), to: to && foreignKeyOf(to) }));
365
346
  const alter = {
366
347
  tableName,
367
348
  schema,
368
349
  type: 'alter',
369
350
  primaryKey,
370
351
  columns: nonEmpty(columns),
371
- indexes: nonEmpty([
372
- ...indexes.toAdd.map((to) => ({ to: indexNodeToSchema(to) })),
373
- ...indexes.toDrop.map((from) => ({ from: indexNodeToSchema(from) })),
374
- ...indexes.toAlter.map(({ from, to }) => ({ from: indexNodeToSchema(from), to: indexNodeToSchema(to) })),
375
- ]),
352
+ indexes: nonEmpty(indexes.changes.map(({ from, to }) => ({
353
+ from: from && indexNodeToSchema(from),
354
+ to: to && indexNodeToSchema(to),
355
+ }))),
376
356
  foreignKeys: nonEmpty(foreignKeys),
377
357
  renamedColumns: nonEmpty(renamedColumns ?? []),
378
358
  };
@@ -415,6 +395,11 @@ export class SqlSchemaGenerator {
415
395
  defaultsEqual: this.defaultsEqual,
416
396
  };
417
397
  }
398
+ /** Converts a builder's column to the `ColumnSchema` its DDL is rendered from. */
399
+ definitionColumn(col) {
400
+ const column = bareColumn(col);
401
+ return { ...column, type: this.columnSqlType(column) };
402
+ }
418
403
  /** Spread, not copied field by field, so a field the node gains cannot go missing here. */
419
404
  columnNodeToSchema(col) {
420
405
  const { table: _table, referencedBy: _referencedBy, references: _references, ...column } = col;
@@ -460,8 +445,8 @@ export class SqlSchemaGenerator {
460
445
  createSql += constraints.map((c) => ` ${c}`).join(',\n');
461
446
  }
462
447
  createSql += '\n)';
463
- if (this.dialect.tableOptions) {
464
- createSql += ` ${this.dialect.tableOptions}`;
448
+ if (this.tableDdl.tableOptions) {
449
+ createSql += ` ${this.tableDdl.tableOptions}`;
465
450
  }
466
451
  if (table.comment && this.features.commentSyntax === 'inline') {
467
452
  createSql += ` COMMENT=${this.dialect.escape(table.comment)}`;
@@ -484,8 +469,8 @@ export class SqlSchemaGenerator {
484
469
  return statements;
485
470
  }
486
471
  /**
487
- * Generate a column definition from a ColumnNode. A composite key is declared as a table constraint,
488
- * so only a lone primary key column carries `PRIMARY KEY` inline.
472
+ * Generate a column definition from a ColumnNode. The primary key is never inline: it is always a table
473
+ * constraint, so a later `DROP` can name it.
489
474
  */
490
475
  generateColumnFromNode(col) {
491
476
  return this.renderColumn({ ...col, type: this.columnSqlType(col) });
@@ -502,9 +487,6 @@ export class SqlSchemaGenerator {
502
487
  const tableNode = tableDefinitionToNode(table, (sql) => this.dialect.compileDdl(sql));
503
488
  return this.generateCreateTableFromNode(tableNode, options);
504
489
  }
505
- generateCreateIndexFromDefinition(tableName, index) {
506
- return this.generateCreateIndex(tableName, renderIndexDefinition(index, (sql) => this.dialect.compileDdl(sql)));
507
- }
508
490
  generateRenameTableSql(oldName, newName) {
509
491
  return this.tableDdl.renameTable(oldName, newName);
510
492
  }
@@ -543,7 +525,7 @@ export class SqlSchemaGenerator {
543
525
  }
544
526
  /** `ADD COLUMN`, plus the foreign key and index the column declares, as `CREATE TABLE` lifts them. */
545
527
  generateAddColumnSql(tableName, column) {
546
- const statements = this.addColumnStatements(tableName, this.columnNodeToSchema(fullColumnDefinitionToNode(column, tableName)));
528
+ const statements = this.addColumnStatements(tableName, this.definitionColumn(column));
547
529
  const foreignKey = columnForeignKey(column);
548
530
  if (foreignKey) {
549
531
  statements.push(...this.addForeignKeyStatements(tableName, [foreignKey]));
@@ -556,8 +538,8 @@ export class SqlSchemaGenerator {
556
538
  }
557
539
  generateAlterColumnSql(tableName, columnName, column) {
558
540
  this.assertAlterable(`Altering the column "${columnName}" of "${tableName}"`);
559
- const node = fullColumnDefinitionToNode(column, tableName);
560
- return this.tableDdl.alterColumn(tableName, { ...this.columnNodeToSchema(node), name: columnName }, this.generateColumnFromNode(node));
541
+ const schema = this.definitionColumn(column);
542
+ return this.tableDdl.alterColumn(tableName, { ...schema, name: columnName }, this.renderColumn(schema));
561
543
  }
562
544
  generateDropColumnSql(tableName, columnName) {
563
545
  return this.tableDdl.dropColumn(tableName, columnName);
@@ -585,7 +567,7 @@ export class SqlSchemaGenerator {
585
567
  return `ALTER TABLE ${this.escapeId(tableName)} ADD ${constraint};`;
586
568
  }
587
569
  generateDropForeignKeySql(tableName, constraintName) {
588
- return `ALTER TABLE ${this.escapeId(tableName)} ${this.dialect.dropForeignKeySyntax} ${this.escapeId(constraintName)};`;
570
+ return this.tableDdl.dropForeignKey(tableName, constraintName);
589
571
  }
590
572
  /**
591
573
  * `ALTER TABLE ... ADD CONSTRAINT <name> PRIMARY KEY (...)`, the other half of
@@ -604,15 +586,7 @@ export class SqlSchemaGenerator {
604
586
  */
605
587
  generateDropPrimaryKeySql(tableName, constraintName) {
606
588
  this.assertAlterable(`Changing the primary key of "${tableName}"`);
607
- const table = this.escapeId(tableName);
608
- if (this.dialect.dropPrimaryKeySyntax === 'DROP PRIMARY KEY') {
609
- return `ALTER TABLE ${table} DROP PRIMARY KEY;`;
610
- }
611
- if (!constraintName) {
612
- throw new UqlUsageError(`Cannot drop the primary key of "${tableName}": ${this.dialect} names the constraint, and ` +
613
- 'introspection did not report a name for it.');
614
- }
615
- return `ALTER TABLE ${table} DROP CONSTRAINT ${this.escapeId(constraintName)};`;
589
+ return this.tableDdl.dropPrimaryKey(tableName, constraintName);
616
590
  }
617
591
  /** A stored generated column, which an engine that rebuilds tables takes only in a `CREATE TABLE`. */
618
592
  assertColumnAddable(tableName, column) {
@@ -19,6 +19,6 @@ export declare function dropTrigger<E>(dialect: AbstractSqlDialect, meta: Entity
19
19
  /**
20
20
  * The triggers a stamp needs: one per event it names, each assigning the field's expression to its
21
21
  * column. Generated rather than authored, so unlike an authored body it renders on every engine from
22
- * one declaration - and not at all on the MySQL family, whose columns stamp themselves.
22
+ * one declaration.
23
23
  */
24
24
  export declare function stampTriggers<E extends object>(dialect: AbstractSqlDialect, meta: EntityMeta<E>): EntityTriggerMeta<E>[];
@@ -156,7 +156,7 @@ function condition(dialect, meta, where, rows, names, operand) {
156
156
  /**
157
157
  * The triggers a stamp needs: one per event it names, each assigning the field's expression to its
158
158
  * column. Generated rather than authored, so unlike an authored body it renders on every engine from
159
- * one declaration - and not at all on the MySQL family, whose columns stamp themselves.
159
+ * one declaration.
160
160
  */
161
161
  export function stampTriggers(dialect, meta) {
162
162
  const features = dialect.features.triggers;
@@ -184,10 +184,10 @@ const STAMP_EVENTS = {
184
184
  after: { insert: 'afterInsert', update: 'afterUpdate' },
185
185
  };
186
186
  /**
187
- * The one statement a stamp runs, in whichever of the two shapes the engine leaves open: an assignment
188
- * to the incoming row, or where it may not be written, the row restated after the write, as any write in
189
- * a trigger's body is, keyed on its whole key and only where the stamp still differs: that `UPDATE` fires
190
- * the trigger again, and with recursive triggers on it then finds nothing left to change.
187
+ * The statement a stamp runs: an assignment to the incoming row where the engine allows one, else an
188
+ * `UPDATE` of the written row after the write, by its whole key and only where the stamp still differs.
189
+ * That `UPDATE` fires the table's triggers again; where a running trigger can fire again, `reentryGuard`
190
+ * makes the nested run return.
191
191
  */
192
192
  function stampBody(dialect, meta, key, value, newRow) {
193
193
  const { entity } = meta;
@@ -201,7 +201,9 @@ function stampBody(dialect, meta, key, value, newRow) {
201
201
  const stamped = dialect.compileDdl(value, entity);
202
202
  const differs = raw(({ ctx, escapedPrefix }) => ctx.append(dialect.neExpr(`${escapedPrefix}${dialect.escapedColumnName(meta, key)}`, stamped)));
203
203
  const where = { $and: [...keyed, differs] };
204
- return written({ kind: 'update', entity, set: { [key]: value }, where });
204
+ const restated = written({ kind: 'update', entity, set: { [key]: value }, where });
205
+ const { reentryGuard } = dialect.features.triggers;
206
+ return reentryGuard ? raw `${raw(() => reentryGuard)}\n${restated}` : restated;
205
207
  }
206
208
  /** A dollar quote the body does not contain, so no `$$` in it - a literal, a comment - ends the function early. */
207
209
  function dollarQuote(body) {
@@ -35,7 +35,6 @@ export declare class MongoDialect extends AbstractDialect {
35
35
  #private;
36
36
  readonly features: DialectFeatures;
37
37
  readonly dialectName = "mongodb";
38
- readonly insertIdSource = "returning";
39
38
  /**
40
39
  * MongoDB stores the primary key as `_id`; everything else resolves as usual. Projections, sorts,
41
40
  * `$group` refs and `$where` keys all map through here, so no read path can address a property name
@@ -80,8 +79,6 @@ export declare class MongoDialect extends AbstractDialect {
80
79
  * Each end is one field matched against one `_id`, so both sides must be sole-keyed.
81
80
  */
82
81
  private junctionOf;
83
- /** Whether a query subtracts `key` from the projection, via `$exclude` or a negative `$select`. */
84
- private subtractsKey;
85
82
  /** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
86
83
  private assertNoRaw;
87
84
  /**
@@ -222,6 +219,10 @@ export declare class MongoDialect extends AbstractDialect {
222
219
  * it, and anything else as given. Only 24-hex, not any 12-byte string. Arrays convert element-wise.
223
220
  */
224
221
  toWireId(value: unknown): unknown;
222
+ /** Whether `key` holds ids the driver stores as `ObjectId`s: the entity's own `_id`, or a reference to one. */
223
+ private holdsKeys;
224
+ /** Converts every operand `ops` compares a key against with {@link toWireId}, including inside a `$not`. */
225
+ private toWireOperands;
225
226
  /** The seam out of the driver: an `ObjectId` becomes its hex string, the type the code declares. */
226
227
  fromWireId(value: unknown): unknown;
227
228
  getPersistable<E extends Document>(meta: EntityMeta<E>, payload: EntityData<E>, callbackKey: CallbackKey): Partial<E>;