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,39 +1,7 @@
1
- import { indexNameParts, normalizeIndexColumn } from '../../util/index.js';
2
- import { derivedIndexName } from '../../util/sql.util.js';
1
+ import { DEFAULT_FOREIGN_KEY_ACTION } from '../../schema/types.js';
2
+ import { UqlUsageError } from '../../util/uqlError.js';
3
+ import { indexDefinition } from '../generator/definitionToNode.js';
3
4
  import { TableBuilder } from './tableBuilder.js';
4
- /**
5
- * One `createIndex` operation. Shared because the alter-table builder, the recorder and the
6
- * executing builder all record the same thing, and an entry left unnormalized reaches the generator
7
- * as a column literally named `[object Object]`.
8
- */
9
- function createIndexOperation(tableName, columns, options = {}) {
10
- const { name, unique, ...index } = options;
11
- const entries = columns.map(normalizeIndexColumn);
12
- return {
13
- type: 'createIndex',
14
- tableName,
15
- index: {
16
- ...index,
17
- name: name ?? derivedIndexName(tableName, indexNameParts(entries)),
18
- entries,
19
- unique: unique ?? false,
20
- },
21
- };
22
- }
23
- /** An `addForeignKey` operation, `NO ACTION` defaults included, for the three builders that record one. */
24
- function addForeignKeyOperation(tableName, columns, target, options = {}) {
25
- return {
26
- type: 'addForeignKey',
27
- tableName,
28
- foreignKey: {
29
- name: options.name,
30
- columns,
31
- references: { table: target.table, columns: target.columns },
32
- onDelete: options.onDelete ?? 'NO ACTION',
33
- onUpdate: options.onUpdate ?? 'NO ACTION',
34
- },
35
- };
36
- }
37
5
  /** One column declared through `createTable`'s vocabulary, a throwaway {@link TableBuilder}, so its type is stated. */
38
6
  function buildOneColumn(callback) {
39
7
  return callback(new TableBuilder('')).build();
@@ -70,8 +38,12 @@ class AlterTableBuilder {
70
38
  });
71
39
  return this;
72
40
  }
