uql-orm 0.96.1 → 0.98.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 (117) hide show
  1. package/dist/dialect/abstractSqlDialect.d.ts +1 -7
  2. package/dist/dialect/abstractSqlDialect.js +1 -9
  3. package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -0
  4. package/dist/dialect/mysqlLikeSqlDialect.js +4 -1
  5. package/dist/dialect/pgLikeSqlDialect.js +0 -1
  6. package/dist/migrate/acquireQuerierForMigrations.d.ts +4 -8
  7. package/dist/migrate/acquireQuerierForMigrations.js +10 -18
  8. package/dist/migrate/builder/columnBuilder.d.ts +1 -2
  9. package/dist/migrate/builder/columnBuilder.js +3 -10
  10. package/dist/migrate/builder/migrationBuilder.d.ts +6 -26
  11. package/dist/migrate/builder/migrationBuilder.js +21 -78
  12. package/dist/migrate/builder/tableBuilder.js +2 -3
  13. package/dist/migrate/builder/types.d.ts +59 -120
  14. package/dist/migrate/cli-config.d.ts +1 -0
  15. package/dist/migrate/cli-config.js +11 -26
  16. package/dist/migrate/cli.d.ts +0 -13
  17. package/dist/migrate/cli.js +55 -118
  18. package/dist/migrate/codegen/entityCodeGenerator.d.ts +7 -61
  19. package/dist/migrate/codegen/entityCodeGenerator.js +53 -174
  20. package/dist/migrate/codegen/fieldOptionsSource.d.ts +1 -3
  21. package/dist/migrate/codegen/fieldOptionsSource.js +3 -11
  22. package/dist/migrate/codegen/index.d.ts +2 -7
  23. package/dist/migrate/codegen/index.js +2 -8
  24. package/dist/migrate/codegen/migrationFile.d.ts +1 -8
  25. package/dist/migrate/codegen/migrationFile.js +9 -13
  26. package/dist/migrate/ddl/defaultSql.d.ts +2 -1
  27. package/dist/migrate/ddl/defaultSql.js +1 -3
  28. package/dist/migrate/ddl/indexCapabilities.d.ts +18 -0
  29. package/dist/migrate/ddl/indexCapabilities.js +60 -0
  30. package/dist/migrate/ddl/indexDdl.d.ts +11 -24
  31. package/dist/migrate/ddl/indexDdl.js +22 -28
  32. package/dist/migrate/ddl/mssqlIndexDdl.d.ts +1 -7
  33. package/dist/migrate/ddl/mssqlIndexDdl.js +1 -7
  34. package/dist/migrate/ddl/mssqlTableDdl.d.ts +6 -9
  35. package/dist/migrate/ddl/mssqlTableDdl.js +14 -17
  36. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +0 -21
  37. package/dist/migrate/ddl/mysqlIndexDdl.js +4 -48
  38. package/dist/migrate/ddl/mysqlTableDdl.d.ts +6 -5
  39. package/dist/migrate/ddl/mysqlTableDdl.js +15 -10
  40. package/dist/migrate/ddl/pgIndexDdl.d.ts +0 -10
  41. package/dist/migrate/ddl/pgIndexDdl.js +5 -44
  42. package/dist/migrate/ddl/pgTableDdl.d.ts +6 -2
  43. package/dist/migrate/ddl/pgTableDdl.js +17 -1
  44. package/dist/migrate/ddl/sqliteIndexDdl.js +2 -7
  45. package/dist/migrate/ddl/tableDdl.d.ts +43 -24
  46. package/dist/migrate/ddl/tableDdl.js +56 -37
  47. package/dist/migrate/ddl/tableRebuild.d.ts +2 -1
  48. package/dist/migrate/drift/driftDetector.d.ts +29 -32
  49. package/dist/migrate/drift/driftDetector.js +155 -205
  50. package/dist/migrate/drift/index.d.ts +1 -6
  51. package/dist/migrate/drift/index.js +1 -6
  52. package/dist/migrate/generator/definitionToNode.d.ts +2 -2
  53. package/dist/migrate/generator/definitionToNode.js +6 -5
  54. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +56 -77
  55. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +75 -98
  56. package/dist/migrate/introspection/mssqlIntrospector.d.ts +10 -43
  57. package/dist/migrate/introspection/mssqlIntrospector.js +52 -77
  58. package/dist/migrate/introspection/mysqlIntrospector.d.ts +21 -37
  59. package/dist/migrate/introspection/mysqlIntrospector.js +75 -56
  60. package/dist/migrate/introspection/postgresIntrospector.d.ts +15 -60
  61. package/dist/migrate/introspection/postgresIntrospector.js +74 -77
  62. package/dist/migrate/introspection/sqliteIntrospector.d.ts +19 -53
  63. package/dist/migrate/introspection/sqliteIntrospector.js +73 -119
  64. package/dist/migrate/introspection/tableSchemaAST.d.ts +13 -0
  65. package/dist/migrate/introspection/tableSchemaAST.js +85 -0
  66. package/dist/migrate/migrationTarget.js +10 -2
  67. package/dist/migrate/migrator.d.ts +9 -44
  68. package/dist/migrate/migrator.js +72 -150
  69. package/dist/migrate/schemaChange.d.ts +8 -5
  70. package/dist/migrate/schemaChange.js +25 -8
  71. package/dist/migrate/schemaGenerator.d.ts +35 -109
  72. package/dist/migrate/schemaGenerator.js +179 -353
  73. package/dist/migrate/storage/databaseStorage.d.ts +2 -1
  74. package/dist/migrate/storage/databaseStorage.js +3 -2
  75. package/dist/migrate/storage/jsonStorage.d.ts +1 -2
  76. package/dist/migrate/storage/jsonStorage.js +11 -20
  77. package/dist/migrate/triggerSql.d.ts +7 -9
  78. package/dist/migrate/triggerSql.js +17 -18
  79. package/dist/mongo/index.d.ts +0 -1
  80. package/dist/mongo/index.js +0 -1
  81. package/dist/mongo/mongoDialect.js +0 -1
  82. package/dist/mongo/mongoIntrospector.d.ts +1 -6
  83. package/dist/mongo/mongoIntrospector.js +7 -18
  84. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -26
  85. package/dist/mongo/mongoSchemaGenerator.js +51 -75
  86. package/dist/mssql/mssqlDialect.js +0 -1
  87. package/dist/schema/canonicalType.d.ts +15 -19
  88. package/dist/schema/canonicalType.js +20 -43
  89. package/dist/schema/dependencyGraph.d.ts +2 -3
  90. package/dist/schema/dependencyGraph.js +0 -4
  91. package/dist/schema/indexDifferences.js +2 -2
  92. package/dist/schema/schemaAST.d.ts +1 -1
  93. package/dist/schema/schemaAST.js +5 -12
  94. package/dist/schema/schemaASTBuilder.d.ts +5 -6
  95. package/dist/schema/schemaASTBuilder.js +17 -18
  96. package/dist/schema/schemaASTDiffer.d.ts +4 -5
  97. package/dist/schema/schemaASTDiffer.js +40 -73
  98. package/dist/schema/types.d.ts +24 -54
  99. package/dist/sqlite/localSqliteQuerierPool.d.ts +16 -2
  100. package/dist/sqlite/localSqliteQuerierPool.js +20 -4
  101. package/dist/sqlite/nodeSqliteQuerierPool.js +2 -2
  102. package/dist/sqlite/sqliteDialect.js +0 -1
  103. package/dist/sqlite/sqliteQuerierPool.js +3 -3
  104. package/dist/type/dialect.d.ts +0 -2
  105. package/dist/type/migration.d.ts +13 -73
  106. package/dist/util/ddlExpression.util.d.ts +13 -2
  107. package/dist/util/ddlExpression.util.js +27 -4
  108. package/dist/util/sql.util.d.ts +2 -12
  109. package/dist/util/sql.util.js +9 -18
  110. package/package.json +1 -1
  111. package/skills/uql-orm/SKILL.md +1 -1
  112. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -36
  113. package/dist/migrate/introspection/baseSqlIntrospector.js +0 -133
  114. package/dist/schema/index.d.ts +0 -2
  115. package/dist/schema/index.js +0 -1
  116. package/dist/sqlite/sqlitePragmas.d.ts +0 -3
  117. package/dist/sqlite/sqlitePragmas.js +0 -15
