uql-orm 0.91.1 → 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 +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 +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 +3 -3
  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 +21 -10
  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,88 +3,73 @@
3
3
  *
4
4
  * Fluent API for defining columns in migrations.
5
5
  */
6
+ import { DEFAULT_FOREIGN_KEY_ACTION } from '../../schema/types.js';
6
7
  /**
7
- * Builder for column definitions with a fluent API.
8
- * Columns are NOT NULL by default (safer).
8
+ * Builder for column definitions with a fluent API. Each call replaces the definition it holds, and `build`
9
+ * returns it. Columns are NOT NULL by default (safer).
9
10
  */
10
11
  export class ColumnBuilder {
11
- _name;
12
- _type;
13
- _nullable;
14
- _defaultValue;
15
- _primaryKey;
16
- _autoIncrement;
17
- _unique;
18
- _enum;
19
- _generatedAs;
20
- _comment;
21
- _index;
22
- _foreignKey;
12
+ column;
23
13
  constructor(name, type, options = {}) {
24
- this._name = name;
25
- this._type = type;
26
- // Apply options with defaults (non-nullable by default)
27
- this._nullable = options.nullable ?? false;
28
- this._unique = options.unique ?? false;
29
- this._primaryKey = options.primaryKey ?? false;
30
- this._autoIncrement = options.autoIncrement ?? false;
31
- this._defaultValue = options.defaultValue;
32
- this._index = options.index;
33
- this._comment = options.comment;
34
- if (options.unsigned !== undefined) {
35
- this._type = { ...this._type, unsigned: options.unsigned };
36
- }
37
- // Handle inline references option
38
- if (options.references) {
39
- this._foreignKey = {
40
- references: { table: options.references.table, columns: [options.references.column ?? 'id'] },
41
- onDelete: options.references.onDelete ?? 'NO ACTION',
42
- onUpdate: options.references.onUpdate ?? 'NO ACTION',
43
- };
44
- }
14
+ const { references } = options;
15
+ this.column = {
16
+ name,
17
+ type: options.unsigned === undefined ? type : { ...type, unsigned: options.unsigned },
18
+ nullable: options.nullable ?? false,
19
+ defaultValue: options.defaultValue,
20
+ isPrimaryKey: options.primaryKey ?? false,
21
+ isAutoIncrement: options.autoIncrement ?? false,
22
+ isUnique: options.unique ?? false,
23
+ enum: undefined,
24
+ generatedAs: undefined,
25
+ comment: options.comment,
26
+ index: options.index,
27
+ foreignKey: references && {
28
+ references: { table: references.table, columns: [references.column ?? 'id'] },
29
+ onDelete: references.onDelete ?? DEFAULT_FOREIGN_KEY_ACTION,
30
+ onUpdate: references.onUpdate ?? DEFAULT_FOREIGN_KEY_ACTION,
31
+ },
32
+ };
33
+ }
34
+ set(change) {
35
+ this.column = { ...this.column, ...change };
36
+ return this;
45
37
  }
46
38
  /**
47
39
  * Make the column nullable or not nullable.
48
40
  */
49
41
  nullable(value = true) {
50
- this._nullable = value;
51
- return this;
42
+ return this.set({ nullable: value });
52
43
  }
53
44
  /**
54
45
  * Make the column NOT NULL.
55
46
  */
56
47
  notNullable() {
57
- this._nullable = false;
58
- return this;
48
+ return this.set({ nullable: false });
59
49
  }
60
50
  /**
61
51
  * Set a default value for the column.
62
52
  */
63
53
  defaultValue(value) {
64
- this._defaultValue = value;
65
- return this;
54
+ return this.set({ defaultValue: value });
66
55
  }
67
56
  /**
68
57
  * Mark as primary key.
69
58
  */
70
59
  primaryKey() {
71
- this._primaryKey = true;
72
- this._nullable = false;
73
- return this;
60
+ return this.set({ isPrimaryKey: true, nullable: false });
74
61
  }
75
62
  /**
76
63
  * Enable auto-increment (for integer types).
77
64
  */
78
65
  autoIncrement() {
79
- this._autoIncrement = true;
80
- return this;
66
+ return this.set({ isAutoIncrement: true });
81
67
  }
82
68
  /**
83
69
  * Add a unique constraint.
84
70
  */
85
71
  unique() {
86
- this._unique = true;
87
- return this;
72
+ return this.set({ isUnique: true });
88
73
  }
89
74
  /**
90
75
  * Make the column one the database computes: `GENERATED ALWAYS AS (<sql>) STORED`.
@@ -93,85 +78,64 @@ export class ColumnBuilder {
93
78
  * a check expression and a partial-index predicate do.
94
79
  */
95
80
  computed(sql) {
96
- this._generatedAs = sql;
97
- return this;
81
+ return this.set({ generatedAs: sql });
98
82
  }
99
83
  /**
100
84
  * Constrain the column to these values, as a `CHECK (col IN (...))` - what `@Field({ enum })` emits.
101
85
  */
102
86
  enum(values) {
103
- this._enum = values;
104
- return this;
87
+ return this.set({ enum: values });
105
88
  }
106
89
  /**
107
90
  * Add a comment to the column.
108
91
  */
109
92
  comment(text) {
110
- this._comment = text;
111
- return this;
93
+ return this.set({ comment: text });
112
94
  }
113
95
  /**
114
96
  * Add an index on this column.
115
97
  * @param name - Optional index name. If true, auto-generates name.
116
98
  */
117
99
  index(name) {
118
- this._index = name ?? true;
119
- return this;
100
+ return this.set({ index: name ?? true });
120
101
  }
121
102
  /**
122
103
  * Set as unsigned (MySQL/MariaDB).
123
104
  */
124
105
  unsigned() {
125
- this._type = { ...this._type, unsigned: true };
126
- return this;
106
+ return this.set({ type: { ...this.column.type, unsigned: true } });
127
107
  }
128
108
  /**
129
109
  * Add a foreign key reference.
130
110
  * Returns a ForeignKeyBuilder for additional options.
131
111
  */
132
112
  references(table, column = 'id') {
133
- this._foreignKey = {
134
- references: { table, columns: [column] },
135
- onDelete: 'NO ACTION',
136
- onUpdate: 'NO ACTION',
137
- };
138
- return this;
113
+ return this.set({
114
+ foreignKey: {
115
+ references: { table, columns: [column] },
116
+ onDelete: DEFAULT_FOREIGN_KEY_ACTION,
117
+ onUpdate: DEFAULT_FOREIGN_KEY_ACTION,
118
+ },
119
+ });
139
120
  }
140
121
  /**
141
122
  * Set ON DELETE action for foreign key.
142
123
  */
143
124
  onDelete(action) {
144
- if (this._foreignKey) {
145
- this._foreignKey = { ...this._foreignKey, onDelete: action };
146
- }
147
- return this;
125
+ const { foreignKey } = this.column;
126
+ return foreignKey ? this.set({ foreignKey: { ...foreignKey, onDelete: action } }) : this;
148
127
  }
149
128
  /**
150
129
  * Set ON UPDATE action for foreign key.
151
130
  */
152
131
  onUpdate(action) {
153
- if (this._foreignKey) {
154
- this._foreignKey = { ...this._foreignKey, onUpdate: action };
155
- }
156
- return this;
132
+ const { foreignKey } = this.column;
133
+ return foreignKey ? this.set({ foreignKey: { ...foreignKey, onUpdate: action } }) : this;
157
134
  }
158
135
  /**
159
136
  * Build and return the column definition.
160
137
  */
161
138
  build() {
162
- return {
163
- name: this._name,
164
- type: this._type,
165
- nullable: this._nullable,
166
- defaultValue: this._defaultValue,
167
- isPrimaryKey: this._primaryKey,
168
- isAutoIncrement: this._autoIncrement,
169
- isUnique: this._unique,
170
- enum: this._enum,
171
- generatedAs: this._generatedAs,
172
- comment: this._comment,
173
- index: this._index,
174
- foreignKey: this._foreignKey,
175
- };
139
+ return this.column;
176
140
  }
177
141
  }