41
+ /** Alters only the column: throws if it declares an index or a foreign key, rather than dropping them. */
73
42
  alterColumn(callback) {
74
43
  const column = buildOneColumn(callback);
44
+ if (column.index || column.foreignKey) {
45
+ throw new UqlUsageError(`alterColumn changes '${column.name}' alone: add its index with createIndex, its foreign key with addForeignKey`);
46
+ }
75
47
  this.operations.push({
76
48
  type: 'alterColumn',
77
49
  tableName: this.tableName,
@@ -81,7 +53,11 @@ class AlterTableBuilder {
81
53
  return this;
82
54
  }
83
55
  addIndex(columns, options) {
84
- this.operations.push(createIndexOperation(this.tableName, columns, options));
56
+ this.operations.push({
57
+ type: 'createIndex',
58
+ tableName: this.tableName,
59
+ index: indexDefinition(this.tableName, columns, options),
60
+ });
85
61
  return this;
86
62
  }
87
63
  dropIndex(name) {
@@ -92,8 +68,18 @@ class AlterTableBuilder {
92
68
  });
93
69
  return this;
94
70
  }
95
- addForeignKey(columns, target, options) {
96
- this.operations.push(addForeignKeyOperation(this.tableName, columns, target, options));
71
+ addForeignKey(columns, target, options = {}) {
72
+ this.operations.push({
73
+ type: 'addForeignKey',
74
+ tableName: this.tableName,
75
+ foreignKey: {
76
+ name: options.name,
77
+ columns,
78
+ references: { table: target.table, columns: target.columns },
79
+ onDelete: options.onDelete ?? DEFAULT_FOREIGN_KEY_ACTION,
80
+ onUpdate: options.onUpdate ?? DEFAULT_FOREIGN_KEY_ACTION,
81
+ },
82
+ });
97
83
  return this;
98
84
  }
99
85
  dropForeignKey(name) {
@@ -152,56 +138,30 @@ export class OperationRecorder {
152
138
  await this.record(operation);
153
139
  }
154
140
  }
155
- async addColumn(tableName, callback) {
156
- await this.record({
157
- type: 'addColumn',
158
- tableName,
159
- column: buildOneColumn(callback),
160
- });
141
+ // Each single change delegates to `alterTable`, so each operation is implemented only once.
142
+ addColumn(tableName, callback) {
143
+ return this.alterTable(tableName, (table) => table.addColumn(callback));
161
144
  }
162
- async dropColumn(tableName, columnName) {
163
- await this.record({
164
- type: 'dropColumn',
165
- tableName,
166
- columnName,
167
- });
145
+ dropColumn(tableName, columnName) {
146
+ return this.alterTable(tableName, (table) => table.dropColumn(columnName));
168
147
  }
169
- async alterColumn(tableName, callback) {
170
- const column = buildOneColumn(callback);
171
- await this.record({
172
- type: 'alterColumn',
173
- tableName,
174
- columnName: column.name,
175
- changes: column,
176
- });
148
+ alterColumn(tableName, callback) {
149
+ return this.alterTable(tableName, (table) => table.alterColumn(callback));
177
150
  }
178
- async renameColumn(tableName, oldName, newName) {
179
- await this.record({
180
- type: 'renameColumn',
181
- tableName,
182
- oldName,
183
- newName,
184
- });
151
+ renameColumn(tableName, oldName, newName) {
152
+ return this.alterTable(tableName, (table) => table.renameColumn(oldName, newName));
185
153
  }
186
- async createIndex(tableName, columns, options) {
187
- await this.record(createIndexOperation(tableName, columns, options));
154
+ createIndex(tableName, columns, options) {
155
+ return this.alterTable(tableName, (table) => table.addIndex(columns, options));
188
156
  }
189
- async dropIndex(tableName, indexName) {
190
- await this.record({
191
- type: 'dropIndex',
192
- tableName,
193
- indexName,
194
- });
157
+ dropIndex(tableName, indexName) {
158
+ return this.alterTable(tableName, (table) => table.dropIndex(indexName));
195
159
  }
196
- async addForeignKey(tableName, columns, target, options = {}) {
197
- await this.record(addForeignKeyOperation(tableName, columns, target, options));
160
+ addForeignKey(tableName, columns, target, options) {
161
+ return this.alterTable(tableName, (table) => table.addForeignKey(columns, target, options));
198
162
  }
199
- async dropForeignKey(tableName, constraintName) {
200
- await this.record({
201
- type: 'dropForeignKey',
202
- tableName,
203
- constraintName,
204
- });
163
+ dropForeignKey(tableName, constraintName) {
164
+ return this.alterTable(tableName, (table) => table.dropForeignKey(constraintName));
205
165
  }
206
166
  async raw(sql) {
207
167
  await this.record({
@@ -46,13 +46,6 @@ export declare class TableBuilder implements ITableBuilder {
46
46
  primaryKey(columns: string[]): this;
47
47
  unique(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
48
48
  index(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
49
- /**
50
- * `@Index` and `table.index(...)` differ only in how the name is defaulted, so both normalize their
51
- * entries here: the generator renders expressions and per-column modifiers from the normalized
52
- * form, and anything left as a bare string would reach it as a column literally named `[object
53
- * Object]`.
54
- */
55
- private addIndex;
56
49
  foreignKey(columns: string[]): ITableForeignKeyBuilder;
57
50
  comment(text: string): this;
58
51
  /**
@@ -3,11 +3,15 @@
3
3
  *
4
4
  * Fluent API for defining tables in migrations.
5
5
  */
6
- import { indexNameParts, normalizeIndexColumn } from '../../util/index.js';
7
- import { derivedIndexName } from '../../util/sql.util.js';
8
- import { columnForeignKey, columnIndex } from '../generator/definitionToNode.js';
6
+ import { DEFAULT_FOREIGN_KEY_ACTION } from '../../schema/types.js';
7
+ import { DATE_PRECISION } from '../../util/date.js';
8
+ import { currentTimestamp } from '../../util/raw.js';
9
+ import { columnForeignKey, columnIndex, indexDefinition } from '../generator/definitionToNode.js';
9
10
  import { ColumnBuilder } from './columnBuilder.js';
10
- import { expr } from './expressions.js';
11
+ /** Normalizes `table.index` options, where a bare string is the index name. */
12
+ function namedOptions(options) {
13
+ return typeof options === 'string' ? { name: options } : (options ?? {});
14
+ }
11
15
  /**
12
16
  * Builder for table-level foreign keys.
13
17
  */
@@ -15,11 +19,11 @@ class TableForeignKeyBuilder {
15
19
  _columns;
16
20
  _referencedTable;
17
21
  _referencedColumns = [];
18
- _onDelete = 'NO ACTION';
19
- _onUpdate = 'NO ACTION';
22
+ _onDelete = DEFAULT_FOREIGN_KEY_ACTION;
23
+ _onUpdate = DEFAULT_FOREIGN_KEY_ACTION;
20
24
  _name;
21
- constructor(columns, _parent) {
22
- this._columns = columns;
25
+ constructor(_columns) {
26
+ this._columns = _columns;
23
27
  }
24
28
  references(table, columns) {
25
29
  this._referencedTable = table;
@@ -110,10 +114,10 @@ export class TableBuilder {
110
114
  return this.add(name, { category: 'time' }, options);
111
115
  }
112
116
  timestamp(name, options) {
113
- return this.add(name, { category: 'timestamp' }, options);
117
+ return this.add(name, { category: 'timestamp', precision: DATE_PRECISION }, options);
114
118
  }
115
119
  timestamptz(name, options) {
116
- return this.add(name, { category: 'timestamp', withTimezone: true }, options);
120
+ return this.add(name, { category: 'timestamp', withTimezone: true, precision: DATE_PRECISION }, options);
117
121
  }
118
122
  json(name, options) {
119
123
  return this.add(name, { category: 'json' }, options);
@@ -144,7 +148,7 @@ export class TableBuilder {
144
148
  return this.timestampNow('updatedAt');
145
149
  }
146
150
  timestampNow(name) {
147
- return this.timestamptz(name, { defaultValue: expr.now() });
151
+ return this.timestamptz(name, { defaultValue: currentTimestamp });
148
152
  }
149
153
  timestamps() {
150
154
  this.createdAt();
@@ -155,30 +159,15 @@ export class TableBuilder {
155
159
  return this;
156
160
  }
157
161
  unique(columns, options) {
158
- return this.addIndex(columns, options, true);
162
+ this._indexes.push(indexDefinition(this._name, columns, { ...namedOptions(options), unique: true }, true));
163
+ return this;
159
164
  }
160
165
  index(columns, options) {
161
- return this.addIndex(columns, options, false);
162
- }
163
- /**
164
- * `@Index` and `table.index(...)` differ only in how the name is defaulted, so both normalize their
165
- * entries here: the generator renders expressions and per-column modifiers from the normalized
166
- * form, and anything left as a bare string would reach it as a column literally named `[object
167
- * Object]`.
168
- */
169
- addIndex(columns, options, unique) {
170
- const { name, ...rest } = typeof options === 'string' ? { name: options } : (options ?? {});
171
- const entries = columns.map(normalizeIndexColumn);
172
- this._indexes.push({
173
- ...rest,
174
- name: name ?? derivedIndexName(this._name, indexNameParts(entries), unique),
175
- entries,
176
- unique,
177
- });
166
+ this._indexes.push(indexDefinition(this._name, columns, namedOptions(options)));
178
167
  return this;
179
168
  }
180
169
  foreignKey(columns) {
181
- const fk = new TableForeignKeyBuilder(columns, this);
170
+ const fk = new TableForeignKeyBuilder(columns);
182
171
  this._foreignKeyBuilders.push(fk);
183
172
  return fk;
184
173
  }
@@ -68,13 +68,13 @@ export interface VectorColumnOptions extends BaseColumnOptions {
68
68
  dimensions?: number;
69
69
  }
70
70
  /** A column as the builder describes one: a {@link ColumnNode} without its graph links. */
71
- export type ColumnDefinition = Omit<ColumnNode, 'table' | 'referencedBy' | 'references'>;
71
+ export type ColumnDefinition = Except<ColumnNode, 'table' | 'referencedBy' | 'references'>;
72
72
  /**
73
73
  * The foreign key a single column declares: {@link ForeignKeySchema} without the local columns, which
74
74
  * are the column itself. Derived for the reason {@link ColumnDefinition} is - restated, the two spelled
75
75
  * their target differently and every hand-off between them had to translate.
76
76
  */
77
- export type ForeignKeyDefinition = Omit<ForeignKeySchema, 'columns'>;
77
+ export type ForeignKeyDefinition = Except<ForeignKeySchema, 'columns'>;
78
78
  /**
79
79
  * Full column definition including foreign key.
80
80
  */
@@ -1,7 +1,7 @@
1
1
  import { canonicalToTypeScript } from '../../schema/canonicalType.js';
2
2
  import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
3
3
  import { camelCase, lowerFirst, pascalCase, singularize, upperFirst } from '../../util/string.util.js';
4
- import { buildFieldOptionsSource, enumMembersSource, fieldNeedsRaw } from './fieldOptionsSource.js';
4
+ import { buildFieldOptionsSource, enumMembersSource, fieldImports } from './fieldOptionsSource.js';
5
5
  import { buildIndexDecoratorSource, indexNeedsRaw, isPlainFieldIndex } from './indexDecoratorSource.js';
6
6
  import { memberSource, quoted } from './sourceLiteral.js';
7
7
  /** The decorator on the other side of a relation. */
@@ -80,8 +80,8 @@ export class EntityCodeGenerator {
80
80
  if (col.isPrimaryKey) {
81
81
  uqlImports.add('Id');
82
82
  }
83
- if (fieldNeedsRaw(col)) {
84
- uqlImports.add('raw');
83
+ for (const name of fieldImports(col)) {
84
+ uqlImports.add(name);
85
85
  }
86
86
  if (col.type.category === 'json') {
87
87
  uqlImports.add('type Json');
@@ -1,6 +1,6 @@
1
1
  import { getMeta } from '../../entity/index.js';
2
2
  import { canonicalToTypeScript, resolveColumnCanonicalType } from '../../schema/canonicalType.js';
3
- import { isToManyRelation, upperFirst } from '../../util/index.js';
3
+ import { declaresNotNull, isToManyRelation, upperFirst } from '../../util/index.js';
4
4
  import { isIdentifierName } from './sourceLiteral.js';
5
5
  /**
6
6
  * A `.d.ts` for the entities as registered, so a shape that only exists at runtime reaches the
@@ -60,7 +60,7 @@ function fieldMember(key, field) {
60
60
  return ` ${name}?: ${type};`;
61
61
  }
62
62
  const written = field.computed === undefined ? '' : 'readonly ';
63
- if (!field.isId && field.nullable !== false) {
63
+ if (!declaresNotNull(field)) {
64
64
  return ` ${written}${name}?: ${type} | null;`;
65
65
  }
66
66
  const optional = !field.isId && (field.defaultValue !== undefined || field.onInsert !== undefined || field.eager === false);
@@ -3,5 +3,5 @@ import type { ColumnNode, EnumValues } from '../../schema/types.js';
3
3
  export declare function buildFieldOptionsSource(col: ColumnNode, propertyName: string, indexName?: string): string;
4
4
  /** An enum's members as source literals, which are also the property's type as a union. */
5
5
  export declare function enumMembersSource(members: EnumValues): string[];
6
- /** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
7
- export declare function fieldNeedsRaw(col: ColumnNode): boolean;
6
+ /** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
7
+ export declare function fieldImports(col: ColumnNode): string[];
@@ -1,4 +1,6 @@
1
1
  import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalType.js';
2
+ import { SqlExpression } from '../../schema/sqlExpression.js';
3
+ import { DATE_PRECISION } from '../../util/date.js';
2
4
  import { isAutoIncrement } from '../../util/field.util.js';
3
5
  import { quoted, rawTag } from './sourceLiteral.js';
4
6
  /** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
@@ -14,7 +16,7 @@ const OPTION_SOURCE = {
14
16
  `type: ${quoted(columnType)}`,
15
17
  ...(col.type.length && col.type.category === 'string' ? [`length: ${col.type.length}`] : []),
16
18
  ...(col.type.length && isVectorCategory(col.type.category) ? [`dimensions: ${col.type.length}`] : []),
17
- ...(col.type.precision === undefined ? [] : [`precision: ${col.type.precision}`]),
19
+ ...(writesPrecision(col.type) ? [`precision: ${col.type.precision}`] : []),
18
20
  ...(col.type.precision !== undefined && col.type.scale !== undefined ? [`scale: ${col.type.scale}`] : []),
19
21
  ];
20
22
  },
@@ -36,6 +38,10 @@ const OPTION_SOURCE = {
36
38
  references: null,
37
39
  referencedBy: null,
38
40
  };
41
+ /** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
42
+ function writesPrecision(type) {
43
+ return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);
44
+ }
39
45
  /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
40
46
  export function buildFieldOptionsSource(col, propertyName, indexName) {
41
47
  const context = { propertyName, indexName };
@@ -50,20 +56,22 @@ export function buildFieldOptionsSource(col, propertyName, indexName) {
50
56
  export function enumMembersSource(members) {
51
57
  return members.map((it) => (typeof it === 'number' ? String(it) : quoted(it)));
52
58
  }
53
- /** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
54
- export function fieldNeedsRaw(col) {
55
- return col.generatedAs !== undefined;
59
+ /** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
60
+ export function fieldImports(col) {
61
+ const sql = SqlExpression.isExpression(col.defaultValue) ? [sqlDefaultSource(col.defaultValue).name] : [];
62
+ return [...(col.generatedAs === undefined ? [] : ['raw']), ...sql];
56
63
  }
57
- /** A default value as source, a string single-quoted and escaped, an expression included: `defaultValue: 'now()'`. */
64
+ /** A default value as source code: SQL the way an entity declares it, a string single-quoted and escaped. */
58
65
  function defaultValueSource(value) {
59
- if (typeof value === 'string') {
60
- return quoted(value);
61
- }
62
- if (typeof value === 'boolean' || typeof value === 'number') {
63
- return value.toString();
66
+ if (SqlExpression.isExpression(value)) {
67
+ return sqlDefaultSource(value).source;
64
68
  }
65
- if (value === null) {
66
- return 'null';
67
- }
68
- return JSON.stringify(value);
69
+ return typeof value === 'string' ? quoted(value) : JSON.stringify(value);
70
+ }
71
+ /**
72
+ * A SQL default as an entity declares it, with the name to import for it: the value uql exports by its own
73
+ * name (`currentTimestamp`), and `raw` for any other SQL, as introspection reads it back.
74
+ */
75
+ function sqlDefaultSource({ kind, sql }) {
76
+ return sql === undefined ? { name: kind, source: kind } : { name: 'raw', source: rawTag(sql) };
69
77
  }
@@ -1,20 +1,64 @@
1
1
  import { isVectorIndexType } from '../../type/index.js';
2
- import { memberSource, rawTag } from './sourceLiteral.js';
2
+ import { fulltextConfig } from '../../util/dialect.util.js';
3
+ import { memberSource, quoted, rawTag } from './sourceLiteral.js';
3
4
  /**
4
- * The per-entry modifiers worth writing into an entity, which is not everything introspection reports.
5
- * Postgres states an entry in full - a plain column comes back `order: 'asc', nulls: 'last'` - and
6
- * emitting that would bake one engine's defaults into source that is meant to run on any of them.
7
- * `nulls` never survives for the same reason: it is Postgres-only and always reported.
5
+ * The options each field of an index entry writes into `@Index`, in emit order; `satisfies` forces every new
6
+ * field to be listed. Defaults are skipped: Postgres reports each entry in full (`order: 'asc', nulls: 'last'`
7
+ * on a plain column), and writing that out would bake its defaults into every entity.
8
8
  */
9
- function significantModifiers(entry) {
10
- const parts = [];
11
- if (entry.order === 'desc')
12
- parts.push(`order: 'desc'`);
13
- if (entry.opsClass)
14
- parts.push(`opsClass: '${entry.opsClass}'`);
15
- if (entry.length !== undefined)
16
- parts.push(`length: ${entry.length}`);
17
- return parts;
9
+ const ENTRY_MODIFIER_SOURCE = {
10
+ order: (entry) => (entry.order === 'desc' ? [`order: 'desc'`] : []),
11
+ opsClass: (entry) => (entry.opsClass ? [`opsClass: ${quoted(entry.opsClass)}`] : []),
12
+ length: (entry) => (entry.length === undefined ? [] : [`length: ${entry.length}`]),
13
+ weight: (entry) => ((entry.weight ?? 1) === 1 ? [] : [`weight: ${entry.weight}`]),
14
+ // Never written: only Postgres reports it, and on every entry.
15
+ nulls: null,
16
+ // Written by `indexEntrySource` as the entry itself, ahead of its modifiers.
17
+ column: null,
18
+ expression: null,
19
+ // Never written: introspection reads a JSON entry back as the expression the engine prints for it.
20
+ jsonPath: null,
21
+ jsonArray: null,
22
+ };
23
+ /** Each {@link IndexNode} field's `@Index` options, in emit order; `satisfies` forces a new field to be listed. */
24
+ const INDEX_OPTION_SOURCE = {
25
+ name: (index) => (index.name ? [`name: ${quoted(index.name)}`] : []),
26
+ unique: (index) => (index.unique ? ['unique: true'] : []),
27
+ type: (index) => (writesType(index) ? [`type: '${index.type}'`] : []),
28
+ distance: (index) => (isVectorIndexType(index.type) && index.distance ? [`distance: '${index.distance}'`] : []),
29
+ m: (index) => (index.m === undefined ? [] : [`m: ${index.m}`]),
30
+ efConstruction: (index) => (index.efConstruction === undefined ? [] : [`efConstruction: ${index.efConstruction}`]),
31
+ lists: (index) => (index.lists === undefined ? [] : [`lists: ${index.lists}`]),
32
+ // The default config is skipped: an index without one is built with the default anyway.
33
+ config: (index) => {
34
+ const config = fulltextConfig(index);
35
+ return index.type === 'fulltext' && config !== fulltextConfig({}) ? [`config: ${quoted(config)}`] : [];
36
+ },
37
+ where: (index) => (index.where ? [`where: ${rawTag(index.where)}`] : []),
38
+ include: (index, { param, propertyName }) => {
39
+ const included = index.include?.map((column) => memberSource(param, propertyName(column))) ?? [];
40
+ return included.length ? [`include: (${param}) => [${included.join(', ')}]`] : [];
41
+ },
42
+ // Written as the decorator's first argument, not as an option.
43
+ entries: null,
44
+ // Taken from the indexed field, never declared on the index.
45
+ vectorType: null,
46
+ dimensions: null,
47
+ // A link back to the table node in the schema graph, not an option.
48
+ table: null,
49
+ };
50
+ /**
51
+ * Whether to write the index's type. `btree` is skipped: it is every engine's default and reported on every
52
+ * index. So is a vector type whose distance introspection could not recover, since `@Index` requires a
53
+ * `distance` beside a vector type and would not compile without one.
54
+ */
55
+ function writesType(index) {
56
+ return (index.type !== undefined &&
57
+ index.type !== 'btree' &&
58
+ (!isVectorIndexType(index.type) || index.distance !== undefined));
59
+ }
60
+ function entryModifiers(entry) {
61
+ return Object.values(ENTRY_MODIFIER_SOURCE).flatMap((source) => source?.(entry) ?? []);
18
62
  }
19
63
  /**
20
64
  * Whether `@Field({ index })` can carry the whole index. It says only "this column is indexed under
@@ -32,7 +76,7 @@ export function isPlainFieldIndex(index) {
32
76
  // Postgres names an access method on every index, so the default one still counts as plain.
33
77
  (index.type === undefined || index.type === 'btree') &&
34
78
  !index.include?.length &&
35
- significantModifiers(entry).length === 0);
79
+ entryModifiers(entry).length === 0);
36
80
  }
37
81
  /**
38
82
  * One `@Index((user) => [...])` as source, for an index no `@Field` can express, its columns read off the
@@ -40,38 +84,17 @@ export function isPlainFieldIndex(index) {
40
84
  * {@link indexNeedsRaw} holds.
41
85
  */
42
86
  export function buildIndexDecoratorSource(index, propertyName, param) {
43
- const entries = index.entries.map((entry) => indexEntrySource(entry, propertyName, param)).join(', ');
44
- // `@Index` requires a `distance` beside a vector `type`, as the introspector reads it back.
45
- const isVector = isVectorIndexType(index.type);
46
- const distance = isVector ? index.distance : undefined;
47
- const options = [];
48
- if (index.name)
49
- options.push(`name: '${index.name}'`);
50
- if (index.unique)
51
- options.push('unique: true');
52
- // `btree` is every engine's default and is reported on every index, so writing it out would put it
53
- // in every generated entity. A vector type whose metric could not be recovered is left off too,
54
- // rather than written out in a form that does not compile.
55
- const writesType = index.type !== undefined && index.type !== 'btree' && (distance !== undefined || !isVector);
56
- if (writesType) {
57
- options.push(`type: '${index.type}'`);
58
- }
59
- if (distance)
60
- options.push(`distance: '${distance}'`);
61
- if (index.where)
62
- options.push(`where: ${rawTag(index.where)}`);
63
- if (index.include?.length) {
64
- const included = index.include.map((column) => memberSource(param, propertyName(column)));
65
- options.push(`include: (${param}) => [${included.join(', ')}]`);
66
- }
87
+ const context = { param, propertyName };
88
+ const entries = index.entries.map((entry) => indexEntrySource(entry, context)).join(', ');
89
+ const options = Object.values(INDEX_OPTION_SOURCE).flatMap((source) => source?.(index, context) ?? []);
67
90
  return `@Index((${param}) => [${entries}]${options.length > 0 ? `, { ${options.join(', ')} }` : ''})`;
68
91
  }
69
92
  /** Whether emitting this index needs `raw` imported alongside `Index`. */
70
93
  export function indexNeedsRaw(index) {
71
94
  return Boolean(index.where) || index.entries.some((entry) => entry.expression);
72
95
  }
73
- function indexEntrySource(entry, propertyName, param) {
96
+ function indexEntrySource(entry, { param, propertyName }) {
74
97
  const column = entry.expression ? rawTag(entry.column) : memberSource(param, propertyName(entry.column));
75
- const modifiers = significantModifiers(entry);
98
+ const modifiers = entryModifiers(entry);
76
99
  return modifiers.length === 0 ? column : `{ column: ${column}, ${modifiers.join(', ')} }`;
77
100
  }
@@ -0,0 +1,31 @@
1
+ import type { AbstractSqlDialect } from '../../dialect/index.js';
2
+ import { SqlExpression } from '../../schema/sqlExpression.js';
3
+ import { type SqlDialectName } from '../../type/index.js';
4
+ /** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
5
+ export type DialectDefaults = {
6
+ /** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
7
+ readonly wrapTypes?: RegExp;
8
+ /** Column types whose clock default must repeat their precision, captured by the pattern. */
9
+ readonly preciseTypes?: RegExp;
10
+ };
11
+ /**
12
+ * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query bundle - the
13
+ * same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`.
14
+ */
15
+ export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
16
+ /**
17
+ * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
18
+ * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
19
+ * the result needs wrapping, which MySQL demands on its large types whatever the value.
20
+ */
21
+ export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
22
+ /**
23
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
24
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
25
+ */
26
+ export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
27
+ /**
28
+ * Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
29
+ * compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
30
+ */
31
+ export declare function knownDefault(expression: SqlExpression, dialect: AbstractSqlDialect): SqlExpression;