uql-orm 0.97.0 → 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 (114) 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 +57 -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 +51 -168
  20. package/dist/migrate/codegen/fieldOptionsSource.js +3 -6
  21. package/dist/migrate/codegen/index.d.ts +2 -7
  22. package/dist/migrate/codegen/index.js +2 -8
  23. package/dist/migrate/codegen/migrationFile.d.ts +1 -8
  24. package/dist/migrate/codegen/migrationFile.js +9 -13
  25. package/dist/migrate/ddl/defaultSql.d.ts +2 -1
  26. package/dist/migrate/ddl/defaultSql.js +1 -3
  27. package/dist/migrate/ddl/indexCapabilities.d.ts +18 -0
  28. package/dist/migrate/ddl/indexCapabilities.js +60 -0
  29. package/dist/migrate/ddl/indexDdl.d.ts +11 -24
  30. package/dist/migrate/ddl/indexDdl.js +22 -28
  31. package/dist/migrate/ddl/mssqlIndexDdl.d.ts +1 -7
  32. package/dist/migrate/ddl/mssqlIndexDdl.js +1 -7
  33. package/dist/migrate/ddl/mssqlTableDdl.d.ts +6 -9
  34. package/dist/migrate/ddl/mssqlTableDdl.js +14 -17
  35. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +0 -21
  36. package/dist/migrate/ddl/mysqlIndexDdl.js +4 -48
  37. package/dist/migrate/ddl/mysqlTableDdl.d.ts +6 -5
  38. package/dist/migrate/ddl/mysqlTableDdl.js +15 -10
  39. package/dist/migrate/ddl/pgIndexDdl.d.ts +0 -10
  40. package/dist/migrate/ddl/pgIndexDdl.js +5 -44
  41. package/dist/migrate/ddl/pgTableDdl.d.ts +6 -2
  42. package/dist/migrate/ddl/pgTableDdl.js +17 -1
  43. package/dist/migrate/ddl/sqliteIndexDdl.js +2 -7
  44. package/dist/migrate/ddl/tableDdl.d.ts +43 -24
  45. package/dist/migrate/ddl/tableDdl.js +56 -37
  46. package/dist/migrate/ddl/tableRebuild.d.ts +2 -1
  47. package/dist/migrate/drift/driftDetector.d.ts +29 -32
  48. package/dist/migrate/drift/driftDetector.js +139 -205
  49. package/dist/migrate/drift/index.d.ts +1 -6
  50. package/dist/migrate/drift/index.js +1 -6
  51. package/dist/migrate/generator/definitionToNode.js +3 -3
  52. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +53 -76
  53. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +68 -90
  54. package/dist/migrate/introspection/mssqlIntrospector.d.ts +8 -43
  55. package/dist/migrate/introspection/mssqlIntrospector.js +44 -77
  56. package/dist/migrate/introspection/mysqlIntrospector.d.ts +11 -38
  57. package/dist/migrate/introspection/mysqlIntrospector.js +48 -57
  58. package/dist/migrate/introspection/postgresIntrospector.d.ts +12 -60
  59. package/dist/migrate/introspection/postgresIntrospector.js +62 -77
  60. package/dist/migrate/introspection/sqliteIntrospector.d.ts +14 -53
  61. package/dist/migrate/introspection/sqliteIntrospector.js +59 -119
  62. package/dist/migrate/introspection/tableSchemaAST.d.ts +13 -0
  63. package/dist/migrate/introspection/tableSchemaAST.js +85 -0
  64. package/dist/migrate/migrationTarget.js +10 -2
  65. package/dist/migrate/migrator.d.ts +4 -21
  66. package/dist/migrate/migrator.js +47 -71
  67. package/dist/migrate/schemaChange.d.ts +0 -2
  68. package/dist/migrate/schemaChange.js +1 -1
  69. package/dist/migrate/schemaGenerator.d.ts +22 -97
  70. package/dist/migrate/schemaGenerator.js +113 -298
  71. package/dist/migrate/storage/databaseStorage.d.ts +2 -1
  72. package/dist/migrate/storage/databaseStorage.js +3 -2
  73. package/dist/migrate/storage/jsonStorage.d.ts +1 -2
  74. package/dist/migrate/storage/jsonStorage.js +11 -20
  75. package/dist/migrate/triggerSql.d.ts +3 -3
  76. package/dist/migrate/triggerSql.js +5 -4
  77. package/dist/mongo/index.d.ts +0 -1
  78. package/dist/mongo/index.js +0 -1
  79. package/dist/mongo/mongoDialect.js +0 -1
  80. package/dist/mongo/mongoIntrospector.d.ts +0 -3
  81. package/dist/mongo/mongoIntrospector.js +7 -14
  82. package/dist/mongo/mongoSchemaGenerator.d.ts +7 -20
  83. package/dist/mongo/mongoSchemaGenerator.js +51 -70
  84. package/dist/mssql/mssqlDialect.js +0 -1
  85. package/dist/schema/canonicalType.d.ts +15 -19
  86. package/dist/schema/canonicalType.js +20 -43
  87. package/dist/schema/dependencyGraph.d.ts +2 -3
  88. package/dist/schema/dependencyGraph.js +0 -4
  89. package/dist/schema/indexDifferences.js +2 -2
  90. package/dist/schema/schemaAST.d.ts +1 -1
  91. package/dist/schema/schemaAST.js +4 -12
  92. package/dist/schema/schemaASTBuilder.d.ts +2 -5
  93. package/dist/schema/schemaASTBuilder.js +11 -14
  94. package/dist/schema/schemaASTDiffer.d.ts +4 -5
  95. package/dist/schema/schemaASTDiffer.js +22 -70
  96. package/dist/schema/types.d.ts +1 -48
  97. package/dist/sqlite/localSqliteQuerierPool.d.ts +16 -2
  98. package/dist/sqlite/localSqliteQuerierPool.js +20 -4
  99. package/dist/sqlite/nodeSqliteQuerierPool.js +2 -2
  100. package/dist/sqlite/sqliteDialect.js +0 -1
  101. package/dist/sqlite/sqliteQuerierPool.js +3 -3
  102. package/dist/type/dialect.d.ts +0 -2
  103. package/dist/type/migration.d.ts +3 -54
  104. package/dist/util/ddlExpression.util.d.ts +2 -2
  105. package/dist/util/ddlExpression.util.js +3 -3
  106. package/dist/util/sql.util.d.ts +0 -8
  107. package/dist/util/sql.util.js +7 -12
  108. package/package.json +1 -1
  109. package/dist/migrate/introspection/baseSqlIntrospector.d.ts +0 -36
  110. package/dist/migrate/introspection/baseSqlIntrospector.js +0 -133
  111. package/dist/schema/index.d.ts +0 -2
  112. package/dist/schema/index.js +0 -1
  113. package/dist/sqlite/sqlitePragmas.d.ts +0 -3
  114. package/dist/sqlite/sqlitePragmas.js +0 -15