@@ -1,12 +1,14 @@
1
1
  import type { AbstractSqlDialect } from '../../dialect/index.js';
2
+ import { SqlExpression, type SqlExpressionKind } from '../../schema/sqlExpression.js';
2
3
  import type { SqlDialectName } from '../../type/index.js';
4
+ export { SqlExpression, type SqlExpressionKind };
3
5
  /**
4
- * A {@link ColumnSchema.defaultValue} that is SQL rather than a literal. Kinds are symbolic: the
5
- * dialect names the spelling and {@link formatDefaultValue} renders one at DDL time.
6
+ * Each kind's DDL spelling, or `null` where the engine has none. `raw` carries its own SQL instead. `now`
7
+ * defaults to the dialect's `currentTimestamp`, the clock every other statement reads, unless set here.
6
8
  */
7
- export type SqlExpressionKind = 'now' | 'currentDate' | 'currentTime' | 'uuid' | 'uuidv7' | 'onUpdateNow' | 'raw';
8
- /** Every kind's DDL spelling, `null` where an engine has none. `raw` carries its own text instead. */
9
- export type SqlExpressionMap = Readonly<Record<Exclude<SqlExpressionKind, 'raw'>, string | null>>;
9
+ export type SqlExpressionMap = Readonly<Record<Exclude<SqlExpressionKind, 'raw' | 'now'>, string | null>> & {
10
+ readonly now?: string;
11
+ };
10
12
  /** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
11
13
  export type DialectDefaults = {
12
14
  /** Spelling of each kind, `null` where the engine has none. */