@@ -1,12 +1,5 @@
1
1
  import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
2
- /**
3
- * SQL Server schema introspector.
4
- *
5
- * `INFORMATION_SCHEMA` answers columns and foreign keys, but not indexes: it has no view for them at
6
- * all, and its `CONSTRAINT_COLUMN_USAGE` conflates a unique index with a unique constraint. Those
7
- * come from `sys.indexes` instead, which is also the only place the filtered-index predicate and the
8
- * included columns are readable.
9
- */
2
+ /** SQL Server schema introspector: `INFORMATION_SCHEMA` has no view of indexes, which come from `sys.indexes`. */
10
3
  export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
11
4
  defaultSchemaExpr = 'SCHEMA_NAME()';
12
5
  triggersQuery() {
@@ -18,6 +11,14 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
18
11
  AND OBJECT_NAME(t.parent_id) = ${this.dialect.placeholder(1)}
19
12
  `;
20
13
  }
14
+ async getChecks(read, tableName) {
15
+ return read(
16
+ /*sql*/ `
17
+ SELECT k.name AS name, k.definition AS expression
18
+ FROM sys.check_constraints k
19
+ WHERE OBJECT_SCHEMA_NAME(k.parent_object_id) = ${this.schemaExpr} AND OBJECT_NAME(k.parent_object_id) = @p1
20
+ `, [tableName]);
21
+ }
21
22
  getTableNamesQuery() {
22
23
  return /*sql*/ `
23
24
  SELECT TABLE_NAME as table_name
@@ -29,22 +30,14 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
29
30
  }
30
31
  tableExistsQuery() {
31
32
  return /*sql*/ `
32
- SELECT COUNT(*) as count
33
- FROM INFORMATION_SCHEMA.TABLES
34
- WHERE TABLE_SCHEMA = ${this.schemaExpr}
35
- AND TABLE_NAME = @p1
33
+ SELECT 1 FROM INFORMATION_SCHEMA.TABLES
34
+ WHERE TABLE_SCHEMA = ${this.schemaExpr} AND TABLE_NAME = @p1 AND TABLE_TYPE = 'BASE TABLE'
36
35
  `;
37
36
  }
