uql-orm 0.104.1 → 0.105.1

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 (161) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/querier/httpQuerier.d.ts +3 -3
  3. package/dist/browser/type/clientQuerier.d.ts +1 -1
  4. package/dist/browser/uql-browser.min.js +2 -2
  5. package/dist/browser/uql-browser.min.js.map +9 -9
  6. package/dist/cockroachdb/cockroachDialect.d.ts +2 -2
  7. package/dist/dialect/abstractDialect.d.ts +3 -3
  8. package/dist/dialect/abstractSqlDialect.d.ts +39 -37
  9. package/dist/dialect/abstractSqlDialect.js +35 -32
  10. package/dist/dialect/aliases.d.ts +2 -0
  11. package/dist/dialect/aliases.js +2 -0
  12. package/dist/dialect/jsonSql.js +2 -2
  13. package/dist/dialect/mergeSqlDialect.d.ts +2 -2
  14. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -7
  15. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  16. package/dist/dialect/operators.js +2 -4
  17. package/dist/dialect/queryJoins.d.ts +4 -2
  18. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  19. package/dist/dialect/vectorSqlDialect.js +1 -1
  20. package/dist/entity/column.d.ts +3 -0
  21. package/dist/entity/column.js +3 -0
  22. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  23. package/dist/entity/columnOptionsBuilder.js +108 -0
  24. package/dist/entity/decorator/bag.d.ts +5 -5
  25. package/dist/entity/decorator/entity.d.ts +3 -20
  26. package/dist/entity/decorator/entity.js +3 -37
  27. package/dist/entity/decorator/members.d.ts +46 -76
  28. package/dist/entity/decorator/members.js +18 -7
  29. package/dist/entity/index.d.ts +2 -1
  30. package/dist/entity/index.js +2 -1
  31. package/dist/entity/metadata/definition.d.ts +15 -26
  32. package/dist/entity/metadata/definition.js +344 -148
  33. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  34. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  35. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  36. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  37. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  38. package/dist/entity/metadata/schemaFixture/book.js +23 -0
  39. package/dist/http/contract.d.ts +2 -2
  40. package/dist/http/handler.d.ts +2 -2
  41. package/dist/http/query.js +12 -13
  42. package/dist/index.d.ts +2 -2
  43. package/dist/index.js +2 -1
  44. package/dist/mariadb/mariaDialect.d.ts +2 -2
  45. package/dist/mariadb/mariaDialect.js +1 -1
  46. package/dist/mariadb/mariadbQuerier.js +1 -3
  47. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  48. package/dist/migrate/builder/columnBuilder.js +104 -110
  49. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  50. package/dist/migrate/builder/migrationBuilder.js +7 -6
  51. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  52. package/dist/migrate/builder/tableBuilder.js +88 -204
  53. package/dist/migrate/builder/types.d.ts +52 -151
  54. package/dist/migrate/builder/types.js +0 -6
  55. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  56. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  57. package/dist/migrate/codegen/entityTypes.d.ts +2 -2
  58. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  59. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  60. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  61. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  62. package/dist/migrate/ddl/defaultSql.js +7 -6
  63. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  64. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  65. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  66. package/dist/migrate/ddl/indexDdl.js +33 -30
  67. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  68. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  69. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  70. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  71. package/dist/migrate/drift/driftDetector.js +2 -2
  72. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  73. package/dist/migrate/generator/definitionToNode.js +4 -5
  74. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  75. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  76. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  77. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  78. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  79. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  80. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  81. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  82. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  83. package/dist/migrate/migrator.d.ts +2 -2
  84. package/dist/migrate/schemaChange.d.ts +3 -3
  85. package/dist/migrate/schemaChange.js +3 -2
  86. package/dist/migrate/schemaGenerator.d.ts +5 -5
  87. package/dist/migrate/schemaGenerator.js +1 -1
  88. package/dist/migrate/storage/databaseStorage.js +4 -4
  89. package/dist/mongodb/mongoDialect.d.ts +41 -44
  90. package/dist/mongodb/mongoDialect.js +118 -32
  91. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  92. package/dist/mongodb/mongoIntrospector.js +11 -5
  93. package/dist/mongodb/mongoSchemaGenerator.d.ts +4 -4
  94. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  95. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  96. package/dist/mongodb/mongodbQuerier.js +9 -43
  97. package/dist/mssql/mssqlDialect.d.ts +4 -4
  98. package/dist/postgres/postgresDialect.d.ts +2 -2
  99. package/dist/querier/abstractQuerier.d.ts +0 -1
  100. package/dist/querier/abstractQuerier.js +1 -20
  101. package/dist/querier/abstractSqlQuerier.d.ts +1 -1
  102. package/dist/querier/keyset.js +3 -3
  103. package/dist/schema/declaredColumn.d.ts +11 -0
  104. package/dist/schema/declaredColumn.js +21 -0
  105. package/dist/schema/indexColumns.d.ts +0 -3
  106. package/dist/schema/indexColumns.js +11 -7
  107. package/dist/schema/indexDifferences.d.ts +10 -5
  108. package/dist/schema/indexDifferences.js +42 -28
  109. package/dist/schema/schemaASTBuilder.d.ts +4 -4
  110. package/dist/schema/schemaASTBuilder.js +28 -36
  111. package/dist/schema/schemaASTDiffer.js +8 -4
  112. package/dist/schema/sqlExpression.d.ts +21 -17
  113. package/dist/schema/sqlExpression.js +11 -23
  114. package/dist/type/column.d.ts +328 -0
  115. package/dist/type/column.js +2 -0
  116. package/dist/type/config.d.ts +3 -3
  117. package/dist/type/dialect.d.ts +15 -14
  118. package/dist/type/dialect.js +1 -0
  119. package/dist/type/entity.d.ts +292 -281
  120. package/dist/type/entity.js +6 -1
  121. package/dist/type/index.d.ts +2 -0
  122. package/dist/type/index.js +2 -0
  123. package/dist/type/migration.d.ts +11 -11
  124. package/dist/type/querier.d.ts +2 -2
  125. package/dist/type/query.d.ts +44 -40
  126. package/dist/type/query.js +2 -3
  127. package/dist/type/queryAggregate.d.ts +22 -12
  128. package/dist/type/querySql.d.ts +22 -6
  129. package/dist/type/querySql.js +27 -9
  130. package/dist/type/schemaEntity.d.ts +194 -0
  131. package/dist/type/schemaEntity.js +1 -0
  132. package/dist/type/utility.d.ts +4 -7
  133. package/dist/type/vector.d.ts +1 -1
  134. package/dist/util/ddlExpression.util.d.ts +12 -13
  135. package/dist/util/ddlExpression.util.js +12 -21
  136. package/dist/util/dialect.util.d.ts +11 -5
  137. package/dist/util/dialect.util.js +31 -37
  138. package/dist/util/field.util.d.ts +10 -9
  139. package/dist/util/field.util.js +14 -10
  140. package/dist/util/fieldOption.util.d.ts +11 -95
  141. package/dist/util/fieldOption.util.js +49 -16
  142. package/dist/util/hook.util.d.ts +3 -15
  143. package/dist/util/hook.util.js +3 -16
  144. package/dist/util/index.d.ts +1 -0
  145. package/dist/util/index.js +1 -0
  146. package/dist/util/indexEntry.util.d.ts +45 -0
  147. package/dist/util/indexEntry.util.js +138 -0
  148. package/dist/util/relationQuery.util.d.ts +0 -1
  149. package/dist/util/relationQuery.util.js +0 -5
  150. package/dist/util/sql.d.ts +13 -10
  151. package/dist/util/sql.js +34 -16
  152. package/dist/util/sql.util.d.ts +4 -5
  153. package/dist/util/sql.util.js +7 -16
  154. package/dist/util/string.util.d.ts +2 -0
  155. package/dist/util/string.util.js +4 -0
  156. package/dist/util/triggerWrite.d.ts +5 -5
  157. package/dist/util/uqlError.d.ts +1 -1
  158. package/dist/util/uqlError.js +1 -1
  159. package/package.json +1 -1
  160. package/skills/uql-orm/SKILL.md +76 -25
  161. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -1,8 +1,8 @@