@@ -18,22 +20,11 @@ export type DialectDefaults = {
18
20
  };
19
21
  /**
20
22
  * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
21
- * bundle - the same split that keeps `CANONICAL_TO_SQL` in `schema/canonicalType.ts`. `uuidv7()` is
23
+ * bundle - the same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`. `uuidv7()` is
22
24
  * Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
23
25
  * not being knowable here.
24
26
  */
25
27
  export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
26
- /**
27
- * A DDL default that is SQL rather than a literal. A class, not a plain object, so a JSON default
28
- * cannot masquerade as one: `defaultValue` accepts `unknown`.
29
- */
30
- export declare class SqlExpression {
31
- readonly kind: SqlExpressionKind;
32
- readonly sql?: string | undefined;
33
- /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
34
- constructor(kind: SqlExpressionKind, sql?: string | undefined);
35
- static isExpression(value: unknown): value is SqlExpression;
36
- }
37
28
  /**
38
29
  * Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
39
30
  * `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
@@ -65,5 +56,8 @@ export declare const expr: {
65
56
  * the result needs wrapping, which MySQL demands on its large types whatever the value.
66
57
  */
67
58
  export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
68
- /** Whether a stored default is the declared one, as the engine reprints it: `'a'::character varying` is `'a'`. */
59
+ /**
60
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
61
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
62
+ */
69
63
  export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
@@ -1,6 +1,7 @@
1
+ import { SqlExpression, writtenDefault } from '../../schema/sqlExpression.js';
1
2
  import { UqlUsageError } from '../../util/uqlError.js';
