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
@@ -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 { columnForeignKey, columnIndex, indexDefinition } from '../generator/definitionToNode.js';
9
9
  import { ColumnBuilder } from './columnBuilder.js';
10
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);
@@ -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,15 +80,12 @@ 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');
88
88
  }
89
- if (isFilledColumn(col)) {
90
- uqlImports.add('type Filled');
91
- }
92
89
  }
93
90
  // Check for relation decorators
94
91
  if (this.options.includeRelations) {
@@ -353,8 +350,8 @@ export class EntityCodeGenerator {
353
350
  }
354
351
  /**
355
352
  * A column's property as source, declared the way every read and insert types it: present (`!`) where
356
- * the column is NOT NULL, `Filled` where a default fills it (a single-column key stays `!`, which an insert
357
- * leaves out anyway), `| null` where it holds NULL, `readonly` where the database computes it.
353
+ * the column is NOT NULL, left out of an insert (`?`) where a default fills it (a single-column key stays
354
+ * `!`, which an insert leaves out anyway), `| null` where it holds NULL, `readonly` where the database computes it.
358
355
  */
359
356
  function propertySource(col, propertyName) {
360
357
  const type = col.enum
@@ -366,11 +363,8 @@ function propertySource(col, propertyName) {
366
363
  if (col.nullable && !col.isPrimaryKey) {
367
364
  return `${written}${propertyName}?: ${type} | null`;
368
365
  }
369
- return `${written}${propertyName}!: ${isFilledColumn(col) ? `Filled<${type}>` : type}`;
370
- }
371
- /** A non-null column its default fills, which every read has and an insert may leave out. */
372
- function isFilledColumn(col) {
373
- return !col.nullable && !col.isPrimaryKey && col.generatedAs === undefined && col.defaultValue !== undefined;
366
+ const filled = !col.isPrimaryKey && col.defaultValue !== undefined;
367
+ return `${written}${propertyName}${filled ? '?' : '!'}: ${type}`;
374
368
  }
375
369
  /**
376
370
  * Create an EntityCodeGenerator from SchemaAST.
@@ -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
@@ -19,10 +19,7 @@ export function entityTypesSource(entities) {
19
19
  ];
20
20
  return `export interface ${names.get(meta.entity)} {\n${members.join('\n')}\n}`;
21
21
  });
22
- const imports = metas.some((meta) => Object.values(meta.fields).some((field) => field && isFilledField(field)))
23
- ? ["import type { Filled } from 'uql-orm';", '']
24
- : [];
25
- return ['// Generated by `uql-migrate types`. Do not edit.', '', ...imports, ...interfaces, ''].join('\n');
22
+ return ['// Generated by `uql-migrate types`. Do not edit.', '', ...interfaces, ''].join('\n');
26
23
  }
27
24
  /**
28
25
  * One interface name per entity, settled before anything is written so a relation and its target
@@ -53,8 +50,8 @@ function propertyName(key) {
53
50
  }
54
51
  /**
55
52
  * A field as an entity class declares it: required where every read has it and an insert names it, a
56
- * key included, which an insert leaves out anyway; `Filled` where a default fills it; optional where a
57
- * read skips it (`eager: false`); `| null` where the column holds NULL; `readonly` where it is computed.
53
+ * key included, which an insert leaves out anyway; optional where a default fills it or a read skips it
54
+ * (`eager: false`); `| null` where the column holds NULL; `readonly` where the database computes it.
58
55
  */
59
56
  function fieldMember(key, field) {
60
57
  const type = fieldType(field);
@@ -62,24 +59,13 @@ function fieldMember(key, field) {
62
59
  if (!field) {
63
60
  return ` ${name}?: ${type};`;
64
61
  }
65
- if (isFilledField(field)) {
66
- return ` ${name}: Filled<${type}>;`;
67
- }
68
62
  const written = field.computed === undefined ? '' : 'readonly ';
69
- if (!field.isId && field.nullable !== false) {
63
+ if (!declaresNotNull(field)) {
70
64
  return ` ${written}${name}?: ${type} | null;`;
71
65
  }
72
- const optional = !field.isId && field.eager === false;
66
+ const optional = !field.isId && (field.defaultValue !== undefined || field.onInsert !== undefined || field.eager === false);
73
67
  return ` ${written}${name}${optional ? '?' : ''}: ${type};`;
74
68
  }
75
- /** A non-null field a default or `onInsert` fills, which every read has and an insert may leave out. */
76
- function isFilledField(field) {
77
- return (!field.isId &&
78
- field.nullable === false &&
79
- field.eager !== false &&
80
- field.computed === undefined &&
81
- (field.defaultValue !== undefined || field.onInsert !== undefined));
82
- }
83
69
  /**
84
70
  * The property type a column reads back as, resolved the way the DDL resolves it - so a foreign key
85
71
  * reports the type of the key it points at rather than the fallback its own options carry.
@@ -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,5 +1,8 @@
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';
5
+ import { UqlUsageError } from '../../util/uqlError.js';
3
6
  import { quoted, rawTag } from './sourceLiteral.js';
4
7
  /** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
5
8
  const OPTION_SOURCE = {
@@ -14,7 +17,7 @@ const OPTION_SOURCE = {
14
17
  `type: ${quoted(columnType)}`,
15
18
  ...(col.type.length && col.type.category === 'string' ? [`length: ${col.type.length}`] : []),
16
19
  ...(col.type.length && isVectorCategory(col.type.category) ? [`dimensions: ${col.type.length}`] : []),
17
- ...(col.type.precision === undefined ? [] : [`precision: ${col.type.precision}`]),
20
+ ...(writesPrecision(col.type) ? [`precision: ${col.type.precision}`] : []),
18
21
  ...(col.type.precision !== undefined && col.type.scale !== undefined ? [`scale: ${col.type.scale}`] : []),
19
22
  ];
20
23
  },
@@ -36,6 +39,10 @@ const OPTION_SOURCE = {
36
39
  references: null,
37
40
  referencedBy: null,
38
41
  };
42
+ /** Whether to write `type`'s precision: not for a timestamp at a `Date`'s milliseconds, its default. */
43
+ function writesPrecision(type) {
44
+ return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);
45
+ }
39
46
  /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
40
47
  export function buildFieldOptionsSource(col, propertyName, indexName) {
41
48
  const context = { propertyName, indexName };
@@ -50,20 +57,28 @@ export function buildFieldOptionsSource(col, propertyName, indexName) {
50
57
  export function enumMembersSource(members) {
51
58
  return members.map((it) => (typeof it === 'number' ? String(it) : quoted(it)));
52
59
  }
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;
60
+ /** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
61
+ export function fieldImports(col) {
62
+ const sql = SqlExpression.isExpression(col.defaultValue) ? [sqlDefaultSource(col.defaultValue).name] : [];
63
+ return [...(col.generatedAs === undefined ? [] : ['raw']), ...sql];
56
64
  }
57
- /** A default value as source, a string single-quoted and escaped, an expression included: `defaultValue: 'now()'`. */
65
+ /** A default value as source code: SQL the way an entity declares it, a string single-quoted and escaped. */
58
66
  function defaultValueSource(value) {
59
- if (typeof value === 'string') {
60
- return quoted(value);
67
+ if (SqlExpression.isExpression(value)) {
68
+ return sqlDefaultSource(value).source;
61
69
  }
62
- if (typeof value === 'boolean' || typeof value === 'number') {
63
- return value.toString();
70
+ return typeof value === 'string' ? quoted(value) : JSON.stringify(value);
71
+ }
72
+ /**
73
+ * A SQL default as an entity declares it, with the name to import for it: `currentTimestamp` for the
74
+ * current timestamp, and `raw` for any other SQL, as introspection reads it back.
75
+ */
76
+ function sqlDefaultSource(value) {
77
+ if (value.kind === 'now') {
78
+ return { name: 'currentTimestamp', source: 'currentTimestamp' };
64
79
  }
65
- if (value === null) {
66
- return 'null';
80
+ if (value.sql === undefined) {
81
+ throw new UqlUsageError(`an entity declares a SQL default as raw or currentTimestamp, and '${value.kind}' is neither`);
67
82
  }
68
- return JSON.stringify(value);
83
+ return { name: 'raw', source: rawTag(value.sql) };
69
84
  }
@@ -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
  }
@@ -5,12 +5,10 @@ export { IndexDdl } from './indexDdl.js';
5
5
  export { MsSqlIndexDdl } from './mssqlIndexDdl.js';
6
6
  export { MsSqlTableDdl } from './mssqlTableDdl.js';
7
7
  export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
8
+ export { MySqlTableDdl } from './mysqlTableDdl.js';
8
9
  export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
10
+ export { PgTableDdl } from './pgTableDdl.js';
9
11
  export { SqliteIndexDdl } from './sqliteIndexDdl.js';
10
12
  export { TableDdl } from './tableDdl.js';
11
13
  export declare function indexDdlFor(dialect: AbstractSqlDialect): IndexDdl;
12
- /**
13
- * The table DDL a dialect gets: SQL Server's, or the portable form every other engine takes. By
14
- * `dialectName`, which a subclass inherits too, so this entry need not carry the dialect itself.
15
- */
16
14
  export declare function tableDdlFor(dialect: AbstractSqlDialect): TableDdl;
@@ -2,14 +2,18 @@ import { IndexDdl } from './indexDdl.js';
2
2
  import { MsSqlIndexDdl } from './mssqlIndexDdl.js';
3
3
  import { MsSqlTableDdl } from './mssqlTableDdl.js';
4
4
  import { MariaIndexDdl, MySqlIndexDdl } from './mysqlIndexDdl.js';
5
+ import { MySqlTableDdl } from './mysqlTableDdl.js';
5
6
  import { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
7
+ import { PgTableDdl } from './pgTableDdl.js';
6
8
  import { SqliteIndexDdl } from './sqliteIndexDdl.js';
7
9
  import { TableDdl } from './tableDdl.js';
8
10
  export { IndexDdl } from './indexDdl.js';
9
11
  export { MsSqlIndexDdl } from './mssqlIndexDdl.js';
10
12
  export { MsSqlTableDdl } from './mssqlTableDdl.js';
11
13
  export { MariaIndexDdl, MySqlIndexDdl, MysqlLikeIndexDdl } from './mysqlIndexDdl.js';
14
+ export { MySqlTableDdl } from './mysqlTableDdl.js';
12
15
  export { CockroachIndexDdl, PgIndexDdl } from './pgIndexDdl.js';
16
+ export { PgTableDdl } from './pgTableDdl.js';
13
17
  export { SqliteIndexDdl } from './sqliteIndexDdl.js';
14
18
  export { TableDdl } from './tableDdl.js';
15
19
  /**
@@ -27,10 +31,15 @@ const INDEX_DDL = {
27
31
  export function indexDdlFor(dialect) {
28
32
  return new INDEX_DDL[dialect.dialectName](dialect);
29
33
  }
30
- /**
31
- * The table DDL a dialect gets: SQL Server's, or the portable form every other engine takes. By
32
- * `dialectName`, which a subclass inherits too, so this entry need not carry the dialect itself.
33
- */
34
+ /** Each engine's table DDL, keyed by `dialectName` and exhaustive, for the same reasons as {@link INDEX_DDL}. */
35
+ const TABLE_DDL = {
36
+ postgres: PgTableDdl,
37
+ cockroachdb: PgTableDdl,
38
+ mysql: MySqlTableDdl,
39
+ mariadb: MySqlTableDdl,
40
+ mssql: MsSqlTableDdl,
41
+ sqlite: TableDdl,
42
+ };
34
43
  export function tableDdlFor(dialect) {
35
- return dialect.dialectName === 'mssql' ? new MsSqlTableDdl(dialect) : new TableDdl(dialect);
44
+ return new TABLE_DDL[dialect.dialectName](dialect);
36
45
  }
@@ -19,6 +19,7 @@ export declare class MsSqlTableDdl extends TableDdl {
19
19
  alterColumn(table: string, column: ColumnSchema): string[];
20
20
  renameColumn(table: string, oldName: string, newName: string): string;
21
21
  renameTable(oldName: string, newName: string): string;
22
+ dropIndex(table: string, index: string): string;
22
23
  storedGeneratedColumn(_type: string, expression: string): string;
23
24
  /** One statement, so a split on `;` cannot part the lookup from the `EXEC` it feeds. */
24
25
  private dropPinning;
@@ -1,5 +1,5 @@
1
1
  import { escapeSingleQuotes } from '../../util/sqlLiteral.js';
2
- import { sizedType, TableDdl } from './tableDdl.js';
2
+ import { dropIndexOnTable, sizedType, TableDdl } from './tableDdl.js';
3
3
  /** What pins column `c`, the `sys.columns` row {@link MsSqlTableDdl} reads: each constraint, then each index, by kind. */
4
4
  const PINNED_BY = {
5
5
  default: /*sql*/ `SELECT d.name, 0 AS is_index FROM sys.default_constraints d
@@ -56,6 +56,9 @@ export class MsSqlTableDdl extends TableDdl {
56
56
  renameTable(oldName, newName) {
57
57
  return /*sql*/ `EXEC sp_rename ${this.dialect.escape(this.dialect.escapeId(oldName))}, ${this.dialect.escape(newName)};`;
58
58
  }
59
+ dropIndex(table, index) {
60
+ return dropIndexOnTable(this.dialect, table, index);
61
+ }
59
62
  storedGeneratedColumn(_type, expression) {
60
63
  return /*sql*/ `AS (${expression}) PERSISTED`;
61
64
  }
@@ -0,0 +1,17 @@
1
+ import type { ColumnSchema } from '../../type/index.js';
2
+ import { TableDdl } from './tableDdl.js';
3
+ /** Table DDL for the MySQL family: `MODIFY COLUMN`, and dedicated clauses to drop a primary key or foreign key. */
4
+ export declare class MySqlTableDdl extends TableDdl {
5
+ readonly tableOptions = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
6
+ /**
7
+ * MySQL fills existing rows with a zero when it adds a required column that has no default. So the column
8
+ * is added nullable and then made required, which fails on those rows as it does on other engines.
9
+ */
10
+ addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
11
+ alterColumn(table: string, _column: ColumnSchema, definition: string): string[];
12
+ /** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
13
+ dropIndex(table: string, index: string): string;
14
+ dropForeignKey(table: string, constraint: string): string;
15
+ /** MySQL always names the primary key `PRIMARY`, so it is dropped without a name. */
16
+ dropPrimaryKey(table: string): string;
17
+ }
@@ -0,0 +1,33 @@
1
+ import { lacksValue } from '../schemaChange.js';
2
+ import { dropIndexOnTable, TableDdl } from './tableDdl.js';
3
+ /** Table DDL for the MySQL family: `MODIFY COLUMN`, and dedicated clauses to drop a primary key or foreign key. */
4
+ export class MySqlTableDdl extends TableDdl {
5
+ tableOptions = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4';
6
+ /**
7
+ * MySQL fills existing rows with a zero when it adds a required column that has no default. So the column
8
+ * is added nullable and then made required, which fails on those rows as it does on other engines.
9
+ */
10
+ addColumnStatements(table, column, render) {
11
+ if (!lacksValue(column)) {
12
+ return super.addColumnStatements(table, column, render);
13
+ }
14
+ return [
15
+ this.addColumn(table, render({ ...column, nullable: true })),
16
+ ...this.alterColumn(table, column, render(column)),
17
+ ];
18
+ }
19
+ alterColumn(table, _column, definition) {
20
+ return [`ALTER TABLE ${this.dialect.escapeId(table)} MODIFY COLUMN ${definition};`];
21
+ }
22
+ /** Ignores `schema`: MySQL reads it from the table name, which is already qualified. */
23
+ dropIndex(table, index) {
24
+ return dropIndexOnTable(this.dialect, table, index);
25
+ }
26
+ dropForeignKey(table, constraint) {
27
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP FOREIGN KEY ${this.dialect.escapeId(constraint)};`;
28
+ }
29
+ /** MySQL always names the primary key `PRIMARY`, so it is dropped without a name. */
30
+ dropPrimaryKey(table) {
31
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP PRIMARY KEY;`;
32
+ }
33
+ }
@@ -0,0 +1,7 @@
1
+ import type { ColumnSchema } from '../../type/index.js';
2
+ import { TableDdl } from './tableDdl.js';
3
+ /** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
4
+ export declare class PgTableDdl extends TableDdl {
5
+ /** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
6
+ alterColumn(table: string, column: ColumnSchema, _definition: string, from?: ColumnSchema): string[];
7
+ }
@@ -0,0 +1,17 @@
1
+ import { sameDefault } from '../builder/expressions.js';
2
+ import { TableDdl } from './tableDdl.js';
3
+ /** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
4
+ export class PgTableDdl extends TableDdl {
5
+ /** A clause for each part that differs from `from`, the column as it was, or for every part without it. */
6
+ alterColumn(table, column, _definition, from) {
7
+ const name = this.dialect.escapeId(column.name);
8
+ const alter = `ALTER TABLE ${this.dialect.escapeId(table)} ALTER COLUMN ${name}`;
9
+ return [
10
+ // Casts explicitly: Postgres converts on its own only between compatible types, and text to integer is not.
11
+ (!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type};`,
12
+ (!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`,
13
+ (!from || !sameDefault(column.defaultValue, from.defaultValue, this.dialect)) &&
14
+ (column.defaultValue === undefined ? `${alter} DROP DEFAULT;` : `${alter} SET${this.defaultClause(column)};`),
15
+ ].filter((statement) => statement !== false);
16
+ }
17
+ }
@@ -6,29 +6,32 @@ import type { ColumnSchema } from '../../type/index.js';
6
6
  */
7
7
  export declare function sizedType(column: Pick<ColumnSchema, 'type' | 'length' | 'precision' | 'scale'>): string;
8
8
  /**
9
- * The `ALTER TABLE` statements an engine spells its own way: the migrator's, for the reason
10
- * {@link IndexDdl} is. The form here is the portable one; SQL Server's is {@link MsSqlTableDdl}.
9
+ * Table DDL that engines spell differently. Like {@link IndexDdl}, it belongs to the migrator, so no runtime
10
+ * entry carries it. This class holds the portable form, which SQLite takes; other families override what differs.
11
11
  */
12
12
  export declare class TableDdl {
13
13
  protected readonly dialect: AbstractSqlDialect;
14
14
  constructor(dialect: AbstractSqlDialect);
15
+ /** Options appended to `CREATE TABLE`, such as MySQL's engine; empty by default. */
16
+ readonly tableOptions: string;
15
17
  /** A `CREATE TABLE` up to its column list, a no-op where `ifNotExists` and the table is already there. */
16
18
  createTable(target: string, ifNotExists: boolean): string;
17
19
  addColumn(table: string, definition: string): string;
18
- /**
19
- * `column` added, spelled by `render`. MySQL fills a zero into the rows already there for a required
20
- * column with no default, so there it is added nullable and required after, failing on them as elsewhere.
21
- */
20
+ /** The statements that add `column`, whose definition `render` writes. */
22
21
  addColumnStatements(table: string, column: ColumnSchema, render: (column: ColumnSchema) => string): string[];
23
22
  dropColumn(table: string, column: string): string[];
24
23
  /**
25
- * What changes `column` to what it now declares. `definition` is the whole column, which MySQL's
26
- * `MODIFY COLUMN` restates; Postgres takes each change as a clause of its own, so given what the
27
- * column was (`from`), only the clauses that changed.
24
+ * The statements that change a column from `from`, what it was, to `column`, what it now declares.
25
+ * `definition` is the complete new column definition.
28
26
  */
29
- alterColumn(table: string, column: ColumnSchema, definition: string, from?: ColumnSchema): string[];
27
+ alterColumn(table: string, _column: ColumnSchema, definition: string, _from?: ColumnSchema): string[];
30
28
  renameColumn(table: string, oldName: string, newName: string): string;
31
29
  renameTable(oldName: string, newName: string): string;
30
+ /** `schema` is the table's schema, which also holds its indexes. */
31
+ dropIndex(table: string, index: string, schema?: string): string;
32
+ dropForeignKey(table: string, constraint: string): string;
33
+ /** Drops the primary key by its real constraint name: the introspected one, or the one uql derived when adding it. */
34
+ dropPrimaryKey(table: string, constraint?: string): string;
32
35
  /** A stored generated column's type, with the clause computing it. */
33
36
  storedGeneratedColumn(type: string, expression: string): string;
34
37
  /**
@@ -40,3 +43,5 @@ export declare class TableDdl {
40
43
  readonly type: string;
41
44
  }): string;
42
45
  }
46
+ /** `DROP INDEX <index> ON <table>`, for engines that scope index names per table: MySQL and SQL Server. */
47
+ export declare function dropIndexOnTable(dialect: AbstractSqlDialect, table: string, index: string): string;