1
1
  import { canonicalToTypeScript } from '../../schema/canonicalType.js';
2
2
  import { DEFAULT_FOREIGN_KEY_ACTION, } from '../../schema/types.js';
3
3
  import { camelCase, lowerFirst, pascalCase, singularize, upperFirst } from '../../util/string.util.js';
4
- import { buildFieldOptionsSource, fieldImports } from './fieldOptionsSource.js';
5
- import { buildIndexDecoratorSource, indexNeedsRaw, isPlainFieldIndex } from './indexDecoratorSource.js';
4
+ import { buildFieldOptionsSource, fieldDecoratorSource, fieldImports } from './fieldOptionsSource.js';
5
+ import { buildIndexEntrySource, indexNeedsRaw, isPlainFieldIndex } from './indexEntrySource.js';
6
6
  import { memberSource, quoted } from './sourceLiteral.js';
7
7
  /** The decorator on the other side of a relation. */
8
8
  const INVERSE_RELATION = {
@@ -43,11 +43,11 @@ export class EntityCodeGenerator {
43
43
  const className = this.options.classNameTransformer(table.name);
44
44
  const fileName = `${className}.ts`;
45
45
  const imports = this.buildImports(table);
46
- const decorators = this.buildEntityDecorators(table);
46
+ const decorator = this.buildEntityDecorator(table);
47
47
  const brand = this.idKeyBrand(table);
48
48
  const fields = brand ? `${brand}\n\n${this.buildFields(table)}` : this.buildFields(table);
49
49
  const relations = this.options.includeRelations ? this.buildRelations(table) : '';
50
- const code = [imports, '', decorators, `export class ${className} {`, fields, relations, '}', ''].join('\n');
50
+ const code = [imports, '', decorator, `export class ${className} {`, fields, relations, '}', ''].join('\n');
51
51
  return {
52
52
  className,
53
53
  tableName: table.name,
@@ -56,15 +56,13 @@ export class EntityCodeGenerator {
56
56
  };
57
57
  }
58
58
  buildImports(table) {
59
- const uqlImports = new Set(['Entity', 'Field']);
59
+ const uqlImports = new Set(['Entity', 'f']);
60
60
  const relatedImports = [];
61
61
  if (this.idKeyBrand(table)) {
62
62
  uqlImports.add('idKey');
63
63
  }
64
64
  for (const col of table.columns.values()) {
65
- if (col.isPrimaryKey) {
66
- uqlImports.add('Id');
67
- }
65
+ uqlImports.add(col.generatedAs === undefined ? 'Field' : 'Computed');
68
66
  for (const name of fieldImports(col)) {
69
67
  uqlImports.add(name);
70
68
  }
@@ -89,11 +87,7 @@ export class EntityCodeGenerator {
89
87
  }
90
88
  }
91
89
  if (this.options.includeIndexes) {
92
- const declared = this.declaredIndexes(table);
93
- if (declared.length > 0) {
94
- uqlImports.add('Index');
95
- }
96
- if (declared.some(indexNeedsRaw)) {
90
+ if (this.declaredIndexes(table).some(indexNeedsRaw)) {
97
91
  uqlImports.add('sql');
98
92
  }
99
93
  }
@@ -102,16 +96,22 @@ export class EntityCodeGenerator {
102
96
  ...relatedImports.sort().map((className) => `import { ${className} } from './${className}.js';`),
103
97
  ].join('\n');
104
98
  }
105
- buildEntityDecorators(table) {
106
- const lines = [];
107
- if (this.options.includeIndexes) {
108
- const param = lowerFirst(this.options.classNameTransformer(table.name));
109
- for (const index of this.declaredIndexes(table)) {
110
- lines.push(buildIndexDecoratorSource(index, this.options.propertyNameTransformer, param));
111
- }
99
+ buildEntityDecorator(table) {
100
+ const param = lowerFirst(this.options.classNameTransformer(table.name));
101
+ const indexes = this.options.includeIndexes
102
+ ? this.declaredIndexes(table).map((index) => buildIndexEntrySource(index, this.options.propertyNameTransformer, param))
103
+ : [];
104
+ if (!indexes.length) {
105
+ return `@Entity({ name: '${table.name}' })`;
112
106
  }
113
- lines.push(`@Entity({ name: '${table.name}' })`);
114
- return lines.join('\n');
107
+ return [
108
+ `@Entity({`,
109
+ ` name: '${table.name}',`,
110
+ ` indexes: (${param}, index) => [`,
111
+ ...indexes.map((index) => ` ${index},`),
112
+ ` ],`,
113
+ `})`,
114
+ ].join('\n');
115
115
  }
116
116
  buildFields(table) {
117
117
  return [...table.columns.values()].map((col) => this.buildField(col)).join('\n\n');
@@ -140,7 +140,7 @@ export class EntityCodeGenerator {
140
140
  const propertyName = this.options.propertyNameTransformer(col.name);
141
141
  return [
142
142
  ...this.syncDoc(`Column: ${col.name} (${formatTypeDescription(col.type)})`),
143
- ` @${col.isPrimaryKey ? 'Id' : 'Field'}(${this.buildFieldOptions(col, propertyName)})`,
143
+ ` ${fieldDecoratorSource(this.buildFieldOptions(col, propertyName), col)}`,
144
144
  ` ${propertySource(col, propertyName)};`,
145
145
  ].join('\n');
146
146
  }
@@ -150,7 +150,7 @@ export class EntityCodeGenerator {
150
150
  return buildFieldOptionsSource(col, propertyName, fieldIndex?.name);
151
151
  }
152
152
  /**
153
- * The indexes this table needs an `@Index` for, which is every one a `@Field({ index })` cannot
153
+ * The indexes this table lists under `indexes`, which is every one a `.index()` cannot
154
154
  * carry on its own.
155
155
  */
156
156
  declaredIndexes(table) {
@@ -1,7 +1,7 @@
1
- import type { Type } from '../../type/index.js';
1
+ import type { AbstractType } from '../../type/index.js';
2
2
  /**
3
3
  * A `.d.ts` for the entities as registered, so a shape that only exists at runtime reaches the
4
4
  * compiler too. Interfaces, not the entity classes `generate:from-db` writes: those are the source of
5
5
  * a schema, these describe one already defined elsewhere.
6
6
  */
7
- export declare function entityTypesSource(entities: readonly Type<object>[]): string;
7
+ export declare function entityTypesSource(entities: readonly AbstractType<object>[]): string;
@@ -1,5 +1,7 @@
1
1
  import type { ColumnNode } from '../../schema/types.js';
2
- /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
2
+ /** A column's builder as source, `f.column('varchar').length(80).nullable()`, its plain index's name chained on. */
3
3
  export declare function buildFieldOptionsSource(col: ColumnNode, propertyName: string, indexName?: string): string;
4
+ /** The decorator declaring the column `builder` writes: `@Computed` for one the database generates. */
5
+ export declare function fieldDecoratorSource(builder: string, col: ColumnNode): string;
4
6
  /** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
5
7
  export declare function fieldImports(col: ColumnNode): string[];
@@ -3,35 +3,33 @@ import { SqlExpression } from '../../schema/sqlExpression.js';
3
3
  import { DATE_PRECISION } from '../../util/date.js';
4
4
  import { isAutoIncrement } from '../../util/field.util.js';
5
5
  import { quoted, sqlTag } from './sourceLiteral.js';
6
- /** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
7
- const OPTION_SOURCE = {
8
- // Without this the entity maps to a column named after the property, which for anything the
9
- // transformer rewrote - every `user_id` - is a column the database does not have.
10
- name: (col, propertyName) => (propertyName === col.name ? [] : [`name: ${quoted(col.name)}`]),
11
- // The column type as `type`, which the decorator checks the property against and the schema reads
12
- // exactly as it reads `columnType`.
13
- type: (col) => {
14
- const columnType = canonicalToColumnType(col.type);
15
- return [
16
- `type: ${quoted(columnType)}`,
17
- ...(col.type.length && col.type.category === 'string' ? [`length: ${col.type.length}`] : []),
18
- ...(col.type.length && isVectorCategory(col.type.category) ? [`dimensions: ${col.type.length}`] : []),
19
- ...(writesPrecision(col.type) ? [`precision: ${col.type.precision}`] : []),
20
- ...(col.type.precision !== undefined && col.type.scale !== undefined ? [`scale: ${col.type.scale}`] : []),
21
- ];
22
- },
23
- // A column is nullable unless it says otherwise, and a key is NOT NULL without saying so.
24
- nullable: (col) => (col.nullable || col.isPrimaryKey ? [] : ['nullable: false']),
25
- isUnique: (col) => (col.isUnique ? ['unique: true'] : []),
26
- defaultValue: (col) => col.defaultValue === undefined ? [] : [`defaultValue: ${defaultValueSource(col.defaultValue)}`],
27
- generatedAs: (col) => (col.generatedAs ? [`computed: ${sqlTag(col.generatedAs)}`, 'stored: true'] : []),
28
- comment: (col) => (col.comment ? [`comment: ${quoted(col.comment)}`] : []),
29
- // A key is `@Id`, which says it on its own, and generates where `isAutoIncrement` says, which only a
30
- // column the database treats otherwise contradicts.
31
- isPrimaryKey: null,
6
+ /**
7
+ * What each field of a {@link ColumnNode} chains onto its builder, in emit order; `satisfies` makes a new field
8
+ * answer. The builder itself is the column's type, `f.column('varchar')`.
9
+ */
10
+ const METHOD_SOURCE = {
11
+ // The type's bounds, which its family's builder takes.
12
+ type: (col) => [
13
+ ...(col.type.length && col.type.category === 'string' ? [`.length(${col.type.length})`] : []),
14
+ ...(col.type.length && isVectorCategory(col.type.category) ? [`.dimensions(${col.type.length})`] : []),
15
+ ...(writesPrecision(col.type) ? [`.precision(${col.type.precision})`] : []),
16
+ ...(col.type.precision !== undefined && col.type.scale !== undefined ? [`.scale(${col.type.scale})`] : []),
17
+ ],
18
+ // A column is NOT NULL unless it says otherwise; a key is a key, which holds no null.
19
+ nullable: (col) => (col.nullable && !col.isPrimaryKey ? ['.nullable()'] : []),
20
+ isPrimaryKey: (col) => (col.isPrimaryKey ? ['.id()'] : []),
21
+ // Generates where `isAutoIncrement` says, which only a column the database treats otherwise contradicts.
32
22
  isAutoIncrement: (col) => isAutoIncrement({ type: canonicalToColumnType(col.type) }, col.isPrimaryKey && col.table.primaryKey?.columns.length === 1) === col.isAutoIncrement
33
23
  ? []
34
- : [`autoIncrement: ${col.isAutoIncrement}`],
24
+ : [col.isAutoIncrement ? '.autoIncrement()' : '.autoIncrement(false)'],
25
+ isUnique: (col) => (col.isUnique ? ['.unique()'] : []),
26
+ defaultValue: (col) => (col.defaultValue === undefined ? [] : [`.default(${defaultValueSource(col.defaultValue)})`]),
27
+ // Without this the entity maps to a column named after the property, which for anything the
28
+ // transformer rewrote - every `user_id` - is a column the database does not have.
29
+ name: (col, propertyName) => (propertyName === col.name ? [] : [`.name(${quoted(col.name)})`]),
30
+ comment: (col) => (col.comment ? [`.comment(${quoted(col.comment)})`] : []),
31
+ // Emitted after the index: a generated column is the builder computed `as()` its SQL, and kept.
32
+ generatedAs: (col) => (col.generatedAs ? [`.as(${sqlTag(col.generatedAs)}).stored()`] : []),
35
33
  // The graph link: a foreign key becomes a relation decorator, emitted beside the field rather than in it.
36
34
  table: null,
37
35
  };
@@ -39,14 +37,17 @@ const OPTION_SOURCE = {
39
37
  function writesPrecision(type) {
40
38
  return type.precision !== undefined && !(type.category === 'timestamp' && type.precision === DATE_PRECISION);
41
39
  }
42
- /** A column's `@Id({ ... })` or `@Field({ ... })` options as source. */
40
+ /** A column's builder as source, `f.column('varchar').length(80).nullable()`, its plain index's name chained on. */
43
41
  export function buildFieldOptionsSource(col, propertyName, indexName) {
44
- const options = [
45
- ...Object.values(OPTION_SOURCE).flatMap((source) => source?.(col, propertyName) ?? []),
46
- // Not a column field: the index is a table-level object the field only borrows.
47
- ...(indexName ? [`index: ${quoted(indexName)}`] : []),
48
- ];
49
- return `{ ${options.join(', ')} }`;
42
+ const { generatedAs, ...methodSources } = METHOD_SOURCE;
43
+ const methods = Object.values(methodSources).flatMap((source) => source?.(col, propertyName) ?? []);
44
+ // Not a column field: the index is a table-level object the field only borrows.
45
+ const index = indexName ? [`.index(${quoted(indexName)})`] : [];
46
+ return `f.column(${quoted(canonicalToColumnType(col.type))})${[...methods, ...index, ...generatedAs(col)].join('')}`;
47
+ }
48
+ /** The decorator declaring the column `builder` writes: `@Computed` for one the database generates. */
49
+ export function fieldDecoratorSource(builder, col) {
50
+ return col.generatedAs ? `@Computed(() => ${builder})` : `@Field(${builder})`;
50
51
  }
51
52
  /** The uql imports the field's decorator needs besides `Field`, as {@link indexNeedsRaw} tells for an index. */
52
53
  export function fieldImports(col) {
@@ -0,0 +1,16 @@
1
+ import type { IndexNode } from '../../schema/types.js';
2
+ /**
3
+ * Whether `.index()` can carry the whole index. It says only "this column is indexed under
4
+ * this name", and `unique` beside it that the index is unique, so anything else the index declares - an
5
+ * expression, a predicate, an access method, stored columns, a stored order - has to be written out as
6
+ * an `indexes` entry instead.
7
+ */
8
+ export declare function isPlainFieldIndex(index: IndexNode): boolean;
9
+ /**
10
+ * One `@Entity` `indexes` entry as source, `index([user.email], { unique: true })`, for an index no column's
11
+ * `index()` can express, its columns read off the refs `param` names and a lone name written as the bare string.
12
+ * Emits `sql` for an expression entry, so callers import `sql` when {@link indexNeedsRaw} holds.
13
+ */
14
+ export declare function buildIndexEntrySource(index: IndexNode, propertyName: (column: string) => string, param: string): string;
15
+ /** Whether emitting this index needs `sql` imported. */
16
+ export declare function indexNeedsRaw(index: IndexNode): boolean;
@@ -1,28 +1,39 @@
1
1
  import { isVectorIndexType } from '../../type/index.js';
2
2
  import { fulltextConfig } from '../../util/dialect.util.js';
3
+ import { jsonPathKeys } from '../../util/field.util.js';
4
+ import { isElementsType } from '../../util/indexEntry.util.js';
3
5
  import { memberSource, quoted, sqlTag } from './sourceLiteral.js';
4
6
  /**
5
- * The options each field of an index entry writes into `@Index`, in emit order; `satisfies` forces every new
7
+ * The options each field of an index entry writes, in emit order; `satisfies` forces every new
6
8
  * field to be listed. Defaults are skipped: Postgres reports each entry in full (`order: 'asc', nulls: 'last'`
7
9
  * on a plain column), and writing that out would bake its defaults into every entity.
8
10
  */
9
11
  const ENTRY_MODIFIER_SOURCE = {
12
+ type: (entry) => (entry.type === undefined ? [] : [`type: ${valueTypeSource(entry.type)}`]),
10
13
  order: (entry) => (entry.order === 'desc' ? [`order: 'desc'`] : []),
11
14
  opsClass: (entry) => (entry.opsClass ? [`opsClass: ${quoted(entry.opsClass)}`] : []),
12
- length: (entry) => (entry.length === undefined ? [] : [`length: ${entry.length}`]),
15
+ prefixLength: (entry) => (entry.prefixLength === undefined ? [] : [`prefixLength: ${entry.prefixLength}`]),
16
+ charLength: (entry) => (entry.charLength === undefined ? [] : [`charLength: ${entry.charLength}`]),
13
17
  weight: (entry) => ((entry.weight ?? 1) === 1 ? [] : [`weight: ${entry.weight}`]),
14
18
  // Never written: only Postgres reports it, and on every entry.
15
19
  nulls: null,
16
- // Written by `indexEntrySource` as the entry itself, ahead of its modifiers.
20
+ // Written by `entryTargetSource` as the entry itself, ahead of its modifiers.
17
21
  column: null,
22
+ json: null,
23
+ path: null,
18
24
  expression: null,
19
- // Never written: introspection reads a JSON entry back as the expression the engine prints for it.
20
- jsonPath: null,
21
- jsonArray: null,
22
25
  };
23
- /** Each {@link IndexNode} field's `@Index` options, in emit order; `satisfies` forces a new field to be listed. */
26
+ /** A JSON path's value type as source: `Number`, `'decimal'`, or `[String]` for each element. */
27
+ function valueTypeSource(type) {
28
+ if (isElementsType(type)) {
29
+ return `[${valueTypeSource(type[0])}]`;
30
+ }
31
+ return typeof type === 'string' ? quoted(type) : type.name;
32
+ }
33
+ /** Each {@link IndexNode} field's index options, in emit order; `satisfies` forces a new field to be listed. */
24
34
  const INDEX_OPTION_SOURCE = {
25
- name: (index) => (index.name ? [`name: ${quoted(index.name)}`] : []),
35
+ // Written by `buildIndexEntrySource` ahead of the rest, as the bare string when it is alone.
36
+ name: null,
26
37
  unique: (index) => (index.unique ? ['unique: true'] : []),
27
38
  type: (index) => (writesType(index) ? [`type: '${index.type}'`] : []),
28
39
  distance: (index) => (isVectorIndexType(index.type) && index.distance ? [`distance: '${index.distance}'`] : []),
@@ -37,9 +48,9 @@ const INDEX_OPTION_SOURCE = {
37
48
  where: (index) => (index.where ? [`where: ${sqlTag(index.where)}`] : []),
38
49
  include: (index, { param, propertyName }) => {
39
50
  const included = index.include?.map((column) => memberSource(param, propertyName(column))) ?? [];
40
- return included.length ? [`include: (${param}) => [${included.join(', ')}]`] : [];
51
+ return included.length ? [`include: [${included.join(', ')}]`] : [];
41
52
  },
42
- // Written as the decorator's first argument, not as an option.
53
+ // Written as the entry's `columns`, not as an option.
43
54
  entries: null,
44
55
  // Taken from the indexed field, never declared on the index.
45
56
  vectorType: null,
@@ -49,7 +60,7 @@ const INDEX_OPTION_SOURCE = {
49
60
  };
50
61
  /**
51
62
  * Whether to write the index's type. `btree` is skipped: it is every engine's default and reported on every
52
- * index. So is a vector type whose distance introspection could not recover, since `@Index` requires a
63
+ * index. So is a vector type whose distance introspection could not recover, since an index entry requires a
53
64
  * `distance` beside a vector type and would not compile without one.
54
65
  */
55
66
  function writesType(index) {
@@ -57,44 +68,60 @@ function writesType(index) {
57
68
  index.type !== 'btree' &&
58
69
  (!isVectorIndexType(index.type) || index.distance !== undefined));
59
70
  }
60
- function entryModifiers(entry) {
71
+ function entryModifierSources(entry) {
61
72
  return Object.values(ENTRY_MODIFIER_SOURCE).flatMap((source) => source?.(entry) ?? []);
62
73
  }
63
74
  /**
64
- * Whether `@Field({ index })` can carry the whole index. It says only "this column is indexed under
75
+ * Whether `.index()` can carry the whole index. It says only "this column is indexed under
65
76
  * this name", and `unique` beside it that the index is unique, so anything else the index declares - an
66
77
  * expression, a predicate, an access method, stored columns, a stored order - has to be written out as
67
- * an `@Index` instead.
78
+ * an `indexes` entry instead.
68
79
  */
69
80
  export function isPlainFieldIndex(index) {
70
81
  const entries = index.entries;
71
82
  const [entry] = entries;
72
83
  return (entries.length === 1 &&
73
84
  entry !== undefined &&
74
- !entry.expression &&
85
+ entry.column !== undefined &&
75
86
  index.where === undefined &&
76
87
  // Postgres names an access method on every index, so the default one still counts as plain.
77
88
  (index.type === undefined || index.type === 'btree') &&
78
89
  !index.include?.length &&
79
- entryModifiers(entry).length === 0);
90
+ entryModifierSources(entry).length === 0);
80
91
  }
81
92
  /**
82
- * One `@Index((user) => [...])` as source, for an index no `@Field` can express, its columns read off the
83
- * refs `param` names. Emits `sql` for an expression entry, so callers import `sql` when
84
- * {@link indexNeedsRaw} holds.
93
+ * One `@Entity` `indexes` entry as source, `index([user.email], { unique: true })`, for an index no column's
94
+ * `index()` can express, its columns read off the refs `param` names and a lone name written as the bare string.
95
+ * Emits `sql` for an expression entry, so callers import `sql` when {@link indexNeedsRaw} holds.
85
96
  */
86
- export function buildIndexDecoratorSource(index, propertyName, param) {
97
+ export function buildIndexEntrySource(index, propertyName, param) {
87
98
  const context = { param, propertyName };
88
99
  const entries = index.entries.map((entry) => indexEntrySource(entry, context)).join(', ');
89
100
  const options = Object.values(INDEX_OPTION_SOURCE).flatMap((source) => source?.(index, context) ?? []);
90
- return `@Index((${param}) => [${entries}]${options.length > 0 ? `, { ${options.join(', ')} }` : ''})`;
101
+ const name = index.name ? quoted(index.name) : undefined;
102
+ if (name !== undefined && options.length === 0) {
103
+ return `index([${entries}], ${name})`;
104
+ }
105
+ const written = name === undefined ? options : [`name: ${name}`, ...options];
106
+ return written.length ? `index([${entries}], { ${written.join(', ')} })` : `index([${entries}])`;
91
107
  }
92
- /** Whether emitting this index needs `sql` imported alongside `Index`. */
108
+ /** Whether emitting this index needs `sql` imported. */
93
109
  export function indexNeedsRaw(index) {
94
- return Boolean(index.where) || index.entries.some((entry) => entry.expression);
110
+ return Boolean(index.where) || index.entries.some((entry) => entry.expression !== undefined);
111
+ }
112
+ function indexEntrySource(entry, context) {
113
+ const target = entryTargetSource(entry, context);
114
+ const modifiers = entryModifierSources(entry);
115
+ return modifiers.length === 0 ? target : `{ column: ${target}, ${modifiers.join(', ')} }`;
95
116
  }
96
- function indexEntrySource(entry, { param, propertyName }) {
97
- const column = entry.expression ? sqlTag(entry.column) : memberSource(param, propertyName(entry.column));
98
- const modifiers = entryModifiers(entry);
99
- return modifiers.length === 0 ? column : `{ column: ${column}, ${modifiers.join(', ')} }`;
117
+ /** What an entry indexes as source: a member, a JSON path read along one, or `sql`. */
118
+ function entryTargetSource(entry, { param, propertyName }) {
119
+ if (entry.expression !== undefined) {
120
+ return sqlTag(entry.expression);
121
+ }
122
+ if (entry.column !== undefined) {
123
+ return memberSource(param, propertyName(entry.column));
124
+ }
125
+ const keys = entry.path ? jsonPathKeys(entry.path) : [];
126
+ return keys.reduce((source, key) => memberSource(source, key), memberSource(param, propertyName(entry.json)));
100
127
  }
@@ -54,8 +54,8 @@ const storedLiteral = (value, dialect) => typeof value === 'boolean' && dialect.
54
54
  * compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
55
55
  */
56
56
  export function knownDefault(expression, dialect) {
57
- const name = SQL_VALUE_NAMES.find((kind) => dialect.sqlValues[kind] !== undefined && sameDefault(new SqlExpression(kind), expression, dialect));
58
- return name ? new SqlExpression(name) : expression;
57
+ const name = SQL_VALUE_NAMES.find((kind) => dialect.sqlValues[kind] !== undefined && sameDefault(SqlExpression.named(kind), expression, dialect));
58
+ return name ? SqlExpression.named(name) : expression;
59
59
  }
60
60
  /**
61
61
  * Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
@@ -92,16 +92,17 @@ function defaultLiteral(value, dialect, columnType) {
92
92
  return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
93
93
  }
94
94
  /** A raw expression's own SQL, else the engine's spelling of the value it names. */
95
- function expressionSql({ kind, sql }, dialect, columnType) {
96
- if (sql !== undefined) {
97
- return sql;
95
+ function expressionSql(expression, dialect, columnType) {
96
+ if (expression.kind === 'sql') {
97
+ return expression.sql;
98
98
  }
99
+ const { kind } = expression;
99
100
  const { preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
100
101
  if (kind === 'currentTimestamp' && preciseTypes) {
101
102
  const precision = columnType === undefined ? undefined : preciseTypes.exec(columnType)?.[1];
102
103
  return precision ? `CURRENT_TIMESTAMP(${precision})` : 'CURRENT_TIMESTAMP';
103
104
  }
104
- const spelled = kind === 'sql' ? undefined : dialect.sqlValues[kind];
105
+ const spelled = dialect.sqlValues[kind];
105
106
  if (spelled === undefined) {
106
107
  throw new UqlUsageError(`${dialect.engineName} has no ${kind}; write it as raw SQL this engine accepts`);
107
108
  }
@@ -1,11 +1,12 @@
1
1
  import { type IndexType } from '../../schema/types.js';
2
- import type { IndexFeature, SqlDialectName } from '../../type/index.js';
2
+ import type { DialectName, IndexFeature } from '../../type/index.js';
3
3
  /** What an engine's `CREATE INDEX` can say; an index asking for anything else is refused rather than emitted. */
4
4
  export type IndexCapabilities = {
5
- /** The types its `CREATE INDEX` takes. SQLite's has no `USING`, so every type builds its plain index there. */
6
- readonly types: ReadonlySet<IndexType>;
7
- /** The features it can express, each supported by one engine and a hard error at the server on another. */
8
- readonly features: ReadonlySet<IndexFeature>;
5
+ /**
6
+ * Each type its `CREATE INDEX` takes, with the features it can express on one, each a hard error at the server
7
+ * where it is missing. An untyped index is its `btree`. SQLite's has no `USING`, so every type builds its plain one.
8
+ */
9
+ readonly types: ReadonlyMap<IndexType, ReadonlySet<IndexFeature>>;
9
10
  /**
10
11
  * The types it spells as a keyword of their own (`FULLTEXT INDEX`, `VECTOR INDEX`) rather than as an access
11
12
  * method: one table drives both, so a keyword never also leaks out as a ` USING` the engine has no word for.
@@ -16,5 +17,5 @@ export type IndexCapabilities = {
16
17
  /** Whether `CREATE TABLE` takes a plain index among its definitions, built with the table. */
17
18
  readonly inline: boolean;
18
19
  };
19
- /** Each engine's {@link IndexCapabilities}, total over the SQL engines. */
20
- export declare const INDEX_CAPABILITIES: Readonly<Record<SqlDialectName, IndexCapabilities>>;
20
+ /** Each engine's {@link IndexCapabilities}, total over the engines. */
21
+ export declare const INDEX_CAPABILITIES: Readonly<Record<DialectName, IndexCapabilities>>;
@@ -3,29 +3,31 @@ import { VECTOR_INDEX_TYPES } from '../../type/vector.js';
3
3
  const NONE = new Map();
4
4
  /** A full-text index is its own keyword in the MySQL family: `USING fulltext` is a syntax error there. */
5
5
  const MYSQL_LIKE_KEYWORDS = new Map([['fulltext', 'FULLTEXT INDEX']]);
6
+ /** Each of `types`, expressing the same `features`. */
7
+ function typesWith(types, features) {
8
+ const expressed = new Set(features);
9
+ return new Map(types.map((type) => [type, expressed]));
10
+ }
6
11
  const DECLARE_VECTOR = "; declare type: 'vector' instead";
7
- /** Each engine's {@link IndexCapabilities}, total over the SQL engines. */
12
+ /** Each engine's {@link IndexCapabilities}, total over the engines. */
8
13
  export const INDEX_CAPABILITIES = {
9
14
  /** Postgres 18's `pg_am`, with pgvector's two, and `fulltext`, which builds a `gin` one. */
10
15
  postgres: {
11
- types: new Set(['btree', 'hash', 'gin', 'gist', 'brin', 'hnsw', 'ivfflat', 'fulltext']),
12
- features: new Set(['expression', 'partial', 'nullsOrder', 'opsClass', 'include', 'jsonPath']),
16
+ types: typesWith(['btree', 'hash', 'gin', 'gist', 'brin', 'hnsw', 'ivfflat', 'fulltext'], ['expression', 'partial', 'nullsOrder', 'opsClass', 'include', 'jsonPath']),
13
17
  keywords: NONE,
14
18
  hints: NONE,
15
19
  inline: false,
16
20
  },
17
21
  /** v26.3 answers `hash` and `brin` "unimplemented", `ivfflat` "unrecognized"; no nulls order nor operator class. */
18
22
  cockroachdb: {
19
- types: new Set(['btree', 'gin', 'gist', 'hnsw', 'vector', 'fulltext']),
20
- features: new Set(['expression', 'partial', 'include', 'jsonPath']),
23
+ types: typesWith(['btree', 'gin', 'gist', 'hnsw', 'vector', 'fulltext'], ['expression', 'partial', 'include', 'jsonPath']),
21
24
  keywords: new Map([['vector', 'VECTOR INDEX']]),
22
25
  hints: new Map([['ivfflat', DECLARE_VECTOR]]),
23
26
  inline: true,
24
27
  },
25
28
  /** No vector index: MySQL 26.7 has no distance function outside HeatWave, and `VECTOR INDEX` is MariaDB's. */
26
29
  mysql: {
27
- types: new Set(['btree', 'hash', 'fulltext']),
28
- features: new Set(['expression', 'prefixLength', 'jsonPath', 'jsonArray']),
30
+ types: typesWith(['btree', 'hash', 'fulltext'], ['expression', 'prefixLength', 'jsonPath', 'jsonArray']),
29
31
  keywords: MYSQL_LIKE_KEYWORDS,
30
32
  hints: new Map(VECTOR_INDEX_TYPES.map((type) => [type, '. Vector search on MySQL needs HeatWave'])),
31
33
  inline: true,
@@ -35,8 +37,7 @@ export const INDEX_CAPABILITIES = {
35
37
  * either. A vector index of its own, `CREATE VECTOR INDEX`, 11.7+.
36
38
  */
37
39
  mariadb: {
38
- types: new Set(['btree', 'hash', 'fulltext', 'vector']),
39
- features: new Set(['prefixLength']),
40
+ types: typesWith(['btree', 'hash', 'fulltext', 'vector'], ['prefixLength']),
40
41
  keywords: new Map([...MYSQL_LIKE_KEYWORDS, ['vector', 'VECTOR INDEX']]),
41
42
  hints: new Map([
42
43
  ['hnsw', DECLARE_VECTOR],
@@ -49,16 +50,28 @@ export const INDEX_CAPABILITIES = {
49
50
  * the rowstore B-tree, since the index built in its place fails on a `VECTOR` or `nvarchar(max)` (Msg 1978).
50
51
  */
51
52
  mssql: {
52
- types: new Set(['btree']),
53
- features: new Set(['partial']),
53
+ types: typesWith(['btree'], ['partial']),
54
54
  keywords: NONE,
55
55
  hints: NONE,
56
56
  inline: false,
57
57
  },
58
58
  /** Every type builds a plain index, so an entity written for Postgres migrates; libSQL's vector is DiskANN. */
59
59
  sqlite: {
60
- types: new Set(INDEX_TYPES),
61
- features: new Set(['expression', 'partial', 'jsonPath']),
60
+ types: typesWith(INDEX_TYPES, ['expression', 'partial', 'jsonPath']),
61
+ keywords: NONE,
62
+ hints: NONE,
63
+ inline: false,
64
+ },
65
+ /**
66
+ * A key spec says a plain key or `'text'`, and Atlas adds its vector search index, which pre-filters on fields
67
+ * instead of a predicate. A path inside a document, or each element of an array there, is a key like any other:
68
+ * a multikey index on an array.
69
+ */
70
+ mongodb: {
71
+ types: new Map([
72
+ ...typesWith(['btree', 'fulltext'], ['partial', 'jsonPath', 'jsonArray', 'fulltextPath']),
73
+ ['vectorSearch', new Set()],
74
+ ]),
62
75
  keywords: NONE,
63
76
  hints: NONE,
64
77
  inline: false,
@@ -1,11 +1,12 @@
1
1
  import type { AbstractSqlDialect } from '../../dialect/abstractSqlDialect.js';
2
- import type { IndexType } from '../../schema/types.js';
3
- import { type EngineName, type IndexColumnSchema, type IndexFeature, type IndexJsonPath, type IndexSchema } from '../../type/index.js';
2
+ import { type EngineName, type IndexEntry, type IndexSchema } from '../../type/index.js';
3
+ import { type JsonIndexRead } from '../../util/indexEntry.util.js';
4
4
  import { type IndexCapabilities } from './indexCapabilities.js';
5
- /** Refuses an index of a type `types` lacks, `hints` naming what to declare instead. */
6
- export declare function assertIndexType(index: IndexSchema, types: ReadonlySet<IndexType>, engine: EngineName, hints?: ReadonlyMap<IndexType, string>): void;
7
- /** Refuses an index asking for a feature `features` lacks. */
8
- export declare function assertIndexFeatures(index: IndexSchema, features: ReadonlySet<IndexFeature>, engine: EngineName): void;
5
+ /**
6
+ * Refuses an index `capabilities` cannot express: a type it lacks, its hint naming what to declare instead, or a
7
+ * feature that type cannot take, naming the type where another of the engine's can.
8
+ */
9
+ export declare function assertExpressible(index: IndexSchema, capabilities: IndexCapabilities, engine: EngineName): void;
9
10
  /**
10
11
  * `CREATE INDEX` in its portable form, which the SQLite family takes as is; the engines with more override
11
12
  * the fragments. The migrator's own, so no runtime entry carries it.
@@ -23,7 +24,6 @@ export declare class IndexDdl {
23
24
  * `CREATE INDEX`. Never a unique one: CockroachDB makes that a constraint, which `DROP INDEX` refuses.
24
25
  */
25
26
  inlineDefinition(index: IndexSchema): string | undefined;
26
- private assertExpressible;
27
27
  /** What follows the name and access method, in either form: the columns, then what qualifies them. */
28
28
  private indexBody;
29
29
  /** What an index added to a table that has rows needs run after it to serve queries; nothing, mostly. */
@@ -35,20 +35,20 @@ export declare class IndexDdl {
35
35
  /** What the index is over, between the parentheses: a fulltext one's columns as a search matches them, else its entries. */
36
36
  protected indexTarget(index: IndexSchema): string;
37
37
  /** One index entry: what is indexed, its operator class if any, then its stored order. */
38
- protected indexColumn(entry: IndexColumnSchema, index: IndexSchema): string;
38
+ protected indexColumn(entry: IndexEntry<string>, index: IndexSchema): string;
39
39
  /**
40
40
  * A quoted column, optionally prefix-limited, or an expression in its own parentheses - the form
41
41
  * `((lower("email")))` that MySQL requires and Postgres, CockroachDB and SQLite all accept, so one
42
42
  * rendering serves every engine that has expression indexes. A JSON entry is one of those too, its
43
43
  * expression compiled from the path rather than written out by the caller.
44
44
  */
45
- protected indexColumnTarget(entry: IndexColumnSchema): string;
45
+ protected indexColumnTarget(entry: IndexEntry<string>): string;
46
46
  /** The path read the way a query comparing it reads it, which is how the planner matches the two. */
47
- protected jsonPathIndexExpr(escapedColumn: string, json: IndexJsonPath): string;
47
+ protected jsonIndexExpr(escapedColumn: string, json: JsonIndexRead): string;
48
48
  /** Postgres-wire dialects put a vector or user-declared operator class here. */
49
- protected indexColumnOpsClass(_entry: IndexColumnSchema, _index: IndexSchema): string;
49
+ protected indexColumnOpsClass(_entry: IndexEntry<string>, _index: IndexSchema): string;
50
50
  /** `ASC` is every engine's default, so only `DESC` is worth emitting. */
51
- protected indexColumnOrder(entry: IndexColumnSchema): string;
51
+ protected indexColumnOrder(entry: IndexEntry<string>): string;
52
52
  /** ` INCLUDE (...)`: non-key columns stored for index-only scans. Postgres-wire only. */
53
53
  protected indexInclude(_index: IndexSchema): string;
54
54
  /** The metric this engine's vector index names for the index's distance, refusing a distance it has none for. */
@@ -58,7 +58,7 @@ export declare class IndexDdl {
58
58
  /** What trails the columns: pgvector's ` WITH (m = ...)`, MySQL's ` USING btree`, MariaDB's ` M=8`. */
59
59
  protected indexTuning(_index: IndexSchema): string;
60
60
  /**
61
- * The partial-index predicate. Engines without one reject the index in {@link assertIndexFeatures}
61
+ * The partial-index predicate. Engines without one reject the index in {@link assertExpressible}
62
62
  * rather than reaching here: silently widening a partial unique index changes which rows the
63
63
  * database accepts.
64
64
  */