@@ -43,17 +43,13 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
43
43
  }
44
44
  tableExistsQuery() {
45
45
  return /*sql*/ `
46
- SELECT COUNT(*) as count
47
- FROM information_schema.TABLES
48
- WHERE TABLE_SCHEMA = ${this.schemaExpr}
49
- AND TABLE_NAME = ?
46
+ SELECT 1 FROM information_schema.TABLES
47
+ WHERE TABLE_SCHEMA = ${this.schemaExpr} AND TABLE_NAME = ? AND TABLE_TYPE = 'BASE TABLE'
50
48
  `;
51
49
  }
52
- parseTableExistsResult([row]) {
53
- return Number(row.count) > 0;
54
- }
55
- getColumnsQuery(_tableName) {
56
- return /*sql*/ `
50
+ async getColumns(read, tableName) {
51
+ const rows = await read(
52
+ /*sql*/ `
57
53
  SELECT
58
54
  COLUMN_NAME as column_name,
59
55
  DATA_TYPE as data_type,
@@ -64,7 +60,6 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
64
60
  NUMERIC_PRECISION as numeric_precision,
65
61
  NUMERIC_SCALE as numeric_scale,
66
62
  DATETIME_PRECISION as datetime_precision,
67
- COLUMN_KEY as column_key,
68
63
  EXTRA as extra,
69
64
  CASE WHEN EXTRA LIKE '%STORED GENERATED%' THEN GENERATION_EXPRESSION END as generated_as,
70
65
  COLUMN_COMMENT as column_comment
@@ -72,10 +67,25 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
72
67
  WHERE TABLE_SCHEMA = ${this.schemaExpr}
73
68
  AND TABLE_NAME = ?
74
69
  ORDER BY ORDINAL_POSITION
75
- `;
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
+ }));
76
85
  }
77
- getIndexesQuery(_tableName) {
78
- return /*sql*/ `
86
+ async getIndexes(read, tableName) {
87
+ const rows = await read(
88
+ /*sql*/ `
79
89
  SELECT
80
90
  INDEX_NAME as index_name,
81
91
  GROUP_CONCAT(COALESCE(COLUMN_NAME, '') ORDER BY SEQ_IN_INDEX) as columns,
@@ -87,10 +97,20 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
87
97
  AND INDEX_NAME != 'PRIMARY'
88
98
  GROUP BY INDEX_NAME, NON_UNIQUE
89
99
  ORDER BY INDEX_NAME
90
- `;
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
+ }));
91
110
  }
92
- getForeignKeysQuery(_tableName) {
93
- return /*sql*/ `
111
+ async getForeignKeys(read, tableName) {
112
+ const rows = await read(
113
+ /*sql*/ `
94
114
  SELECT
95
115
  kcu.CONSTRAINT_NAME as constraint_name,
96
116
  GROUP_CONCAT(kcu.COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) as columns,
@@ -107,49 +127,20 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
107
127
  AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
108
128
  GROUP BY kcu.CONSTRAINT_NAME, kcu.REFERENCED_TABLE_NAME, rc.DELETE_RULE, rc.UPDATE_RULE
109
129
  ORDER BY kcu.CONSTRAINT_NAME
110
- `;
130
+ `, [tableName]);
131
+ return this.joinedForeignKeys(rows);
111
132
  }