38
- parseTableExistsResult([row]) {
39
- return row.count > 0;
40
- }
41
- /**
42
- * From `sys` rather than `INFORMATION_SCHEMA`, which has no identity flag and no per-column view of
43
- * the key or of a unique index. A key column is not also `isUnique`, as on MySQL: only a unique index
44
- * of its own, other than the key's, makes it so.
45
- */
46
- getColumnsQuery(_tableName) {
47
- return /*sql*/ `
37
+ /** From `sys` rather than `INFORMATION_SCHEMA`, which has no identity flag. */
38
+ async getColumns(read, tableName) {
39
+ const rows = await read(
40
+ /*sql*/ `
48
41
  SELECT
49
42
  c.name as column_name,
50
43
  t.name as data_type,
@@ -54,8 +47,6 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
54
47
  c.is_nullable as is_nullable,
55
48
  c.is_identity as is_identity,
56
49
  d.definition as column_default,
57
- f.is_primary_key,
58
- f.is_unique,
59
50
  CASE WHEN cc.is_persisted = 1 THEN cc.definition END as generated_as
60
51
  FROM sys.columns c
61
52
  JOIN sys.objects o ON o.object_id = c.object_id
@@ -63,29 +54,33 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
63
54
  JOIN sys.types t ON t.user_type_id = c.user_type_id
64
55
  LEFT JOIN sys.default_constraints d ON d.object_id = c.default_object_id
65
56
  LEFT JOIN sys.computed_columns cc ON cc.object_id = c.object_id AND cc.column_id = c.column_id
66
- OUTER APPLY (
67
- SELECT
68
- MAX(CAST(i.is_primary_key AS INT)) as is_primary_key,
69
- MAX(CASE WHEN i.is_primary_key = 0 AND n.key_columns = 1 THEN 1 ELSE 0 END) as is_unique
70
- FROM sys.index_columns ic
71
- JOIN sys.indexes i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
72
- CROSS APPLY (
73
- SELECT COUNT(*) as key_columns FROM sys.index_columns k
74
- WHERE k.object_id = i.object_id AND k.index_id = i.index_id AND k.is_included_column = 0
75
- ) n
76
- WHERE ic.object_id = c.object_id AND ic.column_id = c.column_id
77
- AND ic.is_included_column = 0 AND i.is_unique = 1
78
- ) f
79
57
  WHERE s.name = ${this.schemaExpr} AND o.name = @p1
80
58
  ORDER BY c.column_id
81
- `;
59
+ `, [tableName]);
60
+ return rows.map((row) => {
61
+ const type = row.data_type.toUpperCase();
62
+ const bytes = this.toNumber(row.max_length);
63
+ return {
64
+ name: row.column_name,
65
+ type: spelledType(type, bytes, this.toNumber(row.numeric_scale)),
66
+ nullable: Boolean(row.is_nullable),
67
+ defaultValue: this.parseDefaultValue(row.column_default),
68
+ isAutoIncrement: Boolean(row.is_identity),
69
+ length: widthOf(type, bytes),
70
+ precision: NUMERIC_TYPES.has(type) ? this.toNumber(row.numeric_precision) : undefined,
71
+ scale: NUMERIC_TYPES.has(type) ? this.toNumber(row.numeric_scale) : undefined,
72
+ generatedAs: row.generated_as ?? undefined,
73
+ };
74
+ });
82
75
  }
83
76
  /** `is_primary_key` is excluded: the key is read separately, the way every other engine reads it. */
84
- getIndexesQuery(_tableName) {
85
- return /*sql*/ `
77
+ async getIndexes(read, tableName) {
78
+ const rows = await read(
79
+ /*sql*/ `
86
80
  SELECT
87
81
  i.name as index_name,
88
82
  i.is_unique as is_unique,
83
+ i.filter_definition as filter_definition,
89
84
  STRING_AGG(c.name, ',') WITHIN GROUP (ORDER BY ic.key_ordinal) as columns
90
85
  FROM sys.indexes i
91
86
  JOIN sys.objects o ON o.object_id = i.object_id
@@ -94,12 +89,19 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
94
89
  JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
95
90
  WHERE s.name = ${this.schemaExpr} AND o.name = @p1
96
91
  AND i.is_primary_key = 0 AND i.name IS NOT NULL AND ic.is_included_column = 0
97
- GROUP BY i.name, i.is_unique
92
+ GROUP BY i.name, i.is_unique, i.filter_definition
98
93
  ORDER BY i.name
99
- `;
94
+ `, [tableName]);
95
+ return rows.map((row) => ({
96
+ name: row.index_name,
97
+ entries: row.columns.split(',').map((column) => ({ column })),
98
+ unique: Boolean(row.is_unique),
99
+ where: row.filter_definition ?? undefined,
100
+ }));
100
101
  }
101
- getForeignKeysQuery(_tableName) {
102
- return /*sql*/ `
102
+ async getForeignKeys(read, tableName) {
103
+ const rows = await read(
104
+ /*sql*/ `
103
105
  SELECT
104
106
  fk.name as constraint_name,
105
107
  STRING_AGG(pc.name, ',') WITHIN GROUP (ORDER BY fkc.constraint_column_id) as columns,
@@ -117,10 +119,12 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
117
119
  WHERE s.name = ${this.schemaExpr} AND o.name = @p1
118
120
  GROUP BY fk.name, rt.name, fk.delete_referential_action_desc, fk.update_referential_action_desc
119
121
  ORDER BY fk.name
120
- `;
122
+ `, [tableName]);
123
+ return this.joinedForeignKeys(rows);
121
124
  }
