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
@@ -0,0 +1,109 @@
1
+ import { SqlExpression, schemaDefault, writtenDefault } from '../../schema/sqlExpression.js';
2
+ import { SQL_VALUE_NAMES } from '../../type/index.js';
3
+ import { UqlUsageError } from '../../util/uqlError.js';
4
+ /** A default in schema form, its SQL compiled with no entity to read: a migration's names no field. */
5
+ const ddlDefault = (value, dialect) => schemaDefault(value, (sql) => dialect.compileDdl(sql));
6
+ /** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
7
+ const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
8
+ /** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
9
+ const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
10
+ const MYSQL_DEFAULTS = { wrapTypes: MYSQL_LARGE_TYPES, preciseTypes: MYSQL_PRECISE_TYPES };
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 const DIALECT_DEFAULTS = {
16
+ postgres: {},
17
+ cockroachdb: {},
18
+ mysql: MYSQL_DEFAULTS,
19
+ mariadb: MYSQL_DEFAULTS,
20
+ sqlite: {},
21
+ mssql: {},
22
+ };
23
+ /**
24
+ * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
25
+ * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
26
+ * the result needs wrapping, which MySQL demands on its large types whatever the value.
27
+ */
28
+ export function formatDefaultValue(value, dialect, columnType) {
29
+ const sql = defaultLiteral(ddlDefault(value, dialect), dialect, columnType);
30
+ const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
31
+ return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
32
+ }
33
+ /**
34
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
35
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
36
+ */
37
+ export function sameDefault(desired, current, dialect) {
38
+ // Both spellings of "no default" are the same fact, and engines disagree on which they report:
39
+ // MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
40
+ // `MODIFY` every nullable column, on every sync, forever.
41
+ if (desired == null || current == null)
42
+ return desired == null && current == null;
43
+ const [want, have] = [ddlDefault(desired, dialect), ddlDefault(current, dialect)];
44
+ if (SqlExpression.isExpression(want) || SqlExpression.isExpression(have)) {
45
+ return (SqlExpression.isExpression(want) &&
46
+ SqlExpression.isExpression(have) &&
47
+ reprinted(formatDefaultValue(want, dialect)) === reprinted(formatDefaultValue(have, dialect)));
48
+ }
49
+ // Compared as text, since a catalogue may report a number either as a number or as its text.
50
+ return writtenDefault(want) === writtenDefault(have);
51
+ }
52
+ /**
53
+ * Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
54
+ * compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
55
+ */
56
+ export function knownDefault(expression, dialect) {
57
+ const name = SQL_VALUE_NAMES.find((kind) => dialect.sqlValues[kind] !== undefined && sameDefault(new SqlExpression(kind), expression, dialect));
58
+ return name ? new SqlExpression(name) : expression;
59
+ }
60
+ /**
61
+ * Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
62
+ * parentheses (SQLite and MySQL drop them, SQL Server adds them) and the empty argument list of
63
+ * CockroachDB's `current_timestamp()`.
64
+ */
65
+ function reprinted(sql) {
66
+ let text = sql
67
+ .toLowerCase()
68
+ .replace(/\s*([(),])\s*/g, '$1')
69
+ .replace(/\s+/g, ' ')
70
+ .trim();
71
+ while (/^\(.*\)$/s.test(text)) {
72
+ text = text.slice(1, -1);
73
+ }
74
+ return text.replace(/\(\)$/, '');
75
+ }
76
+ /**
77
+ * Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
78
+ * it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the cases `escape`
79
+ * cannot serve stay here: a boolean is `1` where booleans are integers, and a plain object or array
80
+ * is JSON rather than the throw and the IN-list `escape` gives them.
81
+ */
82
+ function defaultLiteral(value, dialect, columnType) {
83
+ if (value === undefined || value === null) {
84
+ return 'NULL';
85
+ }
86
+ if (SqlExpression.isExpression(value)) {
87
+ return expressionSql(value, dialect, columnType);
88
+ }
89
+ if (typeof value === 'boolean') {
90
+ return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
91
+ }
92
+ return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
93
+ }
94
+ /** A raw expression's own SQL, else the engine's spelling of the value it names. */
95
+ function expressionSql({ kind, sql }, dialect, columnType) {
96
+ if (sql !== undefined) {
97
+ return sql;
98
+ }
99
+ const { preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
100
+ if (kind === 'currentTimestamp' && preciseTypes) {
101
+ const precision = columnType === undefined ? undefined : preciseTypes.exec(columnType)?.[1];
102
+ return precision ? `CURRENT_TIMESTAMP(${precision})` : 'CURRENT_TIMESTAMP';
103
+ }
104
+ const spelled = kind === 'raw' ? undefined : dialect.sqlValues[kind];
105
+ if (spelled === undefined) {
106
+ throw new UqlUsageError(`${dialect.dialectName} has no ${kind}; write it as raw SQL this engine accepts`);
107
+ }
108
+ return spelled;
109
+ }
@@ -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 './defaultSql.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;
@@ -1,5 +1,5 @@
1
- import { formatDefaultValue, sameDefault } from '../builder/expressions.js';
2
- import { lacksValue } from '../schemaChange.js';
1
+ import { UqlUsageError } from '../../util/uqlError.js';
2
+ import { formatDefaultValue } from './defaultSql.js';
3
3
  /**
4
4
  * A column's type with the size it was read back with, unless its spelling already carries one:
5
5
  * introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
@@ -15,14 +15,16 @@ export function sizedType(column) {
15
15
  return column.length === undefined ? column.type : `${column.type}(${column.length})`;
16
16
  }
17
17
  /**
18
- * The `ALTER TABLE` statements an engine spells its own way: the migrator's, for the reason
19
- * {@link IndexDdl} is. The form here is the portable one; SQL Server's is {@link MsSqlTableDdl}.
18
+ * Table DDL that engines spell differently. Like {@link IndexDdl}, it belongs to the migrator, so no runtime
19
+ * entry carries it. This class holds the portable form, which SQLite takes; other families override what differs.
20
20
  */
21
21
  export class TableDdl {
22
22
  dialect;
23
23
  constructor(dialect) {
24
24
  this.dialect = dialect;
25
25
  }
26
+ /** Options appended to `CREATE TABLE`, such as MySQL's engine; empty by default. */
27
+ tableOptions = '';
26
28
  /** A `CREATE TABLE` up to its column list, a no-op where `ifNotExists` and the table is already there. */
27
29
  createTable(target, ifNotExists) {
28
30
  return `CREATE TABLE ${ifNotExists ? 'IF NOT EXISTS ' : ''}${target}`;
@@ -30,41 +32,19 @@ export class TableDdl {
30
32
  addColumn(table, definition) {
31
33
  return `ALTER TABLE ${this.dialect.escapeId(table)} ADD COLUMN ${definition};`;
32
34
  }
33
- /**
34
- * `column` added, spelled by `render`. MySQL fills a zero into the rows already there for a required
35
- * column with no default, so there it is added nullable and required after, failing on them as elsewhere.
36
- */
35
+ /** The statements that add `column`, whose definition `render` writes. */
37
36
  addColumnStatements(table, column, render) {
38
- if (this.dialect.alterColumnSyntax !== 'MODIFY COLUMN' || !lacksValue(column)) {
39
- return [this.addColumn(table, render(column))];
40
- }
41
- return [
42
- this.addColumn(table, render({ ...column, nullable: true })),
43
- ...this.alterColumn(table, column, render(column)),
44
- ];
37
+ return [this.addColumn(table, render(column))];
45
38
  }
46
39
  dropColumn(table, column) {
47
40
  return [`ALTER TABLE ${this.dialect.escapeId(table)} DROP COLUMN ${this.dialect.escapeId(column)};`];
48
41
  }
49
42
  /**
50
- * What changes `column` to what it now declares. `definition` is the whole column, which MySQL's
51
- * `MODIFY COLUMN` restates; Postgres takes each change as a clause of its own, so given what the
52
- * column was (`from`), only the clauses that changed.
43
+ * The statements that change a column from `from`, what it was, to `column`, what it now declares.
44
+ * `definition` is the complete new column definition.
53
45
  */
54
- alterColumn(table, column, definition, from) {
55
- const target = this.dialect.escapeId(table);
56
- if (this.dialect.alterColumnStrategy !== 'separate-clauses') {
57
- return [`ALTER TABLE ${target} ${this.dialect.alterColumnSyntax} ${definition};`];
58
- }
59
- const name = this.dialect.escapeId(column.name);
60
- const alter = `ALTER TABLE ${target} ALTER COLUMN ${name}`;
61
- return [
62
- // Cast, since the engine converts only between types it deems compatible: text to integer needs saying.
63
- (!from || from.type !== column.type) && `${alter} TYPE ${column.type} USING ${name}::${column.type};`,
64
- (!from || from.nullable !== column.nullable) && `${alter} ${column.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`,
65
- (!from || !sameDefault(column.defaultValue, from.defaultValue, this.dialect)) &&
66
- (column.defaultValue === undefined ? `${alter} DROP DEFAULT;` : `${alter} SET${this.defaultClause(column)};`),
67
- ].filter((statement) => statement !== false);
46
+ alterColumn(table, _column, definition, _from) {
47
+ return [`ALTER TABLE ${this.dialect.escapeId(table)} ALTER COLUMN ${definition};`];
68
48
  }
69
49
  renameColumn(table, oldName, newName) {
70
50
  const [target, from, to] = [table, oldName, newName].map((name) => this.dialect.escapeId(name));
@@ -73,6 +53,21 @@ export class TableDdl {
73
53
  renameTable(oldName, newName) {
74
54
  return `ALTER TABLE ${this.dialect.escapeId(oldName)} RENAME TO ${this.dialect.escapeId(newName)};`;
75
55
  }
56
+ /** `schema` is the table's schema, which also holds its indexes. */
57
+ dropIndex(table, index, schema) {
58
+ return `DROP INDEX IF EXISTS ${this.dialect.escapeQualifiedId(index, schema)};`;
59
+ }
60
+ dropForeignKey(table, constraint) {
61
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP CONSTRAINT ${this.dialect.escapeId(constraint)};`;
62
+ }
63
+ /** Drops the primary key by its real constraint name: the introspected one, or the one uql derived when adding it. */
64
+ dropPrimaryKey(table, constraint) {
65
+ if (!constraint) {
66
+ throw new UqlUsageError(`Cannot drop the primary key of "${table}": ${this.dialect.dialectName} names the constraint, and ` +
67
+ 'introspection did not report a name for it.');
68
+ }
69
+ return `ALTER TABLE ${this.dialect.escapeId(table)} DROP CONSTRAINT ${this.dialect.escapeId(constraint)};`;
70
+ }
76
71
  /** A stored generated column's type, with the clause computing it. */
77
72
  storedGeneratedColumn(type, expression) {
78
73
  return `${type} GENERATED ALWAYS AS (${expression}) STORED`;
@@ -87,3 +82,7 @@ export class TableDdl {
87
82
  : ` DEFAULT ${formatDefaultValue(column.defaultValue, this.dialect, column.type)}`;
88
83
  }
89
84
  }
85
+ /** `DROP INDEX <index> ON <table>`, for engines that scope index names per table: MySQL and SQL Server. */
86
+ export function dropIndexOnTable(dialect, table, index) {
87
+ return `DROP INDEX ${dialect.escapeId(index)} ON ${dialect.escapeId(table)};`;
88
+ }
@@ -30,8 +30,7 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
30
30
  compareRelationships: opts.checkForeignKeys,
31
31
  excludeTables: opts.excludeTables,
32
32
  defaultsEqual: opts.defaultsEqual,
33
- // Without a dialect there is no engine to compare through, and `formatType` below then reports no
34
- // type drift at all.
33
+ // Types are normalized through the dialect's engine; without a dialect, no type drift is reported.
35
34
  ...(dialect && { normalizeType: engineType(dialect) }),
36
35
  });
37
36
  const drifts = [
@@ -55,11 +54,11 @@ export function detectDrift(expectedAST, actualAST, options = {}) {
55
54
  * are not the rows the ORM believes are unique, so it addresses by a key nothing enforces.
56
55
  */
57
56
  function detectPrimaryKeyDrifts(diff) {
58
- return diff.primaryKeyDiffs.map((pkDiff) => ({
57
+ return diff.primaryKeys.map((pkDiff) => ({
59
58
  type: 'constraint_mismatch',
60
59
  severity: 'critical',
61
60
  table: pkDiff.table,
62
- details: `Primary key of "${pkDiff.table}" is (${keyColumns(pkDiff.actual)}) in the database but (${keyColumns(pkDiff.expected)}) in the entity`,
61
+ details: `Primary key of "${pkDiff.table}" is (${keyColumns(pkDiff.from)}) in the database but (${keyColumns(pkDiff.to)}) in the entity`,
63
62
  suggestion: 'Generate a migration to change the primary key',
64
63
  }));
65
64
  }
@@ -71,34 +70,29 @@ function keyColumns(key) {
71
70
  * Detect table-level drifts (missing/unexpected tables).
72
71
  */
73
72
  function detectTableDrifts(diff) {
74
- const drifts = [];
75
- for (const table of diff.tablesToCreate) {
76
- drifts.push({
73
+ return diff.tables.map((change) => change.from === undefined
74
+ ? {
77
75
  type: 'missing_table',
78
76
  severity: 'critical',
79
- table: table.name,
80
- details: `Entity "${table.name}" exists but table not in database`,
77
+ table: change.to.name,
78
+ details: `Entity "${change.to.name}" exists but table not in database`,
81
79
  suggestion: 'Run migrations to create table',
82
- });
83
- }
84
- for (const table of diff.tablesToDrop) {
85
- drifts.push({
80
+ }
81
+ : {
86
82
  type: 'unexpected_table',
87
83
  severity: 'warning',
88
- table: table.name,
89
- details: `Table "${table.name}" exists in database but no matching entity`,
84
+ table: change.from.name,
85
+ details: `Table "${change.from.name}" exists in database but no matching entity`,
90
86
  suggestion: 'Create entity or drop table',
91
87
  });
92
- }
93
- return drifts;
94
88
  }
95
89
  /**
96
90
  * Detect column-level drifts.
97
91
  */
98
92
  function detectColumnDrifts(diff, opts) {
99
93
  const drifts = [];
100
- for (const colDiff of diff.columnDiffs) {
101
- if (colDiff.type === 'add') {
94
+ for (const colDiff of diff.columns) {
95
+ if (colDiff.from === undefined) {
102
96
  drifts.push({
103
97
  type: 'missing_column',
104
98
  severity: 'critical',
@@ -108,7 +102,7 @@ function detectColumnDrifts(diff, opts) {
108
102
  suggestion: 'Run migration to add column',
109
103
  });
110
104
  }
111
- else if (colDiff.type === 'drop') {
105
+ else if (colDiff.to === undefined) {
112
106
  drifts.push({
113
107
  type: 'unexpected_column',
114
108
  severity: 'warning',
@@ -124,53 +118,46 @@ function detectColumnDrifts(diff, opts) {
124
118
  }
125
119
  return drifts;
126
120
  }
127
- /**
128
- * Add drifts for column alterations: type, nullability and default.
129
- */
121
+ /** The drifts for each part of a column the differ found changed: type, nullability and default. */
130
122
  function addAlterColumnDrifts(colDiff, drifts, opts) {
131
- // An auto-increment key is created through the dialect's `serialPrimaryKey`, whose spelling the
132
- // entity never states - `BIGINT UNSIGNED AUTO_INCREMENT` on the MySQL family, where the column then
133
- // reads back as `BIGINT UNSIGNED` against an entity that can only say `BIGINT`. Comparing the two
134
- // reported every table uql created itself as drifting on its own id.
135
- const dialectOwnsType = colDiff.expected.isPrimaryKey && colDiff.expected.isAutoIncrement;
136
- if (opts.checkTypes && !dialectOwnsType) {
137
- const expectedType = formatType(colDiff.expected.type, opts.dialect);
138
- const actualType = formatType(colDiff.actual.type, opts.dialect);
139
- if (expectedType !== actualType) {
140
- drifts.push({
141
- type: 'type_mismatch',
142
- severity: colDiff.isBreaking ? 'critical' : 'warning',
143
- table: colDiff.table,
144
- column: colDiff.column,
145
- expected: expectedType,
146
- actual: actualType,
147
- details: `Type mismatch for "${colDiff.column}": expected ${expectedType}, got ${actualType}`,
148
- suggestion: colDiff.isBreaking
149
- ? 'Data truncation risk! Create migration to fix.'
150
- : 'Create migration to align types',
151
- });
152
- }
123
+ const { changed } = colDiff;
124
+ // Type drift needs a dialect to render both types.
125
+ if (opts.checkTypes && opts.dialect && changed.includes('type')) {
126
+ const expectedType = formatType(colDiff.to.type, opts.dialect);
127
+ const actualType = formatType(colDiff.from.type, opts.dialect);
128
+ drifts.push({
129
+ type: 'type_mismatch',
130
+ severity: colDiff.isBreaking ? 'critical' : 'warning',
131
+ table: colDiff.table,
132
+ column: colDiff.column,
133
+ expected: expectedType,
134
+ actual: actualType,
135
+ details: `Type mismatch for "${colDiff.column}": expected ${expectedType}, got ${actualType}`,
136
+ suggestion: colDiff.isBreaking
137
+ ? 'Data truncation risk! Create migration to fix.'
138
+ : 'Create migration to align types',
139
+ });
153
140
  }
154
- if (opts.checkNullable && colDiff.expected.nullable !== colDiff.actual.nullable) {
141
+ if (opts.checkNullable && changed.includes('nullable')) {
155
142
  drifts.push({
156
143
  type: 'constraint_mismatch',
157
144
  severity: 'warning',
158
145
  table: colDiff.table,
159
146
  column: colDiff.column,
160
- expected: colDiff.expected.nullable ? 'NULLABLE' : 'NOT NULL',
161
- actual: colDiff.actual.nullable ? 'NULLABLE' : 'NOT NULL',
147
+ expected: colDiff.to.nullable ? 'NULLABLE' : 'NOT NULL',
148
+ actual: colDiff.from.nullable ? 'NULLABLE' : 'NOT NULL',
162
149
  details: `Nullable mismatch for "${colDiff.column}"`,
163
150
  suggestion: 'Align nullable setting in entity or database',
164
151
  });
165
152
  }
166
- if (opts.checkDefaults && !opts.defaultsEqual(colDiff.expected.defaultValue, colDiff.actual.defaultValue)) {
153
+ if (opts.checkDefaults && changed.includes('default')) {
167
154
  drifts.push({
168
155
  type: 'constraint_mismatch',
169
156
  severity: 'info',
170
157
  table: colDiff.table,
171
158
  column: colDiff.column,
172
- expected: String(colDiff.expected.defaultValue ?? 'NULL'),
173
- actual: String(colDiff.actual.defaultValue ?? 'NULL'),
159
+ expected: String(colDiff.to.defaultValue ?? 'NULL'),
160
+ actual: String(colDiff.from.defaultValue ?? 'NULL'),
174
161
  details: `Default mismatch for "${colDiff.column}"`,
175
162
  suggestion: 'Align the default in the entity or the database',
176
163
  });
@@ -181,8 +168,8 @@ function addAlterColumnDrifts(colDiff, drifts, opts) {
181
168
  */
182
169
  function detectIndexDrifts(diff) {
183
170
  const drifts = [];
184
- for (const idxDiff of diff.indexDiffs) {
185
- if (idxDiff.type === 'create') {
171
+ for (const idxDiff of diff.indexes) {
172
+ if (idxDiff.from === undefined) {
186
173
  drifts.push({
187
174
  type: 'missing_index',
188
175
  severity: 'warning',
@@ -192,7 +179,7 @@ function detectIndexDrifts(diff) {
192
179
  suggestion: 'Create index via migration',
193
180
  });
194
181
  }
195
- else if (idxDiff.type === 'drop') {
182
+ else if (idxDiff.to === undefined) {
196
183
  drifts.push({
197
184
  type: 'unexpected_index',
198
185
  severity: 'info',
@@ -222,8 +209,8 @@ function detectIndexDrifts(diff) {
222
209
  */
223
210
  function detectRelationshipDrifts(diff) {
224
211
  const drifts = [];
225
- for (const relDiff of diff.relationshipDiffs) {
226
- if (relDiff.type === 'create') {
212
+ for (const relDiff of diff.relationships) {
213
+ if (relDiff.from === undefined) {
227
214
  drifts.push({
228
215
  type: 'missing_relationship',
229
216
  severity: 'warning',
@@ -233,7 +220,7 @@ function detectRelationshipDrifts(diff) {
233
220
  suggestion: 'Add FK constraint or remove relation from entity',
234
221
  });
235
222
  }
236
- else if (relDiff.type === 'drop') {
223
+ else if (relDiff.to === undefined) {
237
224
  drifts.push({
238
225
  type: 'unexpected_relationship',
239
226
  severity: 'info',
@@ -249,8 +236,8 @@ function detectRelationshipDrifts(diff) {
249
236
  severity: 'warning',
250
237
  table: relDiff.fromTable,
251
238
  relationship: relDiff.name,
252
- expected: formatActions(relDiff.expected),
253
- actual: formatActions(relDiff.actual),
239
+ expected: formatActions(relDiff.to),
240
+ actual: formatActions(relDiff.from),
254
241
  details: `FK "${relDiff.name}" has other referential actions in the database than in the entity`,
255
242
  suggestion: 'Generate a migration, which drops and re-adds the constraint',
256
243
  });