112
- getPrimaryKeyQuery(_tableName) {
113
- 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*/ `
114
137
  SELECT COLUMN_NAME as column_name
115
138
  FROM information_schema.KEY_COLUMN_USAGE
116
139
  WHERE TABLE_SCHEMA = ${this.schemaExpr}
117
140
  AND TABLE_NAME = ?
118
141
  AND CONSTRAINT_NAME = 'PRIMARY'
119
142
  ORDER BY ORDINAL_POSITION
120
- `;
121
- }
122
- async mapColumnsResult(_read, _tableName, results) {
123
- return results.map((row) => ({
124
- name: row.column_name,
125
- type: row.column_type.toUpperCase(),
126
- nullable: row.is_nullable === 'YES',
127
- defaultValue: this.parseDefaultValue(row.column_default, row.extra),
128
- isPrimaryKey: row.column_key === 'PRI',
129
- isAutoIncrement: row.extra.toLowerCase().includes('auto_increment'),
130
- isUnique: row.column_key === 'UNI',
131
- // A `VECTOR`'s is its bytes, four a dimension, which `column_type` already states as dimensions.
132
- length: /^vector/i.test(row.column_type) ? undefined : this.toNumber(row.character_maximum_length),
133
- // A timestamp's fractional digits, stated even when 0, which uql's own unstated `DATETIME(3)` is not.
134
- precision: this.toNumber(TIMESTAMP_TYPES.has(row.data_type) ? row.datetime_precision : row.numeric_precision),
135
- scale: this.toNumber(row.numeric_scale),
136
- comment: row.column_comment || undefined,
137
- generatedAs: row.generated_as ?? undefined,
138
- }));
139
- }
140
- async mapIndexesResult(_read, _tableName, results) {
141
- return results.map((row) => ({
142
- name: row.index_name,
143
- ...(row.method === 'VECTOR' && { type: 'vector' }),
144
- // A functional or multi-valued key part has no `COLUMN_NAME` - the `COALESCE` above keeps its
145
- // place in the list, and it is reported as the expression it is, which is what stops diffing
146
- // from comparing an entry list the server cannot state against the entity's own.
147
- entries: row.columns.split(',').map((column) => (column ? { column } : { column, expression: true })),
148
- unique: Boolean(row.is_unique),
149
- }));
150
- }
151
- async mapForeignKeysResult(_read, _tableName, results) {
152
- return this.joinedForeignKeys(results);
143
+ `, tableName);
153
144
  }
154
145
  /**
155
146
  * MySQL prints a literal default unquoted, except one wrapped as `DEFAULT ('x')`, the form a `TEXT`
@@ -200,7 +191,7 @@ const TIMESTAMP_TYPES = new Set(['datetime', 'timestamp']);
200
191
  export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
201
192
  /**
202
193
  * A check's name is unique only in its table on MariaDB, whose `CHECK_CONSTRAINTS` names the table. A
203
- * JSON column's `json_valid()` is its type, read by {@link mapColumnsResult}, so it is left out.
194
+ * JSON column's `json_valid()` is its type, read by {@link getColumns}, so it is left out.
204
195
  */
205
196
  async getChecks(read, tableName) {
206
197
  return read(
@@ -221,8 +212,8 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
221
212
  * A vector index's distance is kept only in the table's own definition, ``VECTOR KEY `ix` (`vec`)
222
213
  * `DISTANCE`='cosine'``, and left out there for MariaDB's default, euclidean.
223
214
  */
224
- async mapIndexesResult(read, tableName, results) {
225
- const indexes = await super.mapIndexesResult(read, tableName, results);
215
+ async getIndexes(read, tableName) {
216
+ const indexes = await super.getIndexes(read, tableName);
226
217
  if (!indexes.some((index) => index.type === 'vector')) {
227
218
  return indexes;
228
219
  }
@@ -240,8 +231,8 @@ export class MariadbSchemaIntrospector extends MysqlSchemaIntrospector {
240
231
  return { ...index, distance: this.dialect.indexedDistance(metric) };
241
232
  });
242
233
  }
243
- async mapColumnsResult(read, tableName, results) {
244
- const columns = await super.mapColumnsResult(read, tableName, results);
234
+ async getColumns(read, tableName) {
235
+ const columns = await super.getColumns(read, tableName);
245
236
  const checks = await read(
246
237
  /*sql*/ `
247
238
  SELECT CONSTRAINT_NAME as column_name
@@ -1,7 +1,7 @@
1
1
  import type { IndexFacet } from '../../schema/indexDifferences.js';
2
2
  import { type CheckSchema } from '../../schema/types.js';
3
- import type { ColumnSchema, ForeignKeySchema, IndexSchema, RawRow } from '../../type/index.js';
4
- import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
3
+ import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema } from '../../type/index.js';
4
+ import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
5
5
  /**
6
6
  * PostgreSQL schema introspector
7
7
  */