3
+ export { SqlExpression };
2
4
  const ANSI = {
3
- now: 'CURRENT_TIMESTAMP',
4
5
  currentDate: 'CURRENT_DATE',
5
6
  currentTime: 'CURRENT_TIME',
6
7
  uuid: null,
@@ -10,6 +11,8 @@ const ANSI = {
10
11
  const PG = { ...ANSI, uuid: 'gen_random_uuid()' };
11
12
  const MYSQL = {
12
13
  ...ANSI,
14
+ // Bare, unlike the dialect's `CURRENT_TIMESTAMP(3)`: `preciseTypes` adds the column's own precision.
15
+ now: 'CURRENT_TIMESTAMP',
13
16
  uuid: 'UUID()',
14
17
  onUpdateNow: 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
15
18
  };
@@ -19,7 +22,7 @@ const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY
19
22
  const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
20
23
  /**
21
24
  * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query
22
- * bundle - the same split that keeps `CANONICAL_TO_SQL` in `schema/canonicalType.ts`. `uuidv7()` is
25
+ * bundle - the same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`. `uuidv7()` is
23
26
  * Postgres 18+ and `UUID_v7()` MariaDB 11.7+; a server below those rejects it itself, the version
24
27
  * not being knowable here.
25
28
  */
@@ -32,29 +35,13 @@ export const DIALECT_DEFAULTS = {
32
35
  wrapTypes: MYSQL_LARGE_TYPES,
33
36
  preciseTypes: MYSQL_PRECISE_TYPES,
34
37
  },
35
- sqlite: { expressions: ANSI },
36
- // `SYSUTCDATETIME()` over `CURRENT_TIMESTAMP`, which is local time in the server's zone. No
37
- // `uuidv7`: `NEWSEQUENTIALID()` is an ordered v4 GUID, so it carries no readable timestamp and
38
+ // Writes today in the same text as a bound `Date` at UTC midnight; `CURRENT_DATE` writes a different text.
39
+ sqlite: { expressions: { ...ANSI, currentDate: "(strftime('%Y-%m-%d 00:00:00.000', 'now'))" } },
40
+ // No `uuidv7`: `NEWSEQUENTIALID()` is an ordered v4 GUID, so it carries no readable timestamp and
38
41
  // does not sort the way a v7 does elsewhere - a `uuidv7()` default is refused rather than served
39
42
  // something that only looks like one.
40
- mssql: { expressions: { ...ANSI, now: 'SYSUTCDATETIME()', uuid: 'NEWID()' } },
43
+ mssql: { expressions: { ...ANSI, uuid: 'NEWID()' } },
41
44
  };
42
- /**
43
- * A DDL default that is SQL rather than a literal. A class, not a plain object, so a JSON default
44
- * cannot masquerade as one: `defaultValue` accepts `unknown`.
45
- */
46
- export class SqlExpression {
47
- kind;
48
- sql;
49
- /** `sql` is set only for the `raw` kind, which carries its own text verbatim. */
50
- constructor(kind, sql) {
51
- this.kind = kind;
52
- this.sql = sql;
53
- }
54
- static isExpression(value) {
55
- return value instanceof SqlExpression;
56
- }
57
- }
58
45
  /**
59
46
  * Symbolic DDL defaults. Each builds a token the dialect spells at DDL time, so `expr.uuid()` is
60
47
  * `gen_random_uuid()` on Postgres and `UUID()` on MySQL from one migration.
@@ -90,29 +77,39 @@ export function formatDefaultValue(value, dialect, columnType) {
90
77
  const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
91
78
  return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
92
79
  }
93
- /** Whether a stored default is the declared one, as the engine reprints it: `'a'::character varying` is `'a'`. */
80
+ /**
81
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
82
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
83
+ */
94
84
  export function sameDefault(desired, current, dialect) {
95
- if (current === desired)
96
- return true;
97
85
  // Both spellings of "no default" are the same fact, and engines disagree on which they report:
98
86
  // MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
99
87
  // `MODIFY` every nullable column, on every sync, forever.
100
- if (current == null || desired == null)
101
- return current == null && desired == null;
102
- const normalize = (value) => {
103
- // Render first: the desired side may be a symbolic expression, the current side is always the
104
- // engine's own text, and `{"kind":"now"}` matches no spelling of `CURRENT_TIMESTAMP`.
105
- const val = SqlExpression.isExpression(value) ? formatDefaultValue(value, dialect) : value;
106
- if (typeof val === 'string') {
107
- let s = val.replace(/::[a-z_]+(\s+[a-z_]+)*(\[\])?$/i, '');
108
- s = s.replace(/^'(.*)'$/, '$1');
109
- if (s.toLowerCase() === 'null')
110
- return 'null';
111
- return s;
112
- }
113
- return typeof val === 'object' ? JSON.stringify(val) : String(val);
114
- };
115
- return normalize(current) === normalize(desired);
88
+ if (desired == null || current == null)
89
+ return desired == null && current == null;
90
+ if (SqlExpression.isExpression(desired) || SqlExpression.isExpression(current)) {
91
+ return (SqlExpression.isExpression(desired) &&
92
+ SqlExpression.isExpression(current) &&
93
+ reprinted(formatDefaultValue(desired, dialect)) === reprinted(formatDefaultValue(current, dialect)));
94
+ }
95
+ // Compared as text, since a catalogue may report a number either as a number or as its text.
96
+ return writtenDefault(desired) === writtenDefault(current);
97
+ }
98
+ /**
99
+ * Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
100
+ * parentheses (SQLite and MySQL drop them, SQL Server adds them) and the empty argument list of
101
+ * CockroachDB's `current_timestamp()`.
102
+ */
103
+ function reprinted(sql) {
104
+ let text = sql
105
+ .toLowerCase()
106
+ .replace(/\s*([(),])\s*/g, '$1')
107
+ .replace(/\s+/g, ' ')
108
+ .trim();
109
+ while (/^\(.*\)$/s.test(text)) {
110
+ text = text.slice(1, -1);
111
+ }
112
+ return text.replace(/\(\)$/, '');
116
113
  }
117
114
  /**
118
115
  * Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
@@ -135,7 +132,7 @@ function defaultLiteral(value, dialect, columnType) {
135
132
  function expressionSql(expression, dialect, columnType) {
136
133
  const { expressions, preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
137
134
  const raw = expression.kind === 'raw';
138
- const sql = raw ? expression.sql : expressions[expression.kind];
135
+ const sql = raw ? expression.sql : { now: dialect.currentTimestamp, ...expressions }[expression.kind];
139
136
  if (sql == null) {
140
137
  throw new UqlUsageError(`${dialect.dialectName} has no '${expression.kind}' default; pass expr.raw(...) with SQL this engine accepts`);
141
138
  }
@@ -1,16 +1,8 @@
1
- import type { ForeignKeyAction } from '../../schema/types.js';
2
1
  import type { IndexColumnInput, IndexOptions } from '../../type/index.js';
3
- import type { SchemaGenerator } from '../../type/migration.js';
2
+ import type { ForeignKeySchema, SchemaGenerator } from '../../type/migration.js';
4
3
  import type { AnyMigrationOperation, IAlterTableBuilder, IColumnBuilder, IColumnFactory, IMigrationBuilder, ITableBuilder } from './types.js';
5
- type ForeignKeyTarget = {
6
- table: string;
7
- columns: string[];
8
- };
9
- type ForeignKeyOptions = {
10
- name?: string;
11
- onDelete?: ForeignKeyAction;
12
- onUpdate?: ForeignKeyAction;
13
- };
4
+ type ForeignKeyTarget = ForeignKeySchema['references'];
5
+ type ForeignKeyOptions = Pick<ForeignKeySchema, 'name' | 'onDelete' | 'onUpdate'>;
14
6
  /**
15
7
  * Records migration operations without executing them.
16
8
  * Use for migration code generation and dry-run scenarios.
@@ -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
  /**