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
@@ -41,12 +41,22 @@ export type ForeignKeyAction = (typeof FOREIGN_KEY_ACTIONS)[number];
41
41
  * dialect's own literal rules, so a number stays bare where a string is quoted.
42
42
  */
43
43
  export type EnumValues = readonly (string | number)[];
44
- /** A `CHECK` as the schema holds it, compared by presence only: the database reprints its expression. */
44
+ /**
45
+ * A `CHECK`, compared by name alone: one uql installs is named by `ownedCheck`, whose hash of the
46
+ * expression makes an edited one a new name. The expression is the engine's reprint when read back.
47
+ */
45
48
  export interface CheckSchema {
46
- /** Absent when nothing named it, which the generator fills in with `derivedCheckName`. */
47
- readonly name?: string;
49
+ readonly name: string;
48
50
  readonly expression: string;
49
51
  }
52
+ /**
53
+ * A trigger, compared by name alone as a check is: its name ends in a hash of its SQL. The statements create
54
+ * it; read back, they are the engine's own, which is what a rollback restores.
55
+ */
56
+ export interface TriggerSchema {
57
+ readonly name: string;
58
+ readonly statements: readonly string[];
59
+ }
50
60
  /**
51
61
  * Default action for foreign key ON DELETE and ON UPDATE clauses.
52
62
  */
@@ -79,18 +89,12 @@ export interface ColumnNode {
79
89
  readonly isAutoIncrement: boolean;
80
90
  /** Whether this column has a unique constraint */
81
91
  readonly isUnique: boolean;
82
- /** The values the column accepts. See {@link EnumValues}. */
83
- readonly enum?: EnumValues;
84
92
  /** The SQL an engine-generated column is computed from, as `GENERATED ALWAYS AS (...) STORED`. */
85
93
  readonly generatedAs?: string;
86
94
  /** Column comment/description */
87
95
  readonly comment?: string;
88
- /** Reference to the parent table */
96
+ /** The table the column is in. */
89
97
  table: TableNode;
90
- /** Relationships where this column is referenced (FKs pointing TO this column) */
91
- referencedBy: RelationshipNode[];
92
- /** Relationship where this column is the foreign key (FK this column points FROM) */
93
- references?: RelationshipNode;
94
98
  }
95
99
  /**
96
100
  * Table node in the schema graph.
@@ -121,6 +125,8 @@ export interface TableNode {
121
125
  readonly indexFacets: ReadonlySet<IndexFacet>;
122
126
  /** `CHECK` constraints on this table. */
123
127
  readonly checks: CheckSchema[];
128
+ /** The triggers uql installs on this table. */
129
+ readonly triggers: TriggerSchema[];
124
130
  /** Optional table comment */
125
131
  readonly comment?: string;
126
132
  /** The statements the engine keeps for the table, where it keeps them; none on a table built from entities. */
@@ -184,7 +190,6 @@ export type ColumnDiff = NodeChange<ColumnNode, {
184
190
  readonly column: string;
185
191
  /** Whether the change can lose data: a drop, or a type change that narrows the column. */
186
192
  readonly isBreaking?: boolean;
187
- readonly description?: string;
188
193
  };
189
194
  /** A part of a column the differ compares. */
190
195
  export type ColumnFacet = 'type' | 'nullable' | 'default';