@@ -11,13 +11,12 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
11
11
  * Expressions and predicates are read back too, for `generate:from-db`, but they are text the
12
12
  * database reprints in its own words, so they are not comparable and are not claimed here.
13
13
  */
14
- readonly indexFacets: ReadonlySet<IndexFacet>;
14
+ protected readonly indexFacets: ReadonlySet<IndexFacet>;
15
15
  protected triggersQuery(): string;
16
16
  /** `pg_get_expr` answers NULL for a table dropped mid-read, where `pg_get_constraintdef` raises. */
17
17
  protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
18
18
  protected getTableNamesQuery(): string;
19
19
  protected tableExistsQuery(): string;
20
- protected parseTableExistsResult([row]: RawRow[]): boolean;
21
20
  /**
22
21
  * The comment reads through `to_regclass` rather than a `::regclass` cast: a name resolves against
23
22
  * the live catalogue while `information_schema` answers from this statement's snapshot, so a table
@@ -28,10 +27,10 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
28
27
  * virtual one Postgres 18 added and uql never declares. CockroachDB states it too. `format_type` for an
29
28
  * extension type's modifier, which `information_schema` drops: a `vector(256)` read back as `vector`.
30
29
  * CockroachDB names that type `vector` where Postgres says `USER-DEFINED`.
31
- *
32
- * A column is unique by a unique index over it alone, a constraint's or its own, as every engine reads it.
33
30
  */
34
- 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;
35
34
  /**
36
35
  * `attname` where the entry is a column, `pg_get_indexdef` for that one position where it is an
37
36
  * expression. Neither alone will do: an expression entry has `attnum = 0`, so joining `pg_attribute`
@@ -43,7 +42,7 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
43
42
  * and the MySQL family report theirs: the diff reads one over a single column as that column's
44
43
  * uniqueness, and one over several as the unique `@Index` it is.
45
44
  */
46
- protected getIndexesQuery(_tableName: string): string;
45
+ protected getIndexes(read: TableRowReader, tableName: string): Promise<IndexSchema[]>;
47
46
  /** Whether an entry sorts nulls first, which Postgres states on every entry. */
48
47
  protected readonly nullsFirstSql: string;
49
48
  /** An index's access method, which is the type it declares. */
@@ -51,17 +50,14 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
51
50
  /** An entry's operator class, where it is not the default for its type. */
52
51
  protected readonly opsClassSql: string;
53
52
  /** From `pg_constraint`, whose key arrays keep each column paired with the one it references. */
54
- protected getForeignKeysQuery(_tableName: string): string;
55
- protected getPrimaryKeyQuery(_tableName: string): string;
56
- 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>;
57
55
  /**
58
56
  * A vector index keeps its distance as its vector column's operator class, `{type}_{metric}_ops`, which
59
57
  * is how `PgIndexDdl` writes the entity's `distance`; read back as that `distance`, so the two compare.
60
58
  * No class named is the engine's default, L2.
61
59
  */
62
60
  private withVectorDistance;
63
- protected mapIndexesResult(_read: TableRowReader, _tableName: string, results: PostgresIndexRow[]): Promise<IndexSchema[]>;
64
- protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: PostgresForeignKeyRow[]): Promise<ForeignKeySchema[]>;
65
61
  protected normalizeType(dataType: string, udtName: string): string;
66
62
  /**
67
63
  * Postgres quotes a negative number (`'-3'::integer`); CockroachDB parenthesizes one (`(-3)`) and
@@ -71,14 +67,6 @@ export declare class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrosp
71
67
  protected parseDefaultValue(defaultValue: string | null): unknown;
72
68
  protected isAutoIncrement(columnDefault: string | null, isIdentity: string): boolean;
73
69
  }
74
- /** `pg_constraint`'s one-letter spelling of each action. */
75
- declare const FOREIGN_KEY_ACTION_CODES: {
76
- readonly a: 'NO ACTION';
77
- readonly r: 'RESTRICT';
78
- readonly c: 'CASCADE';
79
- readonly n: 'SET NULL';
80
- readonly d: 'SET DEFAULT';
81
- };
82
70
  /**
83
71
  * CockroachDB answers the same catalogue queries and differs only in what it can express: v26.2.5
84
72
  * still rejects `NULLS FIRST/LAST` and operator classes as "unimplemented", and it sorts nulls first
@@ -86,7 +74,9 @@ declare const FOREIGN_KEY_ACTION_CODES: {
86
74
  * every ascending index as drifted, against an entity that could not have asked for one.
87
75
  */
