uql-orm 0.89.0 → 0.91.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 (43) hide show
  1. package/README.md +6 -6
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +3 -3
  4. package/dist/entity/decorator/members.d.ts +3 -3
  5. package/dist/entity/decorator/members.js +1 -1
  6. package/dist/migrate/acquireQuerierForMigrations.d.ts +3 -3
  7. package/dist/migrate/acquireQuerierForMigrations.js +3 -6
  8. package/dist/migrate/codegen/entityCodeGenerator.d.ts +15 -4
  9. package/dist/migrate/codegen/entityCodeGenerator.js +84 -47
  10. package/dist/migrate/codegen/entityTypes.js +37 -6
  11. package/dist/migrate/codegen/fieldOptionsSource.d.ts +4 -2
  12. package/dist/migrate/codegen/fieldOptionsSource.js +20 -8
  13. package/dist/migrate/codegen/migrationFile.d.ts +4 -0
  14. package/dist/migrate/codegen/migrationFile.js +4 -2
  15. package/dist/migrate/index.d.ts +1 -2
  16. package/dist/migrate/index.js +0 -2
  17. package/dist/migrate/introspection/index.d.ts +0 -1
  18. package/dist/migrate/introspection/index.js +0 -1
  19. package/dist/migrate/introspection/registry.js +1 -1
  20. package/dist/migrate/migrationTarget.js +6 -5
  21. package/dist/mongo/index.d.ts +4 -1
  22. package/dist/mongo/index.js +4 -1
  23. package/dist/{migrate/generator → mongo}/mongoCommand.js +1 -1
  24. package/dist/{migrate/introspection → mongo}/mongoIntrospector.d.ts +3 -3
  25. package/dist/{migrate/introspection → mongo}/mongoIntrospector.js +4 -4
  26. package/dist/{migrate/storage/mongoStorage.d.ts → mongo/mongoMigrationStorage.d.ts} +2 -1
  27. package/dist/{migrate/storage/mongoStorage.js → mongo/mongoMigrationStorage.js} +2 -2
  28. package/dist/mongo/mongoQuerier.d.ts +18 -0
  29. package/dist/mongo/mongoQuerier.js +13 -0
  30. package/dist/{migrate/generator → mongo}/mongoSchemaGenerator.d.ts +4 -4
  31. package/dist/{migrate/generator → mongo}/mongoSchemaGenerator.js +14 -14
  32. package/dist/mongo/mongodbQuerier.d.ts +2 -1
  33. package/dist/type/entity.d.ts +42 -11
  34. package/dist/type/migratorDialect.d.ts +8 -3
  35. package/dist/type/querier.d.ts +0 -15
  36. package/dist/type/querier.js +0 -7
  37. package/dist/type/queryRaw.d.ts +5 -3
  38. package/dist/type/queryRaw.js +2 -0
  39. package/dist/type/utility.d.ts +9 -3
  40. package/dist/util/dialect.util.d.ts +2 -10
  41. package/package.json +6 -6
  42. package/skills/uql-orm/SKILL.md +4 -3
  43. /package/dist/{migrate/generator → mongo}/mongoCommand.d.ts +0 -0
@@ -14,12 +14,15 @@ export function entityTypesSource(entities) {
14
14
  const names = interfaceNames(metas);
15
15
  const interfaces = metas.map((meta) => {
16
16
  const members = [
17
- ...Object.entries(meta.fields).map(([key, field]) => member(key, fieldType(field))),
18
- ...Object.entries(meta.relations).map(([key, rel]) => member(key, relationType(rel, names))),
17
+ ...Object.entries(meta.fields).map(([key, field]) => fieldMember(key, field)),
18
+ ...Object.entries(meta.relations).map(([key, rel]) => ` ${propertyName(key)}?: ${relationType(rel, names)};`),
19
19
  ];
20
20
  return `export interface ${names.get(meta.entity)} {\n${members.join('\n')}\n}`;
21
21
  });
22
- return ['// Generated by `uql-migrate types`. Do not edit.', '', ...interfaces, ''].join('\n');
22
+ const imports = metas.some((meta) => Object.values(meta.fields).some((field) => field && isFilledField(field)))
23
+ ? ["import type { Filled } from 'uql-orm';", '']
24
+ : [];
25
+ return ['// Generated by `uql-migrate types`. Do not edit.', '', ...imports, ...interfaces, ''].join('\n');
23
26
  }
24
27
  /**
25
28
  * One interface name per entity, settled before anything is written so a relation and its target
@@ -45,9 +48,37 @@ function identifier(text) {
45
48
  return isIdentifierName(stripped) ? stripped : `Entity${stripped}`;
46
49
  }
47
50
  /** A column name a property cannot hold - `hero-image` - is quoted rather than dropped. */