@@ -204,13 +209,17 @@ export type RelationshipDiff = NodeChange<RelationshipNode> & {
204
209
  * `(a, b)` differs from `(b, a)`, while `Member_pkey` and `Member__userId_pk` over the same columns are equal.
205
210
  * `from` keeps the name the database reported, the only name a `DROP` can use.
206
211
  */
207
- export type PrimaryKeyDiff = Change<PrimaryKeySchema> & {
212
+ export type PrimaryKeyDiff = TableChange<PrimaryKeySchema>;
213
+ /** One object of a table changed, named by the table. */
214
+ export type TableChange<T> = Change<T> & {
208
215
  readonly table: string;
209
216
  };
210
217
  /** The differences within a table that exists on both sides. */
211
218
  export interface TableDiff {
212
219
  readonly columns: ColumnDiff[];
213
- readonly indexes: IndexDiff[];
220
+ /** A check or trigger only one side has. Never both: a changed one is a new name, one dropped and one added. */
221
+ readonly checks: TableChange<CheckSchema>[];
222
+ readonly triggers: TableChange<TriggerSchema>[];
214
223
  /** Set only when the two primary keys have different columns. */
215
224
  readonly primaryKey?: PrimaryKeyDiff;
216
225
  }
@@ -220,47 +229,8 @@ export interface SchemaDiffResult {
220
229
  readonly tables: NodeChange<TableNode>[];
221
230
  readonly columns: ColumnDiff[];
222
231
  readonly indexes: IndexDiff[];
232
+ readonly checks: TableChange<CheckSchema>[];
233
+ readonly triggers: TableChange<TriggerSchema>[];
223
234
  readonly primaryKeys: PrimaryKeyDiff[];
224
235
  readonly relationships: RelationshipDiff[];
225
236
  }
226
- /**
227
- * Severity level for schema drift issues.
228
- */
229
- export type DriftSeverity = 'critical' | 'warning' | 'info';
230
- /**
231
- * Type of schema drift.
232
- */
233
- export type DriftType = 'missing_table' | 'unexpected_table' | 'missing_column' | 'unexpected_column' | 'type_mismatch' | 'constraint_mismatch' | 'missing_index' | 'unexpected_index' | 'index_mismatch' | 'missing_relationship' | 'unexpected_relationship' | 'relationship_mismatch';
234
- /**
235
- * A single schema drift issue.
236
- */
237
- export interface Drift {
238
- readonly type: DriftType;
239
- readonly severity: DriftSeverity;
240
- readonly table?: string;
241
- readonly column?: string;
242
- readonly index?: string;
243
- readonly relationship?: string;
244
- readonly expected?: unknown;
245
- readonly actual?: unknown;
246
- readonly details: string;
247
- readonly suggestion: string;
248
- }
249
- /**
250
- * Overall drift status.
251
- */
252
- export type DriftStatus = 'in_sync' | 'drifted' | 'critical';
253
- /**
254
- * Complete drift detection report.
255
- */
256
- export interface DriftReport {
257
- readonly status: DriftStatus;
258
- readonly drifts: Drift[];
259
- readonly generatedAt: Date;
260
- /** Count by severity */
261
- readonly summary: {
262
- readonly critical: number;
263
- readonly warning: number;
264
- readonly info: number;
265
- };
266
- }
@@ -17,6 +17,10 @@ export type LocalSqlitePoolOptions = {
17
17
  export type LocalSqliteDatabase = {
18
18
  prepare(sql: string): SqlitePreparedStatement;
19
19
  loadExtension(path: string): void;
20
+ /** Defines a SQL function, which `bun:sqlite` cannot. */
21
+ function?(name: string, options: {
22
+ deterministic: boolean;
23
+ }, fn: (...args: SqlValue[]) => SqlValue): unknown;
20
24
  close(): unknown;
21
25
  };
22
26
  /**
@@ -26,12 +30,22 @@ export type LocalSqliteDatabase = {
26
30
  export declare function adaptSqlite<S extends Omit<SqlitePreparedStatement, 'reader'>>(db: Omit<LocalSqliteDatabase, 'prepare'> & {
27
31
  prepare(sql: string): S;
28
32
  }, reads: (stmt: S) => boolean): LocalSqliteDatabase;
29
- /** `db` with each loadable extension installed, which `node:sqlite` refuses unless opened to allow them. */
30
- export declare function loadExtensions(db: LocalSqliteDatabase, extensions?: readonly string[]): LocalSqliteDatabase;
33
+ /**
34
+ * `db` extended past SQLite's own: each loadable extension installed, which `node:sqlite` refuses unless
35
+ * opened to allow them, and `REGEXP` defined as libSQL builds it in, which SQLite leaves to the application.
36
+ */
37
+ export declare function extendSqlite(db: LocalSqliteDatabase, extensions?: readonly string[]): LocalSqliteDatabase;
38
+ /** A value SQLite hands a function, and takes back. */
39
+ type SqlValue = string | number | bigint | Uint8Array | null;
31
40
  /** A pool for a database file opened in this process, configured the same way whichever driver's {@link createDb} opens it. */
32
41
  export declare abstract class AbstractLocalSqliteQuerierPool<DB extends SqliteDatabase, D extends SqliteDialect> extends AbstractSharedHandleQuerierPool<DB, SqliteQuerier, D> {
33
42
  /** Opens the driver's database, reading integers as `bigint`, which the querier decodes exactly past 2^53. */
34
43
  protected abstract createDb(): Promise<DB>;
44
+ /**
45
+ * WAL, so a reader does not wait on the writer, and `foreign_keys`, which SQLite ships off per connection:
46
+ * without it a declared `onDelete: 'CASCADE'` does nothing and a dangling reference is accepted.
47
+ */
35
48
  protected openDb(): Promise<DB>;
36
49
  protected buildQuerier(db: DB): SqliteQuerier;
37
50
  }
51
+ export {};
@@ -1,5 +1,4 @@
1
1
  import { AbstractSharedHandleQuerierPool } from '../querier/abstractSharedHandleQuerierPool.js';
2
- import { applySqlitePragmas } from './sqlitePragmas.js';
3
2
  import { SqliteQuerier } from './sqliteQuerier.js';
4
3
  /**
5
4
  * A `node:sqlite` or `bun:sqlite` handle as a {@link LocalSqliteDatabase}. Neither says whether a statement
@@ -17,21 +16,38 @@ export function adaptSqlite(db, reads) {
17
16
  };
18
17
  },
19
18
  loadExtension: (path) => db.loadExtension(path),
19
+ function: db.function?.bind(db),
20
20
  close: () => db.close(),
21
21
  };
22
22
  }
23
- /** `db` with each loadable extension installed, which `node:sqlite` refuses unless opened to allow them. */
24
- export function loadExtensions(db, extensions = []) {
23
+ /**
24
+ * `db` extended past SQLite's own: each loadable extension installed, which `node:sqlite` refuses unless
25
+ * opened to allow them, and `REGEXP` defined as libSQL builds it in, which SQLite leaves to the application.
26
+ */
27
+ export function extendSqlite(db, extensions = []) {
25
28
  for (const extension of extensions) {
26
29
  db.loadExtension(extension);
27
30
  }
31
+ db.function?.('regexp', { deterministic: true }, regexp);
28
32
  return db;
29
33
  }
34
+ /** `value REGEXP pattern`: NULL where the value is, as an operator answers. */
35
+ function regexp(pattern, value) {
36
+ return value === null ? null : Number(new RegExp(String(pattern)).test(String(value)));
37
+ }
30
38
  /** A pool for a database file opened in this process, configured the same way whichever driver's {@link createDb} opens it. */
31
39
  export class AbstractLocalSqliteQuerierPool extends AbstractSharedHandleQuerierPool {
40
+ /**
41
+ * WAL, so a reader does not wait on the writer, and `foreign_keys`, which SQLite ships off per connection:
42
+ * without it a declared `onDelete: 'CASCADE'` does nothing and a dangling reference is accepted.
43
+ */
32
44
  async openDb() {
33
45
  const db = await this.createDb();
34
- await applySqlitePragmas(db);
46
+ for (const pragma of ['journal_mode = WAL', 'foreign_keys = ON']) {
47
+ const stmt = await db.prepare(`PRAGMA ${pragma}`);
48
+ // `journal_mode` answers with a row and `foreign_keys` with none.
49
+ await (stmt.reader ? stmt.all() : stmt.run());
50
+ }
35
51
  return db;
36
52
  }
37
53
  buildQuerier(db) {
@@ -1,5 +1,5 @@
1
1
  import { dialectOptionsFrom } from '../dialect/abstractDialect.js';
2
- import { AbstractLocalSqliteQuerierPool, adaptSqlite, loadExtensions, } from './localSqliteQuerierPool.js';
2
+ import { AbstractLocalSqliteQuerierPool, adaptSqlite, extendSqlite, } from './localSqliteQuerierPool.js';
3
3
  import { SqliteDialect } from './sqliteDialect.js';
4
4
  /**
5
5
  * A pool over Node's built-in `node:sqlite`, needing no dependency at all. {@link Sqlite3QuerierPool} is the
@@ -22,6 +22,6 @@ export class NodeSqliteQuerierPool extends AbstractLocalSqliteQuerierPool {
22
22
  // `node:sqlite` refuses `loadExtension` unless the database was opened with this on.
23
23
  ...(extensions?.length ? { allowExtension: true } : undefined),
24
24
  });
25
- return loadExtensions(adaptSqlite(nodeDb, (stmt) => stmt.columns().length > 0), extensions);
25
+ return extendSqlite(adaptSqlite(nodeDb, (stmt) => stmt.columns().length > 0), extensions);
26
26
  }
27
27
  }
@@ -21,7 +21,6 @@ export const SQLITE_FEATURES = {
21
21
  schemas: false, // SQLite's namespaces are attached database files, not declared objects
22
22
  dropTableCascade: false,
23
23
  rebuildsTables: true,
24
- commentSyntax: 'none',
25
24
  vectorIndexRequiresNotNull: false,
26
25
  vectorSupportsLength: true,
27
26
  vectorBytes: true,
@@ -1,5 +1,5 @@
1
1
  import { dialectOptionsFrom } from '../dialect/abstractDialect.js';
2
- import { AbstractLocalSqliteQuerierPool, adaptSqlite, loadExtensions, } from './localSqliteQuerierPool.js';
2
+ import { AbstractLocalSqliteQuerierPool, adaptSqlite, extendSqlite, } from './localSqliteQuerierPool.js';
3
3
  import { SqliteDialect } from './sqliteDialect.js';
4
4
  /**
5
5
  * Pool for `better-sqlite3`, or `bun:sqlite` when running under Bun - the same file, through whichever
@@ -25,9 +25,9 @@ export class Sqlite3QuerierPool extends AbstractLocalSqliteQuerierPool {
25
25
  const bunDb = typeof this.filename === 'string'
26
26
  ? new Database(this.filename, bunOpts)
27
27
  : Database.deserialize(this.filename, bunOpts);
28
- return loadExtensions(adaptSqlite(bunDb, (stmt) => stmt.columnNames.length > 0), extensions);
28
+ return extendSqlite(adaptSqlite(bunDb, (stmt) => stmt.columnNames.length > 0), extensions);
29
29
  }
30
30
  const { default: BetterSqlite3 } = await import('better-sqlite3');
31
- return loadExtensions(new BetterSqlite3(this.filename, driverOpts).defaultSafeIntegers(true), extensions);
31
+ return extendSqlite(new BetterSqlite3(this.filename, driverOpts).defaultSafeIntegers(true), extensions);
32
32
  }
33
33
  }
@@ -98,8 +98,6 @@ export interface DialectFeatures {
98
98
  * the migration builder refuses the change by name.
99
99
  */
100
100
  readonly rebuildsTables: boolean;
101
- /** Where a comment goes: in the declaration (MySQL family), a `COMMENT ON` of its own (Postgres family), or nowhere. */
102
- readonly commentSyntax: 'inline' | 'statement' | 'none';
103
101
  /**
104
102
  * Whether every column of a vector index has to be `NOT NULL`, which MariaDB 12.3 enforces ("All
105
103
  * parts of a VECTOR index must be NOT NULL") and CockroachDB 26.3 does not - so being indexed, not
@@ -1,9 +1,8 @@
1
1
  import type { AnyMigrationOperation } from '../migrate/builder/types.js';
2
- import type { IndexFacet } from '../schema/indexDifferences.js';
3
2
  import type { SchemaAST } from '../schema/schemaAST.js';
4
3
  import type { DiffOptions } from '../schema/schemaASTDiffer.js';
5
- import type { ColumnNode, ForeignKeyAction, IndexType, TableNode } from '../schema/types.js';
6
- import type { EntityMeta, EntityWhereMeta, Except, FieldOptions, IndexColumnSchema, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, Type, VectorIndexOptions } from './index.js';
4
+ import type { CheckSchema, ColumnNode, ForeignKeyAction, IndexType, TableNode, TriggerSchema } from '../schema/types.js';
5
+ import type { Except, IndexColumnSchema, IndexedVectorField, LoggingOptions, Querier, SqlQuerier, Type, VectorIndexOptions } from './index.js';
7
6
  /**
8
7
  * Defines a migration using a simple object literal. `Q` is `MongoQuerier` for a MongoDB migration.
9
8
  */
@@ -98,7 +97,7 @@ export interface MigrationResult {
98
97
  readonly error?: Error;
99
98
  }
100
99
  /** A column as a statement renders one: a {@link ColumnNode} with the engine's type spelling and no graph links. */
101
- export interface ColumnSchema extends Except<ColumnNode, 'type' | 'table' | 'referencedBy' | 'references'> {
100
+ export interface ColumnSchema extends Except<ColumnNode, 'type' | 'table'> {
102
101
  /**
103
102
  * The engine's own type spelling, `TINYINT(1)`, compared as stored: canonical types would differ where
104
103
  * the engine stores them alike. `sqlToCanonical` reads it.
@@ -118,6 +117,9 @@ export interface TableSchema {
118
117
  readonly primaryKey?: PrimaryKeySchema;
119
118
  readonly indexes?: IndexSchema[];
120
119
  readonly foreignKeys?: ForeignKeySchema[];
120
+ readonly checks?: CheckSchema[];
121
+ /** The triggers uql installed, each with the statements the engine would recreate it from. */
122
+ readonly triggers?: TriggerSchema[];
121
123
  /** The statements the engine keeps for the table, where it keeps them: SQLite's `sqlite_master`. */
122
124
  readonly definition?: readonly StoredDefinition[];
123
125
  }
@@ -159,8 +161,7 @@ export interface IndexSchema extends VectorIndexOptions, IndexedVectorField {
159
161
  }
160
162
  /**
161
163
  * A foreign key constraint, wherever one is described: read back by introspection, planned into a
162
- * {@link SchemaDiff}, or declared through the migration builder. One shape for all three - they
163
- * differed only in spelling, and the translation between them was pure overhead.
164
+ * {@link SchemaDiff}, or declared through the migration builder: one shape for all three.
164
165
  */
165
166
  export interface ForeignKeySchema {
166
167
  /** Absent when nothing named it, which the generator fills in with `derivedForeignKeyName`. */
@@ -215,16 +216,17 @@ export interface PrimaryKeySchema {
215
216
  export interface SchemaDiff {
216
217
  /** Qualified where the table has a schema, since it is also the key the table is found under. */
217
218
  readonly tableName: string;
218
- /**
219
- * The schema {@link tableName} is in, carried separately for the identifiers that live in it
220
- * rather than name it: a Postgres index is dropped as `schema.index`, never `schema.table`.
221
- */
222
- readonly schema?: string;
223
219
  readonly type: 'create' | 'alter' | 'drop';
224
220
  readonly primaryKey?: Change<PrimaryKeySchema>;
225
221
  readonly columns?: readonly ColumnChange[];
226
222
  readonly indexes?: readonly Change<IndexSchema>[];
227
223
  readonly foreignKeys?: readonly Change<ForeignKeySchema>[];
224
+ readonly checks?: readonly Change<CheckSchema>[];
225
+ /**
226
+ * The triggers installed or declared, a kept one as both sides under one name: Postgres refuses to alter
227
+ * a column a trigger names, so a table whose columns change takes every trigger off and puts it back.
228
+ */
229
+ readonly triggers?: readonly Change<TriggerSchema>[];
228
230
  /** Columns renamed in place, `from` the database's name `to` the entity's, which the other changes already use. */
229
231
  readonly renamedColumns?: readonly Rename[];
230
232
  /**
@@ -260,14 +262,10 @@ export interface DropSchemaOptions {
260
262
  /** The schema as it stands, whose foreign keys are dropped before any table, since a cycle of them has no drop order. */
261
263
  readonly existing?: SchemaAST;
262
264
  }
263
- /** The triggers uql installed on one table, by name, each with the statements that recreate it as it stands. */
264
- export type InstalledTriggers = ReadonlyMap<string, readonly string[]>;
265
265
  /**
266
266
  * Interface for generating DDL statements from entity metadata
267
267
  */
268
268
  export interface SchemaGenerator {
269
- /** Whether a column's stored default is the one the entity declares, as the engine reprints it. Absent where columns are not compared. */
270
- readonly defaultsEqual?: (expected: unknown, actual: unknown) => boolean;
271
269
  /** The whole schema for `entities`, tables then the foreign keys between them, which need every entity at once. */
272
270
  generateCreateSchema(entities: readonly Type<object>[], options?: CreateSchemaOptions): string[];
273
271
  /**
@@ -276,42 +274,13 @@ export interface SchemaGenerator {
276
274
  * rejected once the foreign keys are really there.
277
275
  */
278
276
  generateDropSchema(entities: readonly Type<object>[], options?: DropSchemaOptions): string[];
279
- /** Generate DROP TABLE statement. */
280
- generateDropTable(tableName: string, options?: DropSchemaOptions): string;
281
- /**
282
- * What takes the triggers on `entity`'s table from `installed` - each by name, with the statements that
283
- * recreate it - to what it declares: nothing where the two agree, which is always on MongoDB.
284
- */
285
- generateTriggers(entity: Type<object>, installed?: InstalledTriggers): string[];
286
- /** The inverse of {@link generateTriggers} from the same `installed`: its triggers dropped, and the ones it dropped restored. */
287
- generateTriggersDown(entity: Type<object>, installed?: InstalledTriggers): string[];
288
- /** A `DROP` for each trigger uql owns among `names` on `entity`'s table, whatever the entity declares. */
289
- generateTriggerDrops(entity: Type<object>, names: readonly string[]): string[];
290
277
  /** The statements taking a table through `diff`; its rollback is the diff reversed, see `reverseDiff`. */
291
278
  generateAlterTable(diff: SchemaDiff): string[];
292
- /**
293
- * Generate CREATE INDEX statement
294
- */
295
- generateCreateIndex(tableName: string, index: IndexSchema): string;
296
- /**
297
- * Generate DROP INDEX statement
298
- */
299
- generateDropIndex(tableName: string, indexName: string): string;
300
279
  /**
301
280
  * The statements one migration builder operation runs as, one string each. An operation the engine
302
281
  * has no form for throws: MongoDB has no columns, constraints or SQL.
303
282
  */
304
283
  generateOperation(operation: AnyMigrationOperation): string[];
305
- /**
306
- * The text of SQL an entity declares - a check, a stored computed column, an index expression or
307
- * predicate - rendered for this engine, which is what building an entity's schema needs from it.
308
- */
309
- compileDdl(sql: EntityWhereMeta<object>, entity: Type<object>): string;
310
- /**
311
- * A partial index's `$where` as this engine writes it into {@link IndexSchema.where}, refused where its
312
- * index takes less of a predicate than a query does: SQL Server's filter has no `OR`.
313
- */
314
- compileIndexPredicate(where: EntityWhereMeta<object>, entity: Type<object>, indexName: string): string;
315
284
  /**
316
285
  * An entity's differences from its table. `desiredAst`, from {@link buildAST}, has to span every entity
317
286
  * a foreign key here points at, or those keys read as matching.
@@ -322,40 +291,11 @@ export interface SchemaGenerator {
322
291
  buildAST?(entities: readonly Type<object>[]): SchemaAST;
323
292
  /** How this engine's diff compares types and defaults. Absent where {@link buildAST} is. */
324
293
  diffOptions?(): DiffOptions;
325
- /**
326
- * The table's key: {@link resolveTableAlias} behind {@link resolveSchema}, which is how a
327
- * `SchemaAST` stores it and how a diff finds it again.
328
- */
329
- resolveTableName<E>(meta: EntityMeta<E>): string;
330
- /**
331
- * The table's own name, unqualified. What a derived index or constraint name is built from, since
332
- * those are single identifiers.
333
- */
334
- resolveTableAlias<E>(meta: EntityMeta<E>): string;
335
- /** The schema the table lives in, `undefined` where nothing named one. */
336
- resolveSchema<E>(meta: EntityMeta<E>): string | undefined;
337
- /**
338
- * Resolve column name using field options and naming strategy
339
- */
340
- resolveColumnName(key: string, field: FieldOptions): string;
341
294
  }
342
295
  /**
343
296
  * Interface for introspecting the current database schema
344
297
  */
345
298
  export interface SchemaIntrospector {
346
- /**
347
- * Every trigger uql installed on `table`, by name, each with the statements that recreate it as it
348
- * stands. The names say which to drop once an entity no longer declares them; the statements are what
349
- * a rollback puts back, read off the engine rather than recorded anywhere by uql. One table's alone,
350
- * so reading it never meets a trigger another writer is dropping from some other table.
351
- */
352
- ownedTriggers(table: string): Promise<InstalledTriggers>;
353
- /**
354
- * What this introspector can read back about an index, and so all that diffing may compare.
355
- * Comparing a feature it cannot read reports the same drift forever: the entity side declares it,
356
- * the database side never reports it, and no migration can close the gap.
357
- */
358
- readonly indexFacets: ReadonlySet<IndexFacet>;
359
299
  /**
360
300
  * The whole database, or just the tables named. Names nothing matches are left out. `renames` reads
361
301
  * each column under the name it is being renamed to, so a diff compares it as the column it becomes.
@@ -1,3 +1,4 @@
1
+ import type { CheckSchema, EnumValues } from '../schema/types.js';
1
2
  import { type EntityIndexColumn, type EntityIndexMeta, type EntityMeta, type IndexColumnInput, type IndexColumnSchema, QueryRaw } from '../type/index.js';
2
3
  /**
3
4
  * Reduces an authored index entry to the form metadata keeps, so a column, an expression and an options
@@ -14,5 +15,15 @@ export declare function declaredIndexes<E>(meta: EntityMeta<E>): EntityIndexMeta
14
15
  export declare function renderIndexColumn(entry: EntityIndexColumn, render: (sql: QueryRaw) => string): IndexColumnSchema;
15
16
  /** What an unnamed index's name is built from: each entry's column, or `expr<n>` for an expression, which has none. */
16
17
  export declare function indexNameParts(entries: readonly EntityIndexColumn[]): string[];
17
- /** The name an index is created and read by: its own, else one derived from its table and its entries' columns. */
18
- export declare function declaredIndexName(name: string | undefined, table: string, entries: readonly EntityIndexColumn[]): string;
18
+ /** The name an index is created and read by: its own, else one derived from its table, entries' columns and uniqueness. */
19
+ export declare function declaredIndexName(name: string | undefined, table: string, entries: readonly EntityIndexColumn[], unique?: boolean): string;
20
+ /**
21
+ * A check as uql installs it: named for its table and `label`, the author's name or `ck`, then a hash
22
+ * of `expression`, so an edited check is a new name and reordering the checks renames none.
23
+ */
24
+ export declare function ownedCheck(table: string, label: string | undefined, expression: string): CheckSchema;
25
+ /** The check a column's `enum` is, `column IN (...)`, each value the dialect's own literal; none without one. */
26
+ export declare function enumCheck(table: string, { name, enum: values }: {
27
+ readonly name: string;
28
+ readonly enum?: EnumValues;
29
+ }, render: (sql: QueryRaw) => string): CheckSchema[];
@@ -1,6 +1,7 @@
1
1
  import { ColumnRef, QueryRaw, } from '../type/index.js';
2
2
  import { definedEntries } from './object.util.js';
3
- import { derivedIndexName } from './sql.util.js';
3
+ import { raw } from './raw.js';
4
+ import { derivedIndexName, ownedName } from './sql.util.js';
4
5
  /**
5
6
  * Reduces an authored index entry to the form metadata keeps, so a column, an expression and an options
6
7
  * object reach the schema as one: a column read off the refs as its key, any other `raw` as it is.
@@ -35,7 +36,29 @@ export function renderIndexColumn(entry, render) {
35
36
  export function indexNameParts(entries) {
36
37
  return entries.map((entry, at) => (typeof entry.column === 'string' ? entry.column : `expr${at}`));
37
38
  }
38
- /** The name an index is created and read by: its own, else one derived from its table and its entries' columns. */
39
- export function declaredIndexName(name, table, entries) {
40
- return name ?? derivedIndexName(table, indexNameParts(entries));
39
+ /** The name an index is created and read by: its own, else one derived from its table, entries' columns and uniqueness. */
40
+ export function declaredIndexName(name, table, entries, unique = false) {
41
+ return name ?? derivedIndexName(table, indexNameParts(entries), unique);
42
+ }
43
+ /**
44
+ * A check as uql installs it: named for its table and `label`, the author's name or `ck`, then a hash
45
+ * of `expression`, so an edited check is a new name and reordering the checks renames none.
46
+ */
47
+ export function ownedCheck(table, label, expression) {
48
+ return { name: ownedName(table, label ?? 'ck', expression), expression };
49
+ }
50
+ /** The check a column's `enum` is, `column IN (...)`, each value the dialect's own literal; none without one. */
51
+ export function enumCheck(table, { name, enum: values }, render) {
52
+ if (!values) {
53
+ return [];
54
+ }
55
+ const sql = raw(({ ctx, dialect }) => {
56
+ ctx.append(`${dialect.escapeId(name)} IN (`);
57
+ values.forEach((value, i) => {
58
+ ctx.append(i ? ', ' : '');
59
+ ctx.addValue(value);
60
+ });
61
+ ctx.append(')');
62
+ });
63
+ return [ownedCheck(table, name, render(sql))];
41
64
  }
@@ -17,18 +17,10 @@ export declare function splitQualifiedName(qualified: string): {
17
17
  readonly name: string;
18
18
  readonly schema?: string;
19
19
  };
20
- /**
21
- * The name of a derived index or constraint, such as `Order__total_idx`, with the kind last as Postgres names
22
- * its own. It leaves out the table's schema, since it is a single identifier. The AST, the DDL and a `DROP`
23
- * all use this one rule.
24
- */
25
- export declare function derivedConstraintName(table: string, parts: readonly (string | number)[], kind: ConstraintKind): string;
26
- /** The kinds of derived name, which is also what `indexNameStem` strips to compare them. */
27
- export type ConstraintKind = 'pk' | 'fk' | 'idx' | 'ck' | 'uk';
28
20
  /**
29
21
  * Whether uql installed the object called `name`. Ownership is the prefix and nothing else, since no
30
- * engine records who created one - so this is the only thing standing between a hand-written trigger and
31
- * a `DROP`, and it is asked on both sides: when reading the catalogue, and again before emitting.
22
+ * engine records who created one - so this is the only thing standing between a hand-written trigger or
23
+ * check and a `DROP`, and it is asked on both sides: when reading the catalogue, and again before emitting.
32
24
  */
33
25
  export declare function isOwnedName(name: string): boolean;
34
26
  /**
@@ -49,8 +41,6 @@ export declare function derivedIndexName(table: string, columns: readonly string
49
41
  * same, so an existing constraint keeps whatever the engine called it - see `SchemaDiff.primaryKey`.
50
42
  */
51
43
  export declare function derivedPrimaryKeyName(table: string, columns: readonly string[]): string;
52
- /** The constraint name a check gets when nothing named it: `Order__1_ck`, by declaration order. */
53
- export declare function derivedCheckName(table: string, position: number): string;
54
44
  /** The constraint name a foreign key gets when nothing named it: `Order__customerId_fk`. */
55
45
  export declare function derivedForeignKeyName(table: string, columns: readonly string[]): string;
56
46
  /** Escapes an identifier with `escapeIdChar`, refusing a dotted one where `forbidQualified`, with a trailing dot where `addDot`. */
@@ -1,8 +1,6 @@
1
1
  import { OWNED_PREFIX, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
2
2
  import { hasKeys, isRecord } from './object.util.js';
3
3
  import { fnv1a } from './string.util.js';
4
- /** Pre-computed regex for each SQL identifier escape character to avoid per-call allocation. */
5
- const escapeIdRegexCache = { '`': /`/g, '"': /"/g };
6
4
  /** A row with its dotted columns nested, by paths read once off its statement's first row: the row itself where none is. */
7
5
  export function unflatObject(row, attrsPaths) {
8
6
  if (!hasKeys(attrsPaths)) {
@@ -62,7 +60,7 @@ const NAME_HASH_LENGTH = 6;
62
60
  * its own. It leaves out the table's schema, since it is a single identifier. The AST, the DDL and a `DROP`
63
61
  * all use this one rule.
64
62
  */
65
- export function derivedConstraintName(table, parts, kind) {
63
+ function derivedConstraintName(table, parts, kind) {
66
64
  const { name } = splitQualifiedName(table);
67
65
  const body = parts.length ? `${name}${TABLE_SEPARATOR}${parts.join('_')}` : name;
68
66
  return clampIdentifier(`${body}_${kind}`);
@@ -73,8 +71,8 @@ const TABLE_SEPARATOR = '__';
73
71
  const OWNED_START = `${OWNED_PREFIX}_`;
74
72
  /**
75
73
  * Whether uql installed the object called `name`. Ownership is the prefix and nothing else, since no
76
- * engine records who created one - so this is the only thing standing between a hand-written trigger and
77
- * a `DROP`, and it is asked on both sides: when reading the catalogue, and again before emitting.
74
+ * engine records who created one - so this is the only thing standing between a hand-written trigger or
75
+ * check and a `DROP`, and it is asked on both sides: when reading the catalogue, and again before emitting.
78
76
  */
79
77
  export function isOwnedName(name) {
80
78
  return name.startsWith(OWNED_START);
@@ -117,10 +115,6 @@ export function derivedIndexName(table, columns, unique = false) {
117
115
  export function derivedPrimaryKeyName(table, columns) {
118
116
  return derivedConstraintName(table, columns, 'pk');
119
117
  }
120
- /** The constraint name a check gets when nothing named it: `Order__1_ck`, by declaration order. */
121
- export function derivedCheckName(table, position) {
122
- return derivedConstraintName(table, [position], 'ck');
123
- }
124
118
  /** The constraint name a foreign key gets when nothing named it: `Order__customerId_fk`. */
125
119
  export function derivedForeignKeyName(table, columns) {
126
120
  return derivedConstraintName(table, columns, 'fk');
@@ -130,16 +124,13 @@ export function escapeSqlId(val, escapeIdChar = '`', forbidQualified, addDot) {
130
124
  if (!val) {
131
125
  return '';
132
126
  }
133
- if (!forbidQualified && val.includes('.')) {
134
- const result = val
127
+ const escaped = !forbidQualified && val.includes('.')
128
+ ? val
135
129
  .split('.')
136
- .map((it) => escapeSqlId(it, escapeIdChar, true))
137
- .join('.');
138
- return addDot ? result + '.' : result;
139
- }
140
- const escaped = escapeIdChar + val.replace(escapeIdRegexCache[escapeIdChar], escapeIdChar + escapeIdChar) + escapeIdChar;
141
- const suffix = addDot ? '.' : '';
142
- return escaped + suffix;
130
+ .map((part) => escapeSqlId(part, escapeIdChar, true))
131
+ .join('.')
132
+ : `${escapeIdChar}${val.replaceAll(escapeIdChar, escapeIdChar + escapeIdChar)}${escapeIdChar}`;
133
+ return addDot ? `${escaped}.` : escaped;
143
134
  }
144
135
  /**
145
136
  * A driver's result as a {@link QueryUpdateResult}: `RETURNING` rows name their id `id`; a MySQL header's
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Deno, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.96.1",
6
+ "version": "0.98.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=24"
@@ -143,7 +143,7 @@ A `findManyStream` holds its querier until the loop ends, which refuses any othe
143
143
  - `drift:check` fails when the database no longer matches.
144
144
  - `sync --dry-run` prints only SQL on stdout, to append to a migration file another tool applies: on Cloudflare D1, wrangler's (https://uql-orm.dev/cloudflare-d1.md).
145
145
 
146
- Triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
146
+ Checks, an enum's included, and triggers are part of the diff: uql owns the `_uql_`-prefixed ones and never touches another.
147
147
 
148
148
  ## Where to read more
149
149
 
@@ -1,36 +0,0 @@
1
- import type { AbstractSqlDialect } from '../../dialect/index.js';
2
- import type { IndexFacet } from '../../schema/indexDifferences.js';
3
- import { SchemaAST } from '../../schema/schemaAST.js';
4
- import type { ColumnRenames, TableSchema } from '../../type/migration.js';
5
- /**
6
- * Base class for SQL introspectors with shared AST building logic.
7
- */
8
- export declare abstract class BaseSqlIntrospector {
9
- protected readonly dialect: AbstractSqlDialect;
10
- readonly schema?: string | undefined;
11
- /** Columns and uniqueness only; each introspector opts in to what its catalogue queries report. */
12
- readonly indexFacets: ReadonlySet<IndexFacet>;
13
- /**
14
- * The one schema these queries read, `undefined` for the connection's own default. Every table
15
- * reported is stamped with it, so a diff compares like with like: entity and database both say
16
- * `undefined` for "wherever the connection points", and name a schema only when one was asked for.
17
- */
18
- constructor(dialect: AbstractSqlDialect, schema?: string | undefined);
19
- /**
20
- * The database as a {@link SchemaAST}, or just the tables named. A name nothing matches is left out
21
- * rather than raised: the point of naming them is to read a database other things are still
22
- * changing, where scanning every table is both wasted work and a relation that can vanish mid-scan.
23
- */
24
- introspect(tables?: readonly string[], renames?: ColumnRenames): Promise<SchemaAST>;
25
- /** `table` with each column `renames` names under its new name, wherever the table names it. */
26
- private renamed;
27
- abstract getTableNames(): Promise<string[]>;
28
- abstract getTableSchema(tableName: string): Promise<TableSchema | undefined>;
29
- /**
30
- * Build SchemaAST from table schemas.
31
- */
32
- protected buildAST(tableSchemas: TableSchema[]): SchemaAST;
33
- private buildTable;
34
- private buildRelationships;
35
- private buildIndexes;
36
- }