88
76
  export declare class CockroachSchemaIntrospector extends PostgresSchemaIntrospector {
89
- 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'";
90
80
  /** None: it rejects a stated nulls order, so reading one back gives an index it would refuse to rebuild. */
91
81
  protected readonly nullsFirstSql = "NULL::BOOL";
92
82
  /**
@@ -96,41 +86,3 @@ export declare class CockroachSchemaIntrospector extends PostgresSchemaIntrospec
96
86
  protected readonly indexMethodSql = "CASE WHEN pg_get_indexdef(ix.indexrelid) LIKE '% USING cspann %' THEN 'vector' ELSE am.amname END";
97
87
  protected readonly opsClassSql = "CASE WHEN k.n = ix.indnkeyatts THEN substring(pg_get_indexdef(ix.indexrelid) from '(\\w+_ops)\\)') END";
98
88
  }
99
- type PostgresForeignKeyRow = {
100
- constraint_name: string;
101
- columns: string[];
102
- referenced_table: string;
103
- referenced_columns: string[];
104
- delete_rule: keyof typeof FOREIGN_KEY_ACTION_CODES;
105
- update_rule: keyof typeof FOREIGN_KEY_ACTION_CODES;
106
- };
107
- /** One entry of one index; what the index itself is repeats across its rows. */
108
- type PostgresIndexRow = {
109
- index_name: string;
110
- is_unique: boolean;
111
- method: string;
112
- predicate: string | null;
113
- is_key: boolean;
114
- is_expression: boolean;
115
- entry: string;
116
- descending: boolean;
117
- nulls_first: boolean | null;
118
- ops_class: string | null;
119
- };
120
- type PostgresColumnRow = {
121
- column_name: string;
122
- data_type: string;
123
- udt_name: string;
124
- formatted_type: string | null;
125
- is_nullable: string;
126
- column_default: string | null;
127
- is_primary_key: boolean;
128
- is_identity: string;
129
- is_unique: boolean;
130
- character_maximum_length: number | null;
131
- numeric_precision: number | null;
132
- numeric_scale: number | null;
133
- column_comment: string | null;
134
- generated_as: string | null;
135
- };
136
- export {};
@@ -1,6 +1,6 @@
1
1
  import { INDEX_TYPES } from '../../schema/types.js';
2
2
  import { isVectorIndexType } from '../../type/vector.js';
3
- import { AbstractSqlSchemaIntrospector } from './abstractSqlSchemaIntrospector.js';
3
+ import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
4
4
  /**
5
5
  * PostgreSQL schema introspector
6
6
  */
@@ -50,16 +50,10 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
50
50
  }
51
51
  tableExistsQuery() {
52
52
  return /*sql*/ `
53
- SELECT EXISTS (
54
- SELECT FROM information_schema.tables
55
- WHERE table_schema = ${this.schemaExpr}
56
- AND table_name = $1
57
- ) AS exists
53
+ SELECT 1 FROM information_schema.tables
54
+ WHERE table_schema = ${this.schemaExpr} AND table_name = $1 AND table_type = 'BASE TABLE'
58
55
  `;
59
56
  }
60
- parseTableExistsResult([row]) {
61
- return row['exists'] === true;
62
- }
63
57
  /**
64
58
  * The comment reads through `to_regclass` rather than a `::regclass` cast: a name resolves against
65
59
  * the live catalogue while `information_schema` answers from this statement's snapshot, so a table
@@ -70,11 +64,10 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
70
64
  * virtual one Postgres 18 added and uql never declares. CockroachDB states it too. `format_type` for an
71
65
  * extension type's modifier, which `information_schema` drops: a `vector(256)` read back as `vector`.
72
66
  * CockroachDB names that type `vector` where Postgres says `USER-DEFINED`.
73
- *
74
- * A column is unique by a unique index over it alone, a constraint's or its own, as every engine reads it.
75
67
  */
76
- getColumnsQuery(_tableName) {
77
- return /*sql*/ `
68
+ async getColumns(read, tableName) {
69
+ const rows = await read(
70
+ /*sql*/ `
78
71
  SELECT
79
72
  c.column_name,
80
73
  c.data_type,
@@ -89,20 +82,6 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
89
82
  CASE WHEN a.attgenerated = 's' THEN c.generation_expression END AS generated_as,
90
83
  CASE WHEN (c.data_type IN ('USER-DEFINED', 'vector') OR c.data_type LIKE 'timestamp%') AND a.atttypmod > -1
91
84
  THEN format_type(a.atttypid, a.atttypmod) END AS formatted_type,
92
- EXISTS (
93
- SELECT 1 FROM information_schema.table_constraints tc
94
- JOIN information_schema.key_column_usage kcu USING (constraint_schema, constraint_name)
95
- WHERE tc.table_schema = c.table_schema
96
- AND tc.table_name = c.table_name
97
- AND tc.constraint_type = 'PRIMARY KEY'
98
- AND kcu.column_name = c.column_name
99
- ) AS is_primary_key,
100
- EXISTS (
101
- SELECT 1 FROM pg_catalog.pg_index ix
102
- WHERE ix.indrelid = a.attrelid AND ix.indisunique AND NOT ix.indisprimary
103
- AND ix.indnkeyatts = 1 AND ix.indkey[0] = a.attnum
104
- AND ix.indpred IS NULL AND ix.indexprs IS NULL
105
- ) AS is_unique,
106
85
  pg_catalog.col_description(
107
86
  to_regclass(quote_ident(c.table_schema) || '.' || quote_ident(c.table_name)),
108
87
  c.ordinal_position
@@ -113,9 +92,24 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
113
92
  AND a.attname = c.column_name
114
93
  WHERE c.table_schema = ${this.schemaExpr}
115
94
  AND c.table_name = $1
95
+ AND ${this.visibleColumnSql}
116
96
  ORDER BY c.ordinal_position
117
- `;
97
+ `, [tableName]);
98
+ return rows.map((row) => ({
99
+ name: row.column_name,
100
+ type: row.formatted_type?.toUpperCase() ?? this.normalizeType(row.data_type, row.udt_name),
101
+ nullable: row.is_nullable === 'YES',
102
+ defaultValue: this.parseDefaultValue(row.column_default),
103
+ isAutoIncrement: this.isAutoIncrement(row.column_default, row.is_identity),
104
+ length: row.character_maximum_length ?? undefined,
105
+ precision: row.numeric_precision ?? undefined,
106
+ scale: row.numeric_scale ?? undefined,
107
+ comment: row.column_comment ?? undefined,
108
+ generatedAs: row.generated_as ?? undefined,
109
+ }));
118
110
  }