48
- function member(key, type) {
49
- const name = isIdentifierName(key) ? key : JSON.stringify(key);
50
- return ` ${name}?: ${type};`;
51
+ function propertyName(key) {
52
+ return isIdentifierName(key) ? key : JSON.stringify(key);
53
+ }
54
+ /**
55
+ * A field as an entity class declares it: required where every read has it and an insert names it, a
56
+ * key included, which an insert leaves out anyway; `Filled` where a default fills it; optional where a
57
+ * read skips it (`eager: false`); `| null` where the column holds NULL; `readonly` where it is computed.
58
+ */
59
+ function fieldMember(key, field) {
60
+ const type = fieldType(field);
61
+ const name = propertyName(key);
62
+ if (!field) {
63
+ return ` ${name}?: ${type};`;
64
+ }
65
+ if (isFilledField(field)) {
66
+ return ` ${name}: Filled<${type}>;`;
67
+ }
68
+ const written = field.computed === undefined ? '' : 'readonly ';
69
+ if (!field.isId && field.nullable !== false) {
70
+ return ` ${written}${name}?: ${type} | null;`;
71
+ }
72
+ const optional = !field.isId && field.eager === false;
73
+ return ` ${written}${name}${optional ? '?' : ''}: ${type};`;
74
+ }
75
+ /** A non-null field a default or `onInsert` fills, which every read has and an insert may leave out. */
76
+ function isFilledField(field) {
77
+ return (!field.isId &&
78
+ field.nullable === false &&
79
+ field.eager !== false &&
80
+ field.computed === undefined &&
81
+ (field.defaultValue !== undefined || field.onInsert !== undefined));
51
82
  }
52
83
  /**
53
84
  * The property type a column reads back as, resolved the way the DDL resolves it - so a foreign key
@@ -1,5 +1,7 @@
1
- import type { ColumnNode } from '../../schema/types.js';
2
- /** A column's `@Field({ ... })` options as source, `''` where it needs none: shared by the generator and the merger. */
1
+ import type { ColumnNode, EnumValues } from '../../schema/types.js';
2
+ /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
3
3
  export declare function buildFieldOptionsSource(col: ColumnNode, propertyName: string, indexName?: string): string;
4
+ /** An enum's members as source literals, which are also the property's type as a union. */
5
+ export declare function enumMembersSource(members: EnumValues): string[];
4
6
  /** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
5
7
  export declare function fieldNeedsRaw(col: ColumnNode): boolean;
@@ -1,34 +1,42 @@
1
- import { canonicalToColumnType } from '../../schema/canonicalType.js';
1
+ import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalType.js';
2
+ import { isAutoIncrement } from '../../util/field.util.js';
2
3
  import { quoted, rawTag } from './sourceLiteral.js';
3
4
  /** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
4
5
  const OPTION_SOURCE = {
5
6
  // Without this the entity maps to a column named after the property, which for anything the
6
7
  // transformer rewrote - every `user_id` - is a column the database does not have.
7
8
  name: (col, { propertyName }) => (propertyName === col.name ? [] : [`name: ${quoted(col.name)}`]),
9
+ // The column type as `type`, which the decorator checks the property against and the schema reads
10
+ // exactly as it reads `columnType`.
8
11
  type: (col) => {
9
12
  const columnType = canonicalToColumnType(col.type);
10
13
  return [
11
- `columnType: ${quoted(columnType)}`,
14
+ `type: ${quoted(columnType)}`,
12
15
  ...(col.type.length && col.type.category === 'string' ? [`length: ${col.type.length}`] : []),
16
+ ...(col.type.length && isVectorCategory(col.type.category) ? [`dimensions: ${col.type.length}`] : []),
13
17
  ...(col.type.precision === undefined ? [] : [`precision: ${col.type.precision}`]),
14
18
  ...(col.type.precision !== undefined && col.type.scale !== undefined ? [`scale: ${col.type.scale}`] : []),
15
19
  ];
16
20
  },
17
- nullable: (col) => (col.nullable ? ['nullable: true'] : []),
21
+ // A column is nullable unless it says otherwise, and a key is NOT NULL without saying so.
22
+ nullable: (col) => (col.nullable || col.isPrimaryKey ? [] : ['nullable: false']),
18
23
  isUnique: (col) => (col.isUnique ? ['unique: true'] : []),
19
- enum: (col) => col.enum ? [`enum: [${col.enum.map((it) => (typeof it === 'number' ? it : quoted(it))).join(', ')}]`] : [],
24
+ enum: (col) => (col.enum ? [`enum: [${enumMembersSource(col.enum).join(', ')}] as const`] : []),
20
25
  defaultValue: (col) => col.defaultValue === undefined ? [] : [`defaultValue: ${defaultValueSource(col.defaultValue)}`],
21
26
  generatedAs: (col) => (col.generatedAs ? [`computed: ${rawTag(col.generatedAs)}`, 'stored: true'] : []),
22
27
  comment: (col) => (col.comment ? [`comment: ${quoted(col.comment)}`] : []),
23
- // A key is `@Id`, and a numeric one generates by that alone. Neither is an option to write out.
28
+ // A key is `@Id`, which says it on its own, and generates where `isAutoIncrement` says, which only a
29
+ // column the database treats otherwise contradicts.
24
30
  isPrimaryKey: null,
25
- isAutoIncrement: null,
31
+ isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, col.isPrimaryKey && col.table.primaryKey?.columns.length === 1) === col.isAutoIncrement
32
+ ? []
33
+ : [`autoIncrement: ${col.isAutoIncrement}`],
26
34
  // Graph links. A foreign key becomes a relation decorator, emitted beside the field rather than in it.
27
35
  table: null,
28
36
  references: null,
29
37
  referencedBy: null,
30
38
  };
31
- /** A column's `@Field({ ... })` options as source, `''` where it needs none: shared by the generator and the merger. */
39
+ /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
32
40
  export function buildFieldOptionsSource(col, propertyName, indexName) {
33
41
  const context = { propertyName, indexName };
34
42
  const options = [
@@ -36,7 +44,11 @@ export function buildFieldOptionsSource(col, propertyName, indexName) {
36
44
  // Not a column field: the index is a table-level object the field only borrows.
37
45
  ...(indexName ? [`index: ${quoted(indexName)}`] : []),
38
46
  ];
39
- return options.length > 0 ? `{ ${options.join(', ')} }` : '';
47
+ return `{ ${options.join(', ')} }`;
48
+ }
49
+ /** An enum's members as source literals, which are also the property's type as a union. */
50
+ export function enumMembersSource(members) {
51
+ return members.map((it) => (typeof it === 'number' ? String(it) : quoted(it)));
40
52
  }
41
53
  /** Whether the field's decorator needs `raw` imported, the way {@link indexNeedsRaw} does for an index. */
42
54
  export function fieldNeedsRaw(col) {
@@ -31,6 +31,8 @@ export declare const EMPTY_MANUAL_MIGRATION_DOWN_INNER = " // Add your rollba
31
31
  /** How a migration on one querier is scaffolded empty, and how a generated statement is spelled in it. */
32
32
  export type MigrationSource = {
33
33
  readonly querier: MigrationQuerierType;
34
+ /** The entry exporting that querier's type: a MongoDB one names the driver's `Db`, so only `uql-orm/mongo` has it. */
35
+ readonly module: string;
34
36
  readonly emptyUp: string;
35
37
  readonly emptyDown: string;
36
38
  emit(statements: string[]): string;
@@ -38,12 +40,14 @@ export type MigrationSource = {
38
40
  export declare const migrationSource: {
39
41
  SqlQuerier: {
40
42
  querier: "SqlQuerier";
43
+ module: string;
41
44
  emptyUp: string;
42
45
  emptyDown: string;
43
46
  emit: typeof emitSqlRunCalls;
44
47
  };
45
48
  MongoQuerier: {
46
49
  querier: "MongoQuerier";
50
+ module: string;
47
51
  emptyUp: string;
48
52
  emptyDown: string;
49
53
  emit: typeof emitMongoCommandCalls;
@@ -1,4 +1,4 @@
1
- import { mongoCommandSource } from '../generator/mongoCommand.js';
1
+ import { mongoCommandSource } from '../../mongo/mongoCommand.js';
2
2
  /**
3
3
  * Emit one `await querier.run(...)` line for entity-generated migrations.
4
4
  * Uses `JSON.stringify` so SQL with backticks (SQLite/LibSQL), quotes, `${`, etc. stays valid TS source.
@@ -27,12 +27,14 @@ export const EMPTY_MANUAL_MIGRATION_DOWN_INNER = ` // Add your rollback logic
27
27
  export const migrationSource = {
28
28
  SqlQuerier: {
29
29
  querier: 'SqlQuerier',
30
+ module: 'uql-orm/migrate',
30
31
  emptyUp: EMPTY_MANUAL_MIGRATION_UP_INNER,
31
32
  emptyDown: EMPTY_MANUAL_MIGRATION_DOWN_INNER,
32
33
  emit: emitSqlRunCalls,
33
34
  },
34
35
  MongoQuerier: {
35
36
  querier: 'MongoQuerier',
37
+ module: 'uql-orm/mongo',
36
38
  emptyUp: ` // Add your migration logic here, through the database handle.
37
39
  // await querier.db.collection('users').updateMany({}, { $set: { active: true } });
38
40
  `,
@@ -49,7 +51,7 @@ export function buildMigrationModule(options) {
49
51
  const querier = options.querier ?? 'SqlQuerier';
50
52
  const iso = options.createdAt.toISOString();
51
53
  const extra = options.docExtraLines?.map((line) => `\n * ${line}`).join('') ?? '';
52
- return /*ts*/ `import type { ${querier} } from 'uql-orm/migrate';
54
+ return /*ts*/ `import type { ${querier} } from '${migrationSource[querier].module}';
53
55
 
54
56
  /**
55
57
  * Migration: ${options.migrationName}
@@ -1,4 +1,4 @@
1
- export type { Change, ColumnSchema, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigrationStorage, MigratorOptions, MongoQuerier, PrimaryKeySchema, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
1
+ export type { Change, ColumnSchema, DialectName, ForeignKeySchema, IndexSchema, Migration, MigrationDefinition, MigrationResult, MigrationStorage, MigratorOptions, PrimaryKeySchema, SchemaDiff, SchemaGenerator, SchemaIntrospector, SqlDialectName, SqlQuerier, SqlQueryDialect, SyncOptions, TableSchema, } from '../type/index.js';
2
2
  export { type Config, isSqlQuerier } from '../type/index.js';
3
3
  export { acquireQuerierForMigrations } from './acquireQuerierForMigrations.js';
4
4
  export { assertCliConfig } from './assertCliConfig.js';
@@ -14,4 +14,3 @@ export { reverseDiff } from './schemaChange.js';
14
14
  export { SqlSchemaGenerator } from './schemaGenerator.js';
15
15
  export { DatabaseMigrationStorage } from './storage/databaseStorage.js';
16
16
  export { JsonMigrationStorage } from './storage/jsonStorage.js';
17
- export { MongoMigrationStorage } from './storage/mongoStorage.js';
@@ -21,5 +21,3 @@ export { SqlSchemaGenerator } from './schemaGenerator.js';
21
21
  // Storage implementations
22
22
  export { DatabaseMigrationStorage } from './storage/databaseStorage.js';
23
23
  export { JsonMigrationStorage } from './storage/jsonStorage.js';
24
- export { MongoMigrationStorage } from './storage/mongoStorage.js';
25
- // Schema sync
@@ -1,5 +1,4 @@
1
1
  export * from './abstractSqlSchemaIntrospector.js';
2
- export * from './mongoIntrospector.js';
3
2
  export * from './mssqlIntrospector.js';
4
3
  export { MariadbSchemaIntrospector, MysqlSchemaIntrospector } from './mysqlIntrospector.js';
5
4
  export * from './postgresIntrospector.js';
@@ -1,5 +1,4 @@
1
1
  export * from './abstractSqlSchemaIntrospector.js';
2
- export * from './mongoIntrospector.js';
3
2
  export * from './mssqlIntrospector.js';
4
3
  export { MariadbSchemaIntrospector, MysqlSchemaIntrospector } from './mysqlIntrospector.js';
5
4
  export * from './postgresIntrospector.js';
@@ -1,4 +1,4 @@
1
- import { MongoSchemaIntrospector } from './mongoIntrospector.js';
1
+ import { MongoSchemaIntrospector } from '../../mongo/mongoIntrospector.js';
2
2
  import { MsSqlSchemaIntrospector } from './mssqlIntrospector.js';
3
3
  import { MariadbSchemaIntrospector, MysqlSchemaIntrospector } from './mysqlIntrospector.js';
4
4
  import { CockroachSchemaIntrospector, PostgresSchemaIntrospector } from './postgresIntrospector.js';
@@ -1,12 +1,13 @@
1
- import { isMongoQuerier, isSqlQuerier, } from '../type/index.js';
1
+ import { runMongoCommand } from '../mongo/mongoCommand.js';
2
+ import { MongoMigrationStorage } from '../mongo/mongoMigrationStorage.js';
3
+ import { isMongoQuerier, withMongoQuerierForMigrations } from '../mongo/mongoQuerier.js';
4
+ import { isSqlQuerier, } from '../type/index.js';
2
5
  import { UqlUsageError } from '../util/uqlError.js';
3
- import { withMongoQuerierForMigrations, withSqlQuerierForMigrations } from './acquireQuerierForMigrations.js';
6
+ import { withSqlQuerierForMigrations } from './acquireQuerierForMigrations.js';
4
7
  import { MigrationBuilder } from './builder/migrationBuilder.js';
5
8
  import { migrationSource } from './codegen/migrationFile.js';
6
- import { runMongoCommand } from './generator/mongoCommand.js';
7
9
  import { SqlSchemaGenerator } from './schemaGenerator.js';
8
10
  import { DatabaseMigrationStorage } from './storage/databaseStorage.js';
9
- import { MongoMigrationStorage } from './storage/mongoStorage.js';
10
11
  const sqlSession = (querier) => ({
11
12
  querier,
12
13
  run: (statement) => querier.run(statement),
@@ -45,7 +46,7 @@ const mongoSession = (querier) => ({
45
46
  });
46
47
  /** Imported on use, so the optional `mongodb` peer loads only on MongoDB. */
47
48
  async function mongoSchemaGenerator(namingStrategy, defaultForeignKeyAction) {
48
- const { MongoSchemaGenerator } = await import('./generator/mongoSchemaGenerator.js');
49
+ const { MongoSchemaGenerator } = await import('../mongo/mongoSchemaGenerator.js');
49
50
  return new MongoSchemaGenerator(namingStrategy, defaultForeignKeyAction);
50
51
  }
51
52
  export function migrationTargetFor(pool, defaultForeignKeyAction) {
@@ -1,5 +1,8 @@
1
- export { MongoSchemaGenerator } from '../migrate/generator/mongoSchemaGenerator.js';
2
1
  export * from './mongoDialect.js';
3
2
  export * from './mongodbQuerier.js';
4
3
  export * from './mongodbQuerierPool.js';
4
+ export * from './mongoIntrospector.js';
5
+ export * from './mongoMigrationStorage.js';
6
+ export { isMongoQuerier, type MongoQuerier } from './mongoQuerier.js';
7
+ export * from './mongoSchemaGenerator.js';
5
8
  export * from './textLanguage.js';
@@ -1,5 +1,8 @@
1
- export { MongoSchemaGenerator } from '../migrate/generator/mongoSchemaGenerator.js';
2
1
  export * from './mongoDialect.js';
3
2
  export * from './mongodbQuerier.js';
4
3
  export * from './mongodbQuerierPool.js';
4
+ export * from './mongoIntrospector.js';
5
+ export * from './mongoMigrationStorage.js';
6
+ export { isMongoQuerier } from './mongoQuerier.js';
7
+ export * from './mongoSchemaGenerator.js';
5
8
  export * from './textLanguage.js';
@@ -1,4 +1,4 @@
1
- import { UqlUsageError } from '../../util/uqlError.js';
1
+ import { UqlUsageError } from '../util/uqlError.js';
2
2
  export function serializeMongoCommand(command) {
3
3
  return JSON.stringify(command);
4
4
  }
@@ -1,6 +1,6 @@
1
- import type { IndexFacet } from '../../schema/indexDifferences.js';
2
- import { SchemaAST } from '../../schema/schemaAST.js';
3
- import { type InstalledTriggers, type QuerierPool, type SchemaIntrospector, type TableSchema } from '../../type/index.js';
1
+ import type { IndexFacet } from '../schema/indexDifferences.js';
2
+ import { SchemaAST } from '../schema/schemaAST.js';
3
+ import type { InstalledTriggers, QuerierPool, SchemaIntrospector, TableSchema } from '../type/index.js';
4
4
  /**
5
5
  * MongoDB schema introspector.
6
6
  * MongoDB doesn't have a fixed schema, so this primarily focuses on collections and indexes.
@@ -1,7 +1,7 @@
1
- import { textConfigOf } from '../../mongo/textLanguage.js';
2
- import { createTableNode, SchemaAST } from '../../schema/schemaAST.js';
3
- import { isMongoQuerier, } from '../../type/index.js';
4
- import { UqlUsageError } from '../../util/uqlError.js';
1
+ import { createTableNode, SchemaAST } from '../schema/schemaAST.js';
2
+ import { UqlUsageError } from '../util/uqlError.js';
3
+ import { isMongoQuerier } from './mongoQuerier.js';
4
+ import { textConfigOf } from './textLanguage.js';
5
5
  /** What a server without Atlas Search answers a search index command with. */
6
6
  const SEARCH_NOT_ENABLED = 31082;
7
7
  /**
@@ -1,4 +1,5 @@
1
- import type { MigrationStorage, MongoQuerier, QuerierPool } from '../../type/index.js';
1
+ import type { MigrationStorage, QuerierPool } from '../type/index.js';
2
+ import { type MongoQuerier } from './mongoQuerier.js';
2
3
  /**
3
4
  * Stores migration state in a MongoDB collection, named as the SQL table would be.
4
5
  */
@@ -1,5 +1,5 @@
1
- import { withMongoQuerierForMigrations } from '../acquireQuerierForMigrations.js';
2
- import { DEFAULT_MIGRATIONS_TABLE } from './databaseStorage.js';
1
+ import { DEFAULT_MIGRATIONS_TABLE } from '../migrate/storage/databaseStorage.js';
2
+ import { withMongoQuerierForMigrations } from './mongoQuerier.js';
3
3
  /**
4
4
  * Stores migration state in a MongoDB collection, named as the SQL table would be.
5
5
  */
@@ -0,0 +1,18 @@
1
+ import type { Db } from 'mongodb';
2
+ import { type Querier, type QuerierPool } from '../type/index.js';
3
+ /**
4
+ * Extended querier interface for MongoDB execution.
5
+ */
6
+ export interface MongoQuerier extends Querier {
7
+ /**
8
+ * The MongoDB database instance.
9
+ */
10
+ readonly db: Db;
11
+ }
12
+ /**
13
+ * Type guard for a querier over a MongoDB database. A handle alone does not tell: the SQLite, D1 and
14
+ * Turso queriers carry a `db` of their own.
15
+ */
16
+ export declare function isMongoQuerier(querier: Querier): querier is MongoQuerier;
17
+ /** Runs `task` on a migration querier over MongoDB. `requiredBy` names the caller in the error. */
18
+ export declare function withMongoQuerierForMigrations<T>(pool: QuerierPool, requiredBy: string, task: (querier: MongoQuerier) => Promise<T>): Promise<T>;
@@ -0,0 +1,13 @@
1
+ import { withQuerierOfKind } from '../migrate/acquireQuerierForMigrations.js';
2
+ import { isSqlQuerier } from '../type/index.js';
3
+ /**
4
+ * Type guard for a querier over a MongoDB database. A handle alone does not tell: the SQLite, D1 and
5
+ * Turso queriers carry a `db` of their own.
6
+ */
7
+ export function isMongoQuerier(querier) {
8
+ return 'db' in querier && !isSqlQuerier(querier);
9
+ }
10
+ /** Runs `task` on a migration querier over MongoDB. `requiredBy` names the caller in the error. */
11
+ export function withMongoQuerierForMigrations(pool, requiredBy, task) {
12
+ return withQuerierOfKind(pool, isMongoQuerier, `${requiredBy} requires a MongoDB querier`, task);
13
+ }
@@ -1,7 +1,7 @@
1
- import { MongoDialect } from '../../mongo/mongoDialect.js';
2
- import type { ForeignKeyAction, TableNode } from '../../schema/types.js';
3
- import { type CreateSchemaOptions, type EntityWhereMeta, type IndexSchema, type NamingStrategy, type SchemaDiff, type SchemaGenerator, type Type } from '../../type/index.js';
4
- import type { AnyMigrationOperation } from '../builder/types.js';
1
+ import type { AnyMigrationOperation } from '../migrate/builder/types.js';
2
+ import type { ForeignKeyAction, TableNode } from '../schema/types.js';
3
+ import { type CreateSchemaOptions, type EntityWhereMeta, type IndexSchema, type NamingStrategy, type SchemaDiff, type SchemaGenerator, type Type } from '../type/index.js';
4
+ import { MongoDialect } from './mongoDialect.js';
5
5
  export declare class MongoSchemaGenerator extends MongoDialect implements SchemaGenerator {
6
6
  protected readonly defaultForeignKeyAction?: ForeignKeyAction | undefined;
7
7
  constructor(namingStrategy?: NamingStrategy, defaultForeignKeyAction?: ForeignKeyAction | undefined);
@@ -1,18 +1,18 @@
1
- import { getMeta } from '../../entity/index.js';
2
- import { MongoDialect } from '../../mongo/mongoDialect.js';
3
- import { textLanguage } from '../../mongo/textLanguage.js';
4
- import { indexChanges } from '../../schema/indexDifferences.js';
5
- import { QueryRaw, } from '../../type/index.js';
6
- import { indexDistance, unsupportedVectorMetric } from '../../type/vector.js';
7
- import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../../util/ddlExpression.util.js';
8
- import { fulltextConfig, fulltextWeights } from '../../util/dialect.util.js';
9
- import { UqlUsageError } from '../../util/uqlError.js';
10
- import { assertIndexFeatures, assertIndexType } from '../ddl/indexDdl.js';
11
- import { assertIndexPredicate, refusedIndexPredicate } from '../indexPredicate.js';
12
- import { sides } from '../schemaChange.js';
13
- import { renderIndexDefinition } from './definitionToNode.js';
14
- import { indexNodeToSchema } from './indexNodeToSchema.js';
1
+ import { getMeta } from '../entity/index.js';
2
+ import { assertIndexFeatures, assertIndexType } from '../migrate/ddl/indexDdl.js';
3
+ import { renderIndexDefinition } from '../migrate/generator/definitionToNode.js';
4
+ import { indexNodeToSchema } from '../migrate/generator/indexNodeToSchema.js';
5
+ import { assertIndexPredicate, refusedIndexPredicate } from '../migrate/indexPredicate.js';
6
+ import { sides } from '../migrate/schemaChange.js';
7
+ import { indexChanges } from '../schema/indexDifferences.js';
8
+ import { QueryRaw, } from '../type/index.js';
9
+ import { indexDistance, unsupportedVectorMetric } from '../type/vector.js';
10
+ import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../util/ddlExpression.util.js';
11
+ import { fulltextConfig, fulltextWeights } from '../util/dialect.util.js';
12
+ import { UqlUsageError } from '../util/uqlError.js';
15
13
  import { serializeMongoCommand } from './mongoCommand.js';
14
+ import { MongoDialect } from './mongoDialect.js';
15
+ import { textLanguage } from './textLanguage.js';
16
16
  /** The index types a key spec can say, a plain key or `'text'`, and Atlas's vector search index. */
17
17
  const MONGO_INDEX_TYPES = new Set(['btree', 'fulltext', 'vectorSearch']);
18
18
  /** A key spec's one feature beyond its keys: a partial filter. */
@@ -2,7 +2,8 @@ import type { Document, MongoClient } from 'mongodb';
2
2
  import { AbstractQuerier } from '../querier/index.js';
3
3
  import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
4
4
  import type { MongoDialect } from './mongoDialect.js';
5
- export declare class MongodbQuerier extends AbstractQuerier {
5
+ import type { MongoQuerier } from './mongoQuerier.js';
6
+ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
6
7
  readonly dialect: MongoDialect;
7
8
  readonly conn: MongoClient;
8
9
  readonly extra?: ExtraOptions | undefined;
@@ -3,7 +3,7 @@ import type { SqlDialectName } from './dialect.js';
3
3
  import type { FilterOptions, RelationQuery } from './query.js';
4
4
  import type { ColumnRef, QueryRaw, RawFor, RelationAggregate } from './queryRaw.js';
5
5
  import type { QueryWhere } from './queryWhere.js';
6
- import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
6
+ import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, IsMany, Json, Scalar, Type, Unpacked, Writable } from './utility.js';
7
7
  import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
8
8
  /** Brands the property an entity is identified by, where it is not `id`, `_id` or `uuid`. */
9
9
  export declare const idKey: unique symbol;
@@ -13,6 +13,16 @@ export declare const idKey: unique symbol;
13
13
  * must not start demanding one.
14
14
  */
15
15
  export declare const versionKey: unique symbol;
16
+ /**
17
+ * A non-null field uql or the database fills on insert, by `onInsert` or a default: every read has it,
18
+ * and an insert may leave it out. `createdAt!: Filled<Date>`.
19
+ */
20
+ export type Filled<T> = T & FilledBrand;
21
+ declare const filled: unique symbol;
22
+ /** The marker {@link Filled} adds: a symbol key, so no string key or autocomplete shows it. */
23
+ export interface FilledBrand {
24
+ readonly [filled]?: never;
25
+ }
16
26
  /** The filter `@Field({ softDelete })` registers, a name reserved against an entity's own filters. */
17
27
  export declare const SOFT_DELETE_FILTER = "softDelete";
18
28
  /** A filter name an entity may declare: any but {@link SOFT_DELETE_FILTER}, which a refusal names. */
@@ -35,8 +45,23 @@ export type FieldKey<E> = {
35
45
  export type WritableKey<E> = {
36
46
  readonly [K in FieldKey<E>]-?: IsEqual<Pick<E, K>, Writable<Pick<E, K>>> extends true ? K : never;
37
47
  }[FieldKey<E>];
38
- /** A whole-record write as a caller supplies one: {@link EntityData} without the fields it cannot write. */
39
- export type EntityWrite<E> = EntityData<E, WritableKey<E>>;
48
+ /**
49
+ * What an insert may leave out: a single-column key, which something usually generates, the version,
50
+ * which uql starts at 0, and a {@link Filled} field. A composite key is the references a row is made of,
51
+ * so an insert names it.
52
+ */
53
+ type FilledKey<E> = SoleIdKey<E> | VersionKey<E> | FilledFieldKey<E>;
54
+ type FilledFieldKey<E> = {
55
+ readonly [K in WritableKey<E>]-?: typeof filled extends keyof NonNullable<E[K]> ? K : never;
56
+ }[WritableKey<E>];
57
+ /**
58
+ * A whole-record write as a caller supplies one: {@link EntityData} without the fields it cannot write,
59
+ * a {@link FilledKey} optional. That part is a conditional, which TypeScript leaves shut while it types a
60
+ * call's payload against the generic write: as a mapped type, it doubled what checking an insert cost.
61
+ */
62
+ export type EntityWrite<E> = EntityData<E, Exclude<WritableKey<E>, FilledKey<E>>> & ([FilledKey<E>] extends [never] ? unknown : {
63
+ [P in WritableKey<E> & FilledKey<E>]?: E[P];
64
+ });
40
65
  /** A row a trigger's body writes: each writable field its value, or SQL - a row's ref most often. */
41
66
  export type WriteRow<E, F extends keyof E = WritableKey<E>> = {
42
67
  readonly [K in F]?: E[K] | RawFor<QueryRaw, E[K]>;
@@ -66,8 +91,6 @@ export type ToOneRelationKey<E> = {
66
91
  }[RelationKey<E>];
67
92
  /** The relation names a parent holds many rows of: what a populated query fills, and what an aggregate reads. */
68
93
  export type ToManyRelationKey<E> = Exclude<RelationKey<E>, ToOneRelationKey<E>>;
69
- /** Whether `T` carries the `Json` brand, read off its marker key: a primitive matches `Json<infer P>` too. */
70
- type IsJson<T> = '__json' extends keyof T ? true : false;
71
94
  /** The payload `P` of a branded `Json<P>`, or `never` for any other type. */
72
95
  type UnwrapJson<T> = IsJson<T> extends true ? (T extends Json<infer P> ? P : never) : never;
73
96
  /** What a JSON column declared as `V` holds, `Json<P>` or `Json<P>[]` alike; `never` on any other column. */
@@ -140,15 +163,16 @@ type FieldUpdateOpFor<V> = [NonNullable<V>] extends [number] ? FieldUpdateOp<num
140
163
  type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V>;
141
164
  /**
142
165
  * What a whole-record write persists: the fields and relations with their declared optionality, a
143
- * related row's alike, and no methods. Two mapped types, since asking each key costs a conditional.
166
+ * related row as a caller writes one, and no methods. Two mapped types, since asking each key costs a
167
+ * conditional.
144
168
  */
145
169
  export type EntityData<E, F extends keyof E = FieldKey<E>, R extends keyof E = RelationKey<E>> = {
146
170
  [P in F]: E[P];
147
171
  } & {
148
172
  [P in R]: E[P] | RelationData<E[P]>;
149
173
  };
150
- /** A relation's value as its rows' {@link EntityData}. */
151
- type RelationData<V> = V extends readonly (infer T)[] ? EntityData<T>[] : V extends object ? EntityData<V> : never;
174
+ /** A relation's value as its rows' {@link EntityWrite}. */
175
+ type RelationData<V> = V extends readonly (infer T)[] ? EntityWrite<T>[] : V extends object ? EntityWrite<V> : never;
152
176
  /** {@link EntityData} made partial, each member also taking its {@link UpdateExtra}. */
153
177
  export type UpdatePayload<E, Raw = QueryRaw, F extends keyof E = FieldKey<E>, R extends keyof E = RelationKey<E>> = {
154
178
  [P in F]?: E[P] | UpdateExtra<E[P], Raw>;
@@ -171,6 +195,11 @@ export type IdKey<E> = ([NamedIdKey<E>] extends [never] ? FieldKey<E> : NamedIdK
171
195
  export type IdValue<E> = E[IdKey<E>];
172
196
  /** Whether `E`'s primary key spans several columns, which no single column can reference. */
173
197
  export type HasCompositeKey<E> = true extends IsUnion<IdKey<E>> ? true : false;
198
+ /**
199
+ * The key an entity names where it is one column, as `soleIdOf` reads it at run time; `never` for a
200
+ * composite and for no named key, which {@link HasCompositeKey} tells apart where a reference needs it.
201
+ */
202
+ type SoleIdKey<E> = true extends IsUnion<NamedIdKey<E>> ? never : NamedIdKey<E>;
174
203
  /** Every column of a key, which is how a composite row is named and what a `$where` reduces to. */
175
204
  type IdMap<E> = Partial<Pick<E, IdKey<E>>>;
176
205
  /**
@@ -184,7 +213,7 @@ type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) :
184
213
  * The id a write reports: the value for a single key, the map for a composite. {@link EntityId} where
185
214
  * the entity names no key, since a composite cannot then be told from a single one.
186
215
  */
187
- export type WrittenId<E> = [NamedIdKey<E>] extends [never] ? EntityId<E> : IsUnion<IdKey<E>> extends true ? IdMap<E> : IdValue<E>;
216
+ export type WrittenId<E> = [NamedIdKey<E>] extends [never] ? EntityId<E> : [SoleIdKey<E>] extends [never] ? IdMap<E> : IdValue<E>;
188
217
  /** Every SQL column type a field may declare, by family: the unions below and `columnFamily` both read it. */
189
218
  export declare const COLUMN_TYPES: {
190
219
  readonly numeric: readonly ['int', 'integer', 'tinyint', 'smallint', 'bigint', 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'numeric', 'real'];
@@ -201,6 +230,8 @@ type ColumnTypeOf<F extends ColumnFamily> = (typeof COLUMN_TYPES)[F][number];
201
230
  export type NumericColumnType = ColumnTypeOf<'numeric'>;
202
231
  export type StringColumnType = ColumnTypeOf<'string'>;
203
232
  export type DateColumnType = ColumnTypeOf<'date'>;
233
+ /** A date column holding a time of day, which names no day: every driver reads it back as text, never a `Date`. */
234
+ type TimeColumnType = 'time';
204
235
  export type JsonColumnType = ColumnTypeOf<'json'>;
205
236
  export type BlobColumnType = ColumnTypeOf<'blob'>;
206
237
  export type BooleanColumnType = ColumnTypeOf<'boolean'>;
@@ -219,7 +250,7 @@ export type FieldType = StringConstructor | NumberConstructor | BooleanConstruct
219
250
  * compile. JSON is matched on its brand, which a `Json<string>` shares with `string`, and arrays before
220
251
  * scalars, so a vector is not read as a `number`.
221
252
  */
222
- export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType : T extends number ? NumberConstructor | NumericColumnType : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | DateColumnType : T extends Uint8Array ? BlobColumnType : FieldType;
253
+ export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType | TimeColumnType : T extends number ? NumberConstructor | NumericColumnType : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | Exclude<DateColumnType, TimeColumnType> : T extends Uint8Array ? BlobColumnType : FieldType;
223
254
  /** A field as the registry holds it: what was authored, plus what registration worked out, which no decorator can write. */
224
255
  export type FieldMeta<V = TsTypeOf<FieldType>> = Except<FieldOptions<V>, 'computed'> & {
225
256
  /** {@link FieldOptions.computed}, a callback resolved to the SQL it returns. */
@@ -318,7 +349,7 @@ type JsonDdlDefault = Scalar | Record<string, unknown>;
318
349
  * The TypeScript type a declared `type` implies, the inverse of {@link TypeFor}: a decorator checks the
319
350
  * property against it, `defineEntity` the other way round. `entityOptions.test-d.ts` keeps them agreeing.
320
351
  */
321
- export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? Json<unknown> | readonly Json<unknown>[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
352
+ export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType | TimeColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? Json<unknown> | readonly Json<unknown>[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
322
353
  /**
323
354
  * {@link FieldOptions} for a field declared as `V`, `type` checked by {@link TypeFor}. A foreign key may
324
355
  * omit it, taking the referenced key's column type instead.
@@ -1,4 +1,9 @@
1
+ import type { AbstractDialect } from '../dialect/abstractDialect.js';
1
2
  import type { AbstractSqlDialect } from '../dialect/abstractSqlDialect.js';
2
- import type { MongoDialect } from '../mongo/mongoDialect.js';
3
- /** The dialects the migrator runs on, which `dialectName` tells apart: every SQL engine, and MongoDB. */
4
- export type MigratorDialect = AbstractSqlDialect | MongoDialect;
3
+ /**
4
+ * The dialects the migrator runs on, which `dialectName` tells apart: every SQL engine, and MongoDB, named
5
+ * by its `dialectName` alone so these types reach no `mongodb` declaration.
6
+ */
7
+ export type MigratorDialect = AbstractSqlDialect | (AbstractDialect & {
8
+ readonly dialectName: 'mongodb';
9
+ });
@@ -1,4 +1,3 @@
1
- import type { Db } from 'mongodb';
2
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
3
2
  import type { SqlDialectName } from './dialect.js';
4
3
  import type { FieldKey, HookEvent, RelationKey } from './entity.js';
@@ -116,20 +115,6 @@ export interface SqlQuerier extends Querier {
116
115
  * Type guard to check if a querier supports raw SQL execution
117
116
  */
118
117
  export declare function isSqlQuerier(querier: Querier): querier is SqlQuerier;
119
- /**
120
- * Extended querier interface for MongoDB execution.
121
- */
122
- export interface MongoQuerier extends Querier {
123
- /**
124
- * The MongoDB database instance.
125
- */
126
- readonly db: Db;
127
- }
128
- /**
129
- * Type guard for a querier over a MongoDB database. A handle alone does not tell: the SQLite, D1 and
130
- * Turso queriers carry a `db` of their own.
131
- */
132
- export declare function isMongoQuerier(querier: Querier): querier is MongoQuerier;
133
118
  /**
134
119
  * Context passed to global querier listeners.
135
120
  */
@@ -8,10 +8,3 @@ export function isSqlQuerier(querier) {
8
8
  q.dialect !== undefined &&
9
9
  typeof q.dialect.escapeIdChar === 'string');
10
10
  }
11
- /**
12
- * Type guard for a querier over a MongoDB database. A handle alone does not tell: the SQLite, D1 and
13
- * Turso queriers carry a `db` of their own.
14
- */
15
- export function isMongoQuerier(querier) {
16
- return 'db' in querier && !isSqlQuerier(querier);
17
- }