122
- getPrimaryKeyQuery(_tableName) {
123
- return /*sql*/ `
125
+ getPrimaryKey(read, tableName) {
126
+ return this.readPrimaryKey(read,
127
+ /*sql*/ `
124
128
  SELECT c.name as column_name, i.name as constraint_name
125
129
  FROM sys.indexes i
126
130
  JOIN sys.objects o ON o.object_id = i.object_id
@@ -129,36 +133,7 @@ export class MsSqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
129
133
  JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
130
134
  WHERE s.name = ${this.schemaExpr} AND o.name = @p1 AND i.is_primary_key = 1
131
135
  ORDER BY ic.key_ordinal
132
- `;
133
- }
134
- async mapColumnsResult(_read, _tableName, results) {
135
- return results.map((row) => {
136
- const type = row.data_type.toUpperCase();
137
- const bytes = this.toNumber(row.max_length);
138
- return {
139
- name: row.column_name,
140
- type: spelledType(type, bytes, this.toNumber(row.numeric_scale)),
141
- nullable: Boolean(row.is_nullable),
142
- defaultValue: this.parseDefaultValue(row.column_default),
143
- isAutoIncrement: Boolean(row.is_identity),
144
- isPrimaryKey: Boolean(row.is_primary_key),
145
- isUnique: Boolean(row.is_unique),
146
- length: widthOf(type, bytes),
147
- precision: NUMERIC_TYPES.has(type) ? this.toNumber(row.numeric_precision) : undefined,
148
- scale: NUMERIC_TYPES.has(type) ? this.toNumber(row.numeric_scale) : undefined,
149
- generatedAs: row.generated_as ?? undefined,
150
- };
151
- });
152
- }
153
- async mapIndexesResult(_read, _tableName, results) {
154
- return results.map((row) => ({
155
- name: row.index_name,
156
- entries: row.columns.split(',').map((column) => ({ column })),
157
- unique: Boolean(row.is_unique),
158
- }));
159
- }
160
- async mapForeignKeysResult(_read, _tableName, results) {
161
- return this.joinedForeignKeys(results);
136
+ `, tableName);
162
137
  }
163
138
  /**
164
139
  * The engine reprints a default from its own parse tree: all of it in one pair of parentheses, and a
@@ -1,6 +1,7 @@
1
1
  import type { IndexFacet } from '../../schema/indexDifferences.js';
2
- import type { ColumnSchema, ForeignKeySchema, IndexSchema } from '../../type/index.js';
3
- import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
2
+ import type { CheckSchema } from '../../schema/types.js';
3
+ import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema } from '../../type/index.js';
4
+ import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
4
5
  /**
5
6
  * MySQL/MariaDB schema introspector.
6
7
  * Works with both MySQL and MariaDB as they share the same information_schema structure.
@@ -8,18 +9,18 @@ import { AbstractSqlSchemaIntrospector, type JoinedForeignKeyRow, type TableRowR
8
9
  export declare class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
9
10
  protected readonly defaultSchemaExpr = "DATABASE()";
10
11
  protected triggersQuery(): string;
12
+ /**
13
+ * `CHECK_CONSTRAINTS` names no table on MySQL, where a check's name is unique in its schema, so the
14
+ * table comes from `TABLE_CONSTRAINTS`. It reports the clause escaped as a literal's body (`\'a\'`).
15
+ */
16
+ protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
11
17
  protected getTableNamesQuery(): string;
12
18
  protected tableExistsQuery(): string;
13
- protected parseTableExistsResult([row]: {
14
- count: number | bigint;
15
- }[]): boolean;
16
- protected getColumnsQuery(_tableName: string): string;
17
- protected getIndexesQuery(_tableName: string): string;
18
- protected getForeignKeysQuery(_tableName: string): string;
19
- protected getPrimaryKeyQuery(_tableName: string): string;
20
- protected mapColumnsResult(_read: TableRowReader, _tableName: string, results: MysqlColumnRow[]): Promise<ColumnSchema[]>;
21
- protected mapIndexesResult(_read: TableRowReader, _tableName: string, results: MysqlIndexRow[]): Promise<IndexSchema[]>;
22
- protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: JoinedForeignKeyRow[]): Promise<ForeignKeySchema[]>;
19
+ protected getColumns(read: TableRowReader, tableName: string): Promise<ReadColumn[]>;
20
+ protected getIndexes(read: TableRowReader, tableName: string): Promise<IndexSchema[]>;
21
+ protected getForeignKeys(read: TableRowReader, tableName: string): Promise<ForeignKeySchema[]>;
22
+ /** Unnamed: MySQL calls every key `PRIMARY`, and drops one by no name. */
23
+ protected getPrimaryKey(read: TableRowReader, tableName: string): Promise<PrimaryKeySchema | undefined>;
23
24
  /**
24
25
  * MySQL prints a literal default unquoted, except one wrapped as `DEFAULT ('x')`, the form a `TEXT`
25
26
  * column takes. That one comes with a charset introducer and every quote and backslash escaped again:
@@ -32,21 +33,6 @@ export declare class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospect
32
33
  */
33
34
  protected sqlText(defaultValue: string, extra: string): string | undefined;
34
35
  }