111
+ /** Whether `information_schema.columns c` lists a column the table shows: every one, on Postgres. */
112
+ visibleColumnSql = 'TRUE';
119
113
  /**
120
114
  * `attname` where the entry is a column, `pg_get_indexdef` for that one position where it is an
121
115
  * expression. Neither alone will do: an expression entry has `attnum = 0`, so joining `pg_attribute`
@@ -127,8 +121,9 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
127
121
  * and the MySQL family report theirs: the diff reads one over a single column as that column's
128
122
  * uniqueness, and one over several as the unique `@Index` it is.
129
123
  */
130
- getIndexesQuery(_tableName) {
131
- return /*sql*/ `
124
+ async getIndexes(read, tableName) {
125
+ const rows = await read(
126
+ /*sql*/ `
132
127
  SELECT
133
128
  i.relname AS index_name,
134
129
  ix.indisunique AS is_unique,
@@ -155,7 +150,21 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
155
150
  SELECT 1 FROM pg_constraint con WHERE con.conindid = ix.indexrelid AND con.contype = 'x'
156
151
  )
157
152
  ORDER BY i.relname, k.n
158
- `;
153
+ `, [tableName]);
154
+ // One row per index entry, ordered by position, so the rows of an index are its entries in order.
155
+ return [...Map.groupBy(rows, (row) => row.index_name)].map(([name, ofIndex]) => {
156
+ const [first] = ofIndex;
157
+ const include = ofIndex.filter((row) => !row.is_key).map((row) => row.entry);
158
+ return this.withVectorDistance({
159
+ name,
160
+ entries: ofIndex.filter((row) => row.is_key).map(mapIndexEntry),
161
+ unique: first.is_unique,
162
+ type: INDEX_TYPES.find((type) => type === first.method),
163
+ where: first.predicate ?? undefined,
164
+ include: include.length > 0 ? include : undefined,
165
+ ...fulltextIndex(ofIndex),
166
+ });
167
+ });
159
168
  }
160
169
  /** Whether an entry sorts nulls first, which Postgres states on every entry. */
161
170
  nullsFirstSql = '(ix.indoption[k.n - 1] & 2) <> 0';
@@ -164,13 +173,14 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
164
173
  /** An entry's operator class, where it is not the default for its type. */
165
174
  opsClassSql = 'CASE WHEN op.opcdefault THEN NULL ELSE op.opcname END';
166
175
  /** From `pg_constraint`, whose key arrays keep each column paired with the one it references. */
167
- getForeignKeysQuery(_tableName) {
176
+ async getForeignKeys(read, tableName) {
168
177
  const columnsOf = (keys, table) => /*sql*/ `ARRAY_TO_JSON(ARRAY(
169
178
  SELECT a.attname FROM UNNEST(${keys}) WITH ORDINALITY AS k(attnum, n)
170
179
  JOIN pg_attribute a ON a.attrelid = ${table} AND a.attnum = k.attnum
171
180
  ORDER BY k.n
172
181
  ))`;
173
- return /*sql*/ `
182
+ const rows = await read(
183
+ /*sql*/ `
174
184
  SELECT
175
185
  con.conname AS constraint_name,
176
186
  ${columnsOf('con.conkey', 'con.conrelid')} AS columns,
@@ -186,36 +196,33 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
186
196
  AND t.relname = $1
187
197
  AND n.nspname = ${this.schemaExpr}
188
198
  ORDER BY con.conname
189
- `;
199
+ `, [tableName]);
200
+ return rows.map((row) => ({
201
+ name: row.constraint_name,
202
+ columns: row.columns,
203
+ references: { table: row.referenced_table, columns: row.referenced_columns },
204
+ onDelete: FOREIGN_KEY_ACTION_CODES[row.delete_rule],
205
+ onUpdate: FOREIGN_KEY_ACTION_CODES[row.update_rule],
206
+ }));
190
207
  }
191
- getPrimaryKeyQuery(_tableName) {
192
- return /*sql*/ `
208
+ getPrimaryKey(read, tableName) {
209
+ return this.readPrimaryKey(read,
210
+ /*sql*/ `
193
211
  SELECT kcu.column_name, tc.constraint_name
194
212
  FROM information_schema.table_constraints tc
195
213
  JOIN information_schema.key_column_usage kcu
196
214
  ON tc.constraint_name = kcu.constraint_name
197
215
  AND tc.table_schema = kcu.table_schema
216
+ JOIN information_schema.columns c
217
+ ON c.table_schema = kcu.table_schema
218
+ AND c.table_name = kcu.table_name
219
+ AND c.column_name = kcu.column_name
198
220
  WHERE tc.constraint_type = 'PRIMARY KEY'
199
221
  AND tc.table_name = $1
200
222
  AND tc.table_schema = ${this.schemaExpr}
223
+ AND ${this.visibleColumnSql}
201
224
  ORDER BY kcu.ordinal_position
202
- `;
203
- }
204
- async mapColumnsResult(_read, _tableName, results) {
205
- return results.map((row) => ({
206
- name: row.column_name,
207
- type: row.formatted_type?.toUpperCase() ?? this.normalizeType(row.data_type, row.udt_name),
208
- nullable: row.is_nullable === 'YES',
209
- defaultValue: this.parseDefaultValue(row.column_default),
210
- isPrimaryKey: row.is_primary_key,
211
- isAutoIncrement: this.isAutoIncrement(row.column_default, row.is_identity),
212
- isUnique: row.is_unique,
213
- length: row.character_maximum_length ?? undefined,
214
- precision: row.numeric_precision ?? undefined,
215
- scale: row.numeric_scale ?? undefined,
216
- comment: row.column_comment ?? undefined,
217
- generatedAs: row.generated_as ?? undefined,
218
- }));
225
+ `, tableName);
219
226
  }
220
227
  /**
221
228
  * A vector index keeps its distance as its vector column's operator class, `{type}_{metric}_ops`, which
@@ -231,30 +238,6 @@ export class PostgresSchemaIntrospector extends AbstractSqlSchemaIntrospector {
231
238
  const entries = index.entries.map(({ opsClass: _opsClass, ...entry }) => entry);
232
239
  return distance ? { ...index, distance, entries } : index;
233
240
  }
234
- async mapIndexesResult(_read, _tableName, results) {
235
- // One row per index entry, ordered by position, so the rows of an index are its entries in order.
236
- return [...Map.groupBy(results, (row) => row.index_name)].map(([name, rows]) => {
237
- const include = rows.filter((row) => !row.is_key).map((row) => row.entry);
238
- return this.withVectorDistance({
239
- name,
240
- entries: rows.filter((row) => row.is_key).map(mapIndexEntry),
241
- unique: rows[0].is_unique,
242
- type: INDEX_TYPES.find((type) => type === rows[0].method),
243
- where: rows[0].predicate ?? undefined,
244
- include: include.length > 0 ? include : undefined,
245
- ...fulltextIndex(rows),
246
- });
247
- });
248
- }
249
- async mapForeignKeysResult(_read, _tableName, results) {
250
- return results.map((row) => ({
251
- name: row.constraint_name,
252
- columns: row.columns,
253
- references: { table: row.referenced_table, columns: row.referenced_columns },
254
- onDelete: FOREIGN_KEY_ACTION_CODES[row.delete_rule],
255
- onUpdate: FOREIGN_KEY_ACTION_CODES[row.update_rule],
256
- }));
257
- }
258
241
  normalizeType(dataType, udtName) {
259
242
  // Handle user-defined types and arrays
260
243
  if (dataType === 'USER-DEFINED') {
@@ -356,6 +339,8 @@ export class CockroachSchemaIntrospector extends PostgresSchemaIntrospector {
356
339
  'vector',
357
340
  'distance',
358
341
  ]);
342
+ /** Not `rowid`, the `NOT VISIBLE` key it gives a table declared without one, which no entity can name. */
343
+ visibleColumnSql = "c.is_hidden = 'NO'";
359
344
  /** None: it rejects a stated nulls order, so reading one back gives an index it would refuse to rebuild. */
360
345
  nullsFirstSql = 'NULL::BOOL';
361
346
  /**
@@ -1,46 +1,37 @@
1
1
  import type { IndexFacet } from '../../schema/indexDifferences.js';
2
2
  import type { CheckSchema } from '../../schema/types.js';
3
- import type { ColumnSchema, ForeignKeySchema, IndexSchema, StoredDefinition } from '../../type/index.js';
4
- import { AbstractSqlSchemaIntrospector, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
3
+ import type { ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../../type/index.js';
4
+ import { AbstractSqlSchemaIntrospector, type ReadColumn, type TableRowReader } from './abstractSqlSchemaIntrospector.js';
5
5
  /**
6
6
  * SQLite schema introspector
7
7
  */