35
- type MysqlColumnRow = {
36
- column_name: string;
37
- data_type: string;
38
- column_type: string;
39
- is_nullable: string;
40
- column_default: string | null;
41
- column_key: string;
42
- extra: string;
43
- character_maximum_length: number | bigint | null;
44
- numeric_precision: number | bigint | null;
45
- datetime_precision: number | bigint | null;
46
- numeric_scale: number | null;
47
- column_comment: string | null;
48
- generated_as: string | null;
49
- };
50
36
  /**
51
37
  * MariaDB reads out of the same `information_schema` as MySQL, save for one column type it does not
52
38
  * have: `JSON` there is an alias for `LONGTEXT` plus a `json_valid()` check constraint named after
@@ -56,21 +42,19 @@ type MysqlColumnRow = {
56
42
  * JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
57
43
  */
58
44
  export declare class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
45
+ /**
46
+ * A check's name is unique only in its table on MariaDB, whose `CHECK_CONSTRAINTS` names the table. A
47
+ * JSON column's `json_valid()` is its type, read by {@link getColumns}, so it is left out.
48
+ */
49
+ protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
59
50
  /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
60
51
  protected sqlText(defaultValue: string): string | undefined;
61
52
  /** Whether an index is MariaDB's vector index, and the distance it was built for. */
62
- readonly indexFacets: ReadonlySet<IndexFacet>;
53
+ protected readonly indexFacets: ReadonlySet<IndexFacet>;
63
54
  /**
64
55
  * A vector index's distance is kept only in the table's own definition, ``VECTOR KEY `ix` (`vec`)
65
56
  * `DISTANCE`='cosine'``, and left out there for MariaDB's default, euclidean.
66
57
  */
67
- protected mapIndexesResult(read: TableRowReader, tableName: string, results: MysqlIndexRow[]): Promise<IndexSchema[]>;
68
- protected mapColumnsResult(read: TableRowReader, tableName: string, results: MysqlColumnRow[]): Promise<ColumnSchema[]>;
58
+ protected getIndexes(read: TableRowReader, tableName: string): Promise<IndexSchema[]>;
59
+ protected getColumns(read: TableRowReader, tableName: string): Promise<ReadColumn[]>;
69
60
  }
70
- type MysqlIndexRow = {
71
- index_name: string;
72
- columns: string;
73
- is_unique: number;
74
- method: string;
75
- };
76
- export {};
@@ -17,6 +17,21 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
17
17
  WHERE TRIGGER_SCHEMA = ${this.schemaExpr} AND EVENT_OBJECT_TABLE = ${this.dialect.placeholder(1)}