8
8
  export declare class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospector {
9
9
  /** Whether an index is libSQL's vector index, where the engine has one; elsewhere a declared one is built plain. */
10
- readonly indexFacets: ReadonlySet<IndexFacet>;
10
+ protected readonly indexFacets: ReadonlySet<IndexFacet>;
11
11
  protected triggersQuery(): string;
12
12
  /** User tables only: skips SQLite's own and libSQL's vector index tables (its metadata and `<index>_shadow`). */
13
13
  protected getTableNamesQuery(): string;
14
14
  protected tableExistsQuery(): string;
15
- protected parseTableExistsResult([row]: SqliteCountRow[]): boolean;
16
15
  /**
17
16
  * `table_xinfo`, not `table_info`: the latter omits generated columns entirely, so a table carrying
18
17
  * one read back without it and every sync offered to add a column that was already there - which
19
- * SQLite cannot do to an existing table anyway. PRAGMA takes no bound parameters, hence the splice.
18
+ * SQLite cannot do to an existing table anyway. Also the key, by each column's `pk`: one statement for both.
20
19
  */
21
- protected getColumnsQuery(tableName: string): string;
22
- protected getIndexesQuery(tableName: string): string;
23
- protected getForeignKeysQuery(tableName: string): string;
24
- protected getPrimaryKeyQuery(tableName: string): string;
25
- protected getColumnsParams(_tableName: string): unknown[];
26
- protected getIndexesParams(_tableName: string): unknown[];
27
- protected getForeignKeysParams(_tableName: string): unknown[];
28
- protected getPrimaryKeyParams(_tableName: string): unknown[];
29
- /** `sqlite_master`, not `information_schema`, so the column is `name`. */
30
- protected mapTableNameRow(row: {
31
- name: string;
32
- }): string;
33
- protected mapColumnsResult(read: TableRowReader, tableName: string, results: SqliteColumnRow[]): Promise<ColumnSchema[]>;
34
- protected mapIndexesResult(read: TableRowReader, _tableName: string, results: SqliteIndexRow[]): Promise<IndexSchema[]>;
35
- protected mapForeignKeysResult(_read: TableRowReader, _tableName: string, results: SqliteForeignKeyRow[]): Promise<ForeignKeySchema[]>;
20
+ private tableInfo;
21
+ protected getColumns(read: TableRowReader, tableName: string): Promise<ReadColumn[]>;
22
+ protected getPrimaryKey(read: TableRowReader, tableName: string): Promise<PrimaryKeySchema | undefined>;
23
+ protected getIndexes(read: TableRowReader, tableName: string): Promise<IndexSchema[]>;
24
+ /**
25
+ * A row per column of each key, grouped by its id. Unnamed: `PRAGMA foreign_key_list` reports none, so the
26
+ * AST derives one from the columns, as the entity side does.
27
+ */
28
+ protected getForeignKeys(read: TableRowReader, tableName: string): Promise<ForeignKeySchema[]>;
36
29
  /** The named checks in the table's `CREATE TABLE`, the only place SQLite keeps one. */
37
30
  protected getChecks(read: TableRowReader, tableName: string): Promise<CheckSchema[]>;
38
31
  /** Every statement `sqlite_master` keeps for the table, its `CREATE TABLE` first. An automatic index has none. */
39
32
  protected getDefinition(read: TableRowReader, tableName: string): Promise<StoredDefinition[]>;
40
- protected mapPrimaryKeyResult(results: SqliteColumnRow[]): string[] | undefined;
41
- private getUniqueColumns;
42
33
  /** libSQL's `libsql_vector_idx(col, 'metric=...')`, read back from the statement that created it. */
43
- private getVectorIndex;
34
+ private vectorIndex;
44
35
  private getIndexColumns;
45
36
  protected normalizeType(type: string): string;
46
37
  protected extractLength(type: string): number | undefined;
@@ -51,35 +42,5 @@ export declare class SqliteSchemaIntrospector extends AbstractSqlSchemaIntrospec
51
42
  * reports one, and SQLite keeps the statement's text exactly as it was given.
52
43
  */
53
44
  export declare function generatedExpression(ddl: string, column: string): string | undefined;
54
- type SqliteCountRow = {
55
- count: number | bigint;
56
- };
57
- type SqliteColumnRow = {
58
- name: string;
59
- type: string;
60
- notnull: number;
61
- dflt_value: string | null;
62
- pk: number;
63
- /** `PRAGMA table_xinfo`'s flag: 0 ordinary, 1 a hidden `VIRTUAL` table column, 2 virtual, 3 stored. Absent from `table_info`. */
64
- hidden?: number;
65
- };
66
- type SqliteIndexRow = {
67
- seq: number;
68
- name: string;
69
- unique: number;
70
- origin: string;
71
- partial: number;
72
- };
73
- type SqliteForeignKeyRow = {
74
- id: number;
75
- seq: number;
76
- table: string;
77
- from: string;
78
- to: string;
79
- on_update: string;
80
- on_delete: string;
81
- match: string;
82
- };
83
45
  /** Each `CONSTRAINT <name> CHECK (...)` in a `CREATE TABLE`, the only place SQLite keeps one. */
84
46
  export declare function namedChecks(ddl: string): CheckSchema[];
85
- export {};