18
18
  `;
19
19
  }
20
+ /**
21
+ * `CHECK_CONSTRAINTS` names no table on MySQL, where a check's name is unique in its schema, so the
22
+ * table comes from `TABLE_CONSTRAINTS`. It reports the clause escaped as a literal's body (`\'a\'`).
23
+ */
24
+ async getChecks(read, tableName) {
25
+ const rows = await read(
26
+ /*sql*/ `
27
+ SELECT k.CONSTRAINT_NAME AS name, c.CHECK_CLAUSE AS expression
28
+ FROM information_schema.TABLE_CONSTRAINTS k
29
+ JOIN information_schema.CHECK_CONSTRAINTS c
30
+ ON c.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME = k.CONSTRAINT_NAME
31
+ WHERE k.CONSTRAINT_TYPE = 'CHECK' AND k.TABLE_SCHEMA = ${this.schemaExpr} AND k.TABLE_NAME = ?
32
+ `, [tableName]);
33
+ return rows.map(({ name, expression }) => ({ name, expression: unescapeMysqlString(expression) }));
34
+ }
20
35
  getTableNamesQuery() {
21
36
  return /*sql*/ `
22
37
  SELECT TABLE_NAME as table_name
@@ -28,17 +43,13 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
28
43
  }
29
44
  tableExistsQuery() {
30
45
  return /*sql*/ `
31
- SELECT COUNT(*) as count
32
- FROM information_schema.TABLES
33
- WHERE TABLE_SCHEMA = ${this.schemaExpr}
34
- AND TABLE_NAME = ?
46
+ SELECT 1 FROM information_schema.TABLES
47
+ WHERE TABLE_SCHEMA = ${this.schemaExpr} AND TABLE_NAME = ? AND TABLE_TYPE = 'BASE TABLE'
35
48
  `;
36
49
  }
37
- parseTableExistsResult([row]) {
38
- return Number(row.count) > 0;
39
- }
40
- getColumnsQuery(_tableName) {
41
- return /*sql*/ `
50
+ async getColumns(read, tableName) {
51
+ const rows = await read(
52
+ /*sql*/ `
42
53
  SELECT
43
54
  COLUMN_NAME as column_name,
44
55
  DATA_TYPE as data_type,
@@ -49,7 +60,6 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
49
60
  NUMERIC_PRECISION as numeric_precision,
50
61
  NUMERIC_SCALE as numeric_scale,
51
62
  DATETIME_PRECISION as datetime_precision,
52
- COLUMN_KEY as column_key,
53
63
  EXTRA as extra,
54
64
  CASE WHEN EXTRA LIKE '%STORED GENERATED%' THEN GENERATION_EXPRESSION END as generated_as,
55
65
  COLUMN_COMMENT as column_comment
@@ -57,10 +67,25 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
57
67
  WHERE TABLE_SCHEMA = ${this.schemaExpr}
58
68
  AND TABLE_NAME = ?
59
69
  ORDER BY ORDINAL_POSITION
60
- `;
70
+ `, [tableName]);
71
+ return rows.map((row) => ({
72
+ name: row.column_name,
73
+ type: row.column_type.toUpperCase(),
74
+ nullable: row.is_nullable === 'YES',
75
+ defaultValue: this.parseDefaultValue(row.column_default, row.extra),
76
+ isAutoIncrement: row.extra.toLowerCase().includes('auto_increment'),
77
+ // A `VECTOR`'s is its bytes, four a dimension, which `column_type` already states as dimensions.
78
+ length: /^vector/i.test(row.column_type) ? undefined : this.toNumber(row.character_maximum_length),
79
+ // A timestamp's fractional digits, stated even when 0, which uql's own unstated `DATETIME(3)` is not.
80
+ precision: this.toNumber(TIMESTAMP_TYPES.has(row.data_type) ? row.datetime_precision : row.numeric_precision),
81
+ scale: this.toNumber(row.numeric_scale),
82
+ comment: row.column_comment || undefined,
83
+ generatedAs: row.generated_as ?? undefined,
84
+ }));
61
85
  }
62
- getIndexesQuery(_tableName) {
63
- return /*sql*/ `
86
+ async getIndexes(read, tableName) {
87
+ const rows = await read(
88
+ /*sql*/ `
64
89
  SELECT
65
90
  INDEX_NAME as index_name,
66
91
  GROUP_CONCAT(COALESCE(COLUMN_NAME, '') ORDER BY SEQ_IN_INDEX) as columns,
@@ -72,10 +97,20 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
72
97
  AND INDEX_NAME != 'PRIMARY'
73
98
  GROUP BY INDEX_NAME, NON_UNIQUE
74
99
  ORDER BY INDEX_NAME
75
- `;
100
+ `, [tableName]);
101
+ return rows.map((row) => ({
102
+ name: row.index_name,
103
+ ...(row.method === 'VECTOR' && { type: 'vector' }),
104
+ // A functional or multi-valued key part has no `COLUMN_NAME` - the `COALESCE` above keeps its
105
+ // place in the list, and it is reported as the expression it is, which is what stops diffing
106
+ // from comparing an entry list the server cannot state against the entity's own.
107
+ entries: row.columns.split(',').map((column) => (column ? { column } : { column, expression: true })),
108
+ unique: Boolean(row.is_unique),
109
+ }));
76
110
  }
77
- getForeignKeysQuery(_tableName) {
78
- return /*sql*/ `
111
+ async getForeignKeys(read, tableName) {
112
+ const rows = await read(
113
+ /*sql*/ `
79
114
  SELECT
80
115
  kcu.CONSTRAINT_NAME as constraint_name,
81
116
  GROUP_CONCAT(kcu.COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) as columns,
@@ -92,49 +127,20 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
92
127
  AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
93
128
  GROUP BY kcu.CONSTRAINT_NAME, kcu.REFERENCED_TABLE_NAME, rc.DELETE_RULE, rc.UPDATE_RULE
94
129
  ORDER BY kcu.CONSTRAINT_NAME
95
- `;
130
+ `, [tableName]);
131
+ return this.joinedForeignKeys(rows);
96
132
  }
97
- getPrimaryKeyQuery(_tableName) {
98
- return /*sql*/ `
133
+ /** Unnamed: MySQL calls every key `PRIMARY`, and drops one by no name. */
134
+ getPrimaryKey(read, tableName) {
135
+ return this.readPrimaryKey(read,
136
+ /*sql*/ `
99
137
  SELECT COLUMN_NAME as column_name
100
138
  FROM information_schema.KEY_COLUMN_USAGE
101
139
  WHERE TABLE_SCHEMA = ${this.schemaExpr}
102
140
  AND TABLE_NAME = ?
103
141
  AND CONSTRAINT_NAME = 'PRIMARY'
104
142
  ORDER BY ORDINAL_POSITION
105
- `;
106
- }
107
- async mapColumnsResult(_read, _tableName, results) {
108
- return results.map((row) => ({
109
- name: row.column_name,
110
- type: row.column_type.toUpperCase(),
111
- nullable: row.is_nullable === 'YES',
112
- defaultValue: this.parseDefaultValue(row.column_default, row.extra),
113
- isPrimaryKey: row.column_key === 'PRI',
114
- isAutoIncrement: row.extra.toLowerCase().includes('auto_increment'),
115
- isUnique: row.column_key === 'UNI',
116
- // A `VECTOR`'s is its bytes, four a dimension, which `column_type` already states as dimensions.
117
- length: /^vector/i.test(row.column_type) ? undefined : this.toNumber(row.character_maximum_length),
118
- // A timestamp's fractional digits, stated even when 0, which uql's own unstated `DATETIME(3)` is not.
119
- precision: this.toNumber(TIMESTAMP_TYPES.has(row.data_type) ? row.datetime_precision : row.numeric_precision),
120
- scale: this.toNumber(row.numeric_scale),
121
- comment: row.column_comment || undefined,
122
- generatedAs: row.generated_as ?? undefined,
123
- }));
124
- }
125
- async mapIndexesResult(_read, _tableName, results) {
126
- return results.map((row) => ({
127
- name: row.index_name,
128
- ...(row.method === 'VECTOR' && { type: 'vector' }),
129
- // A functional or multi-valued key part has no `COLUMN_NAME` - the `COALESCE` above keeps its
130
- // place in the list, and it is reported as the expression it is, which is what stops diffing
131
- // from comparing an entry list the server cannot state against the entity's own.
132
- entries: row.columns.split(',').map((column) => (column ? { column } : { column, expression: true })),
133
- unique: Boolean(row.is_unique),
134
- }));
135
- }
136
- async mapForeignKeysResult(_read, _tableName, results) {
137
- return this.joinedForeignKeys(results);
143
+ `, tableName);
138
144
  }
139
145
  /**
140
146
  * MySQL prints a literal default unquoted, except one wrapped as `DEFAULT ('x')`, the form a `TEXT`
@@ -183,6 +189,19 @@ const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
183
189
  * JSON, got LONGTEXT", flagged as data loss) on a table uql created itself.
184
190
  */
185
191
  export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
192
+ /**
193
+ * A check's name is unique only in its table on MariaDB, whose `CHECK_CONSTRAINTS` names the table. A
194
+ * JSON column's `json_valid()` is its type, read by {@link getColumns}, so it is left out.
195
+ */
196
+ async getChecks(read, tableName) {
197
+ return read(
198
+ /*sql*/ `
199
+ SELECT CONSTRAINT_NAME AS name, CHECK_CLAUSE AS expression
200
+ FROM information_schema.CHECK_CONSTRAINTS
201
+ WHERE CONSTRAINT_SCHEMA = ${this.schemaExpr} AND TABLE_NAME = ?
202
+ AND CHECK_CLAUSE <> CONCAT('json_valid(\`', CONSTRAINT_NAME, '\`)')
203
+ `, [tableName]);
204
+ }
186
205
  /** MariaDB prints a literal quoted, as SQL reads it (`'it''s'`), so an unquoted default is SQL. */
187
206
  sqlText(defaultValue) {
188
207
  return defaultValue.startsWith("'") ? undefined : defaultValue;
@@ -193,8 +212,8 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
193
212
  * A vector index's distance is kept only in the table's own definition, ``VECTOR KEY `ix` (`vec`)
194
213
  * `DISTANCE`='cosine'``, and left out there for MariaDB's default, euclidean.
195
214
  */
196
- async mapIndexesResult(read, tableName, results) {
197
- const indexes = await super.mapIndexesResult(read, tableName, results);
215
+ async getIndexes(read, tableName) {
216
+ const indexes = await super.getIndexes(read, tableName);
198
217
  if (!indexes.some((index) => index.type === 'vector')) {
199
218
  return indexes;
200
219
  }
@@ -212,8 +231,8 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
212
231
  return { ...index, distance: this.dialect.indexedDistance(metric) };
213
232
  });
214
233
  }
215
- async mapColumnsResult(read, tableName, results) {
216
- const columns = await super.mapColumnsResult(read, tableName, results);
234
+ async getColumns(read, tableName) {
235
+ const columns = await super.getColumns(read, tableName);
217
236
  const checks = await read(
218
237
  /*sql*/ `
219
238
  SELECT CONSTRAINT_NAME as column_name
@@ -1,6 +1,7 @@
1
1
  import type { IndexFacet } from '../../schema/indexDifferences.js';
2
- import type { ColumnSchema, ForeignKeySchema, IndexSchema, RawRow } from '../../type/index.js';
3
- import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
2
+ import { type CheckSchema } from '../../schema/types.js';
3
+ import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema } from '../../type/index.js';
4
+ import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
4
5
  /**
5
6
  * PostgreSQL schema introspector
6
7
  */
@@ -10,11 +11,12 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
10
11
  * Expressions and predicates are read back too, for `generate:from-db`, but they are text the
11
12
  * database reprints in its own words, so they are not comparable and are not claimed here.
12
13
  */
13
- readonly indexFacets: ReadonlySet<IndexFacet>;
14
+ protected readonly indexFacets: ReadonlySet<IndexFacet>;
14
15
  protected triggersQuery(): string;
16
+ /** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
17
+ protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
15
18
  protected getTableNamesQuery(): string;
16
19
  protected tableExistsQuery(): string;
17
- protected parseTableExistsResult([row]: RawRow[]): boolean;
18
20
  /**
19
21
  * The comment reads through `to_regclass` rather than a `::regclass` cast: a name resolves against
20
22
  * the live catalogue while `information_schema` answers from this statement's snapshot, so a table
@@ -25,10 +27,10 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
25
27
  * virtual one Postgres 18 added and uql never declares. CockroachDB states it too. `format_type` for an
26
28
  * extension type's modifier, which `information_schema` drops: a `vector(256)` read back as `vector`.
27
29
  * CockroachDB names that type `vector` where Postgres says `USER-DEFINED`.
28
- *
29
- * A column is unique by a unique index over it alone, a constraint's or its own, as every engine reads it.
30
30
  */
31
- protected getColumnsQuery(_tableName: string): string;
31
+ protected getColumns(read: TableRowReader, tableName: string): Promise<ReadColumn[]>;
32
+ /** Whether `information_schema.columns c` lists a column the table shows: every one, on Postgres. */
33
+ protected readonly visibleColumnSql: string;
32
34
  /**
33
35
  * `attname` where the entry is a column, `pg_get_indexdef` for that one position where it is an
34
36
  * expression. Neither alone will do: an expression entry has `attnum = 0`, so joining `pg_attribute`
@@ -40,7 +42,7 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
40
42
  * and the MySQL family report theirs: the diff reads one over a single column as that column's
41
43
  * uniqueness, and one over several as the unique `@Index` it is.
42
44
  */
43
- protected getIndexesQuery(_tableName: string): string;
45
+ protected getIndexes(read: TableRowReader, tableName: string): Promise<IndexSchema[]>;
44
46
  /** Whether an entry sorts nulls first, which Postgres states on every entry. */
45
47
  protected readonly nullsFirstSql: string;
46
48
  /** An index's access method, which is the type it declares. */
@@ -48,17 +50,14 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
48
50
  /** An entry's operator class, where it is not the default for its type. */
49
51
  protected readonly opsClassSql: string;
50
52
  /** From `pg_constraint`, whose key arrays keep each column paired with the one it references. */
51
- protected getForeignKeysQuery(_tableName: string): string;
52
- protected getPrimaryKeyQuery(_tableName: string): string;
53
- protected mapColumnsResult(_read: TableRowReader, _tableName: string, results: PostgresColumnRow[]): Promise<ColumnSchema[]>;
53
+ protected getForeignKeys(read: TableRowReader, tableName: string): Promise<ForeignKeySchema[]>;
54
+ protected getPrimaryKey(read: TableRowReader, tableName: string): Promise<PrimaryKeySchema | undefined>;
54
55
  /**
55
56
  * A vector index keeps its distance as its vector column's operator class, `{type}_{metric}_ops`, which
56
57
  * is how `PgIndexDdl` writes the entity's `distance`; read back as that `distance`, so the two compare.
57
58
  * No class named is the engine's default, L2.
58
59
  */
59
60
  private withVectorDistance;
60
- protected mapIndexesResult(_read: TableRowReader, _tableName: string, results: PostgresIndexRow[]): Promise<IndexSchema[]>;
61
- protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: PostgresForeignKeyRow[]): Promise<ForeignKeySchema[]>;
62
61
  protected normalizeType(dataType: string, udtName: string): string;
63
62
  /**
64
63
  * Postgres quotes a negative number (`'-3'::integer`); CockroachDB parenthesizes one (`(-3)`) and
@@ -68,14 +67,6 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
68
67
  protected parseDefaultValue(defaultValue: string | null): unknown;
69
68
  protected isAutoIncrement(columnDefault: string | null, isIdentity: string): boolean;
70
69
  }
71
- /** `pg_constraint`'s one-letter spelling of each action. */
72
- declare const FOREIGN_KEY_ACTION_CODES: {
73
- readonly a: 'NO ACTION';
74
- readonly r: 'RESTRICT';
75
- readonly c: 'CASCADE';
76
- readonly n: 'SET NULL';
77
- readonly d: 'SET DEFAULT';
78
- };
79
70
  /**
80
71
  * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.2.5
81
72
  * still rejects `NULLS FIRST/LAST` and operator classes as "unimplemented", and it sorts nulls first
@@ -83,7 +74,9 @@ declare const FOREIGN_KEY_ACTION_CODES: {
83
74
  * every ascending index as drifted, against an entity that could not have asked for one.
84
75
  */
85
76
  export declare class CockroachSchemaIntrospector extends PostgresSchemaIntrospector {
86
- readonly indexFacets: ReadonlySet<IndexFacet>;
77
+ protected readonly indexFacets: ReadonlySet<IndexFacet>;
78
+ /** Not `rowid`, the `NOT VISIBLE` key it gives a table declared without one, which no entity can name. */
79
+ protected readonly visibleColumnSql = "c.is_hidden = 'NO'";
87
80
  /** None: it rejects a stated nulls order, so reading one back gives an index it would refuse to rebuild. */
88
81
  protected readonly nullsFirstSql = "NULL::BOOL";
89
82
  /**
@@ -93,41 +86,3 @@ export declare class CockroachSchemaIntrospector extends PostgresSchemaIntrospec
93
86
  protected readonly indexMethodSql = "CASE WHEN pg_get_indexdef(ix.indexrelid) LIKE '% USING cspann %' THEN 'vector' ELSE am.amname END";
94
87
  protected readonly opsClassSql = "CASE WHEN k.n = ix.indnkeyatts THEN substring(pg_get_indexdef(ix.indexrelid) from '(\\w+_ops)\\)') END";
95
88
  }
96
- type PostgresForeignKeyRow = {
97
- constraint_name: string;
98
- columns: string[];
99
- referenced_table: string;
100
- referenced_columns: string[];
101
- delete_rule: keyof typeof FOREIGN_KEY_ACTION_CODES;
102
- update_rule: keyof typeof FOREIGN_KEY_ACTION_CODES;
103
- };
104
- /** One entry of one index; what the index itself is repeats across its rows. */
105
- type PostgresIndexRow = {
106
- index_name: string;
107
- is_unique: boolean;
108
- method: string;
109
- predicate: string | null;
110
- is_key: boolean;
111
- is_expression: boolean;
112
- entry: string;
113
- descending: boolean;
114
- nulls_first: boolean | null;
115
- ops_class: string | null;
116
- };
117
- type PostgresColumnRow = {
118
- column_name: string;
119
- data_type: string;
120
- udt_name: string;
121
- formatted_type: string | null;
122
- is_nullable: string;
123
- column_default: string | null;
124
- is_primary_key: boolean;
125
- is_identity: string;
126
- is_unique: boolean;
127
- character_maximum_length: number | null;
128
- numeric_precision: number | null;
129
- numeric_scale: number | null;
130
- column_comment: string | null;
131
- generated_as: string | null;
132
- };
133
- export {};