uql-orm 0.104.1 → 0.105.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 (143) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +7 -7
  4. package/dist/dialect/abstractSqlDialect.d.ts +6 -4
  5. package/dist/dialect/abstractSqlDialect.js +35 -32
  6. package/dist/dialect/aliases.d.ts +2 -0
  7. package/dist/dialect/aliases.js +2 -0
  8. package/dist/dialect/jsonSql.js +2 -2
  9. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  10. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  11. package/dist/dialect/operators.js +2 -4
  12. package/dist/dialect/queryJoins.d.ts +2 -0
  13. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  14. package/dist/dialect/vectorSqlDialect.js +1 -1
  15. package/dist/entity/column.d.ts +3 -0
  16. package/dist/entity/column.js +3 -0
  17. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  18. package/dist/entity/columnOptionsBuilder.js +108 -0
  19. package/dist/entity/decorator/bag.d.ts +4 -4
  20. package/dist/entity/decorator/entity.d.ts +2 -19
  21. package/dist/entity/decorator/entity.js +3 -37
  22. package/dist/entity/decorator/members.d.ts +46 -76
  23. package/dist/entity/decorator/members.js +18 -7
  24. package/dist/entity/index.d.ts +2 -1
  25. package/dist/entity/index.js +2 -1
  26. package/dist/entity/metadata/definition.d.ts +10 -24
  27. package/dist/entity/metadata/definition.js +329 -147
  28. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  29. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  30. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  31. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  32. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  33. package/dist/entity/metadata/schemaFixture/book.js +22 -0
  34. package/dist/http/query.js +12 -13
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +2 -1
  37. package/dist/mariadb/mariaDialect.js +1 -1
  38. package/dist/mariadb/mariadbQuerier.js +1 -3
  39. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  40. package/dist/migrate/builder/columnBuilder.js +104 -110
  41. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  42. package/dist/migrate/builder/migrationBuilder.js +7 -6
  43. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  44. package/dist/migrate/builder/tableBuilder.js +88 -204
  45. package/dist/migrate/builder/types.d.ts +52 -151
  46. package/dist/migrate/builder/types.js +0 -6
  47. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  49. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  50. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  51. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  52. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  53. package/dist/migrate/ddl/defaultSql.js +7 -6
  54. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  55. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  56. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  57. package/dist/migrate/ddl/indexDdl.js +33 -30
  58. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  59. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  60. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  61. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  62. package/dist/migrate/drift/driftDetector.js +2 -2
  63. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  64. package/dist/migrate/generator/definitionToNode.js +4 -5
  65. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  66. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  67. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  68. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  69. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  70. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  71. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  72. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  73. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  74. package/dist/migrate/schemaChange.d.ts +3 -3
  75. package/dist/migrate/schemaChange.js +3 -2
  76. package/dist/migrate/schemaGenerator.js +1 -1
  77. package/dist/migrate/storage/databaseStorage.js +4 -4
  78. package/dist/mongodb/mongoDialect.d.ts +33 -36
  79. package/dist/mongodb/mongoDialect.js +118 -32
  80. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  81. package/dist/mongodb/mongoIntrospector.js +11 -5
  82. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  83. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  84. package/dist/mongodb/mongodbQuerier.js +9 -43
  85. package/dist/querier/abstractQuerier.d.ts +0 -1
  86. package/dist/querier/abstractQuerier.js +1 -20
  87. package/dist/querier/keyset.js +3 -3
  88. package/dist/schema/declaredColumn.d.ts +11 -0
  89. package/dist/schema/declaredColumn.js +21 -0
  90. package/dist/schema/indexColumns.d.ts +0 -3
  91. package/dist/schema/indexColumns.js +11 -7
  92. package/dist/schema/indexDifferences.d.ts +10 -5
  93. package/dist/schema/indexDifferences.js +42 -28
  94. package/dist/schema/schemaASTBuilder.js +28 -36
  95. package/dist/schema/schemaASTDiffer.js +8 -4
  96. package/dist/schema/sqlExpression.d.ts +21 -17
  97. package/dist/schema/sqlExpression.js +11 -23
  98. package/dist/type/column.d.ts +328 -0
  99. package/dist/type/column.js +2 -0
  100. package/dist/type/config.d.ts +1 -1
  101. package/dist/type/dialect.d.ts +2 -1
  102. package/dist/type/dialect.js +1 -0
  103. package/dist/type/entity.d.ts +290 -279
  104. package/dist/type/entity.js +6 -1
  105. package/dist/type/index.d.ts +2 -0
  106. package/dist/type/index.js +2 -0
  107. package/dist/type/migration.d.ts +5 -5
  108. package/dist/type/query.d.ts +44 -40
  109. package/dist/type/query.js +2 -3
  110. package/dist/type/queryAggregate.d.ts +22 -12
  111. package/dist/type/querySql.d.ts +20 -4
  112. package/dist/type/querySql.js +27 -9
  113. package/dist/type/schemaEntity.d.ts +190 -0
  114. package/dist/type/schemaEntity.js +1 -0
  115. package/dist/type/utility.d.ts +0 -6
  116. package/dist/type/vector.d.ts +1 -1
  117. package/dist/util/ddlExpression.util.d.ts +12 -13
  118. package/dist/util/ddlExpression.util.js +12 -21
  119. package/dist/util/dialect.util.d.ts +11 -5
  120. package/dist/util/dialect.util.js +31 -37
  121. package/dist/util/field.util.d.ts +10 -9
  122. package/dist/util/field.util.js +14 -10
  123. package/dist/util/fieldOption.util.d.ts +11 -95
  124. package/dist/util/fieldOption.util.js +49 -16
  125. package/dist/util/hook.util.d.ts +2 -14
  126. package/dist/util/hook.util.js +3 -16
  127. package/dist/util/index.d.ts +1 -0
  128. package/dist/util/index.js +1 -0
  129. package/dist/util/indexEntry.util.d.ts +45 -0
  130. package/dist/util/indexEntry.util.js +138 -0
  131. package/dist/util/relationQuery.util.d.ts +0 -1
  132. package/dist/util/relationQuery.util.js +0 -5
  133. package/dist/util/sql.d.ts +10 -7
  134. package/dist/util/sql.js +34 -16
  135. package/dist/util/sql.util.d.ts +4 -5
  136. package/dist/util/sql.util.js +7 -16
  137. package/dist/util/string.util.d.ts +2 -0
  138. package/dist/util/string.util.js +4 -0
  139. package/dist/util/uqlError.d.ts +1 -1
  140. package/dist/util/uqlError.js +1 -1
  141. package/package.json +1 -1
  142. package/skills/uql-orm/SKILL.md +76 -25
  143. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -1,73 +1,6 @@
1
- /**
2
- * Migration Builder Types
3
- *
4
- * Type definitions for the fluent migration builder API.
5
- * Enables type-safe migrations without raw SQL.
6
- */
7
1
  import type { ColumnNode, EnumValues, ForeignKeyAction } from '../../schema/types.js';
8
- import type { EntityIndexColumn, Except, IndexColumnInput, IndexOptions, IndexSchema, QuerySql } from '../../type/index.js';
2
+ import type { IndexEntry, Except, FieldOptions, IndexColumnInput, IndexOptions, IndexSchema, QuerySql } from '../../type/index.js';
9
3
  import type { ForeignKeySchema } from '../../type/migration.js';
10
- /**
11
- * Foreign key reference options.
12
- */
13
- export interface ReferenceOptions {
14
- /** Referenced table */
15
- table: string;
16
- /** Referenced column (default: 'id') */
17
- column?: string;
18
- /** Action on delete */
19
- onDelete?: ForeignKeyAction;
20
- /** Action on update */
21
- onUpdate?: ForeignKeyAction;
22
- }
23
- /**
24
- * Base options for all column types.
25
- * Columns are NOT NULL by default (safer).
26
- */
27
- export interface BaseColumnOptions {
28
- /** Whether the column is nullable (default: false) */
29
- nullable?: boolean;
30
- /** Whether this column has a unique constraint */
31
- unique?: boolean;
32
- /** Set as primary key */
33
- primaryKey?: boolean;
34
- /** Enable auto-increment (for integer types) */
35
- autoIncrement?: boolean;
36
- /** Default value or expression */
37
- defaultValue?: unknown;
38
- /** Add an index (true = auto-name, string = custom name) */
39
- index?: boolean | string;
40
- /** Column comment */
41
- comment?: string;
42
- /** Whether the numeric type is unsigned (MySQL/MariaDB) */
43
- unsigned?: boolean;
44
- /** Foreign key reference */
45
- references?: ReferenceOptions;
46
- }
47
- /**
48
- * Options for string/char columns.
49
- */
50
- export interface StringColumnOptions extends BaseColumnOptions {
51
- /** Maximum length (default: 255 for string, 1 for char) */
52
- length?: number;
53
- }
54
- /**
55
- * Options for decimal columns.
56
- */
57
- export interface DecimalColumnOptions extends BaseColumnOptions {
58
- /** Total digits */
59
- precision?: number;
60
- /** Digits after decimal point */
61
- scale?: number;
62
- }
63
- /**
64
- * Options for vector columns (AI embeddings).
65
- */
66
- export interface VectorColumnOptions extends BaseColumnOptions {
67
- /** Number of dimensions */
68
- dimensions?: number;
69
- }
70
- /** A column as the builder describes one: a {@link ColumnNode} without its graph links. */
71
4
  export type ColumnDefinition = Except<ColumnNode, 'table'>;
72
5
  /**
73
6
  * The foreign key a single column declares: {@link ForeignKeySchema} without the local columns, which
@@ -87,13 +20,13 @@ export interface FullColumnDefinition extends ColumnDefinition {
87
20
  index?: string | boolean;
88
21
  }
89
22
  /**
90
- * An index as the builder records it, with the entries and options `@Index` takes: its SQL kept as `raw`
23
+ * An index as the builder records it, with the entries and options an entity's `indexes` entry takes: its SQL kept as `raw`
91
24
  * until a generator renders it for the engine the migration runs on.
92
25
  */
93
26
  export type IndexDefinition = Except<IndexSchema, 'name' | 'entries' | 'where'> & {
94
27
  /** As declared; an unnamed index is named when it is rendered, from its predicate as written. */
95
28
  readonly name?: string;
96
- readonly entries: readonly EntityIndexColumn[];
29
+ readonly entries: readonly IndexEntry[];
97
30
  readonly where?: QuerySql;
98
31
  /** Whether an unnamed index takes the `_uk` kind. Only `table.unique` sets it: earlier migrations installed `_uk` there, so `index` keeps `_idx`. */
99
32
  readonly uniqueName?: boolean;
@@ -169,104 +102,72 @@ export type AnyMigrationOperation = {
169
102
  export type ForeignKeyTarget = ForeignKeySchema['references'];
170
103
  /** A foreign key's constraint name and actions, each the engine's default where unstated. */
171
104
  export type ForeignKeyOptions = Pick<ForeignKeySchema, 'name' | 'onDelete' | 'onUpdate'>;
172
- /**
173
- * Interface for column builder (fluent API).
174
- */
175
- export interface ColumnBuilder {
176
- /** Make column nullable */
177
- nullable(value?: boolean): this;
178
- /** Make column NOT NULL (convenience method) */
179
- notNullable(): this;
180
- /** Set default value */
181
- defaultValue(value: unknown): this;
182
- /** Set as primary key */
183
- primaryKey(): this;
184
- /** Enable auto-increment */
105
+ /** A table's column, in an entity column's vocabulary: `table.string('email').length(80).nullable()`. */
106
+ export interface TableColumnBuilder {
107
+ /** Lets the column hold `null`: a column is `NOT NULL` otherwise, as an entity's is. */
108
+ nullable(): this;
109
+ /** The column's DDL default: a value, or SQL the database evaluates per row (`currentTimestamp`, `sql`). */
110
+ default(value: FieldOptions['defaultValue']): this;
111
+ /** Makes it the primary key. */
112
+ id(): this;
185
113
  autoIncrement(): this;
186
- /** Add unique constraint */
187
114
  unique(): this;
188
- /** Constrain the column to these values, as a `CHECK (col IN (...))`. */
115
+ /** A string column's length. */
116
+ length(length: number): this;
117
+ /** A decimal's digits, or a timestamp's fractional-second digits. */
118
+ precision(digits: number): this;
119
+ scale(digits: number): this;
189
120
  enum(values: EnumValues): this;
190
- /** Make the column one the database computes, as `GENERATED ALWAYS AS (<sql>) STORED`. */
191
- computed(sql: string): this;
192
- /** Add comment */
121
+ /** A column the database computes, `GENERATED ALWAYS AS (<sql>) STORED`, its SQL as text. */
122
+ as(sql: string): this;
193
123
  comment(text: string): this;
194
- /** Add index */
195
124
  index(name?: string): this;
196
- /** Set as unsigned (MySQL/MariaDB) */
197
125
  unsigned(): this;
198
- /** Add foreign key reference */
199
126
  references(table: string, column?: string): ForeignKeyBuilder;
200
- /** Get the built column definition */
201
127
  build(): FullColumnDefinition;
202
128
  }
203
- /**
204
- * Interface for foreign key builder.
205
- */
206
- export interface ForeignKeyBuilder extends ColumnBuilder {
129
+ export interface ForeignKeyBuilder extends TableColumnBuilder {
207
130
  /** Set ON DELETE action */
208
131
  onDelete(action: ForeignKeyAction): this;
209
132
  /** Set ON UPDATE action */
210
133
  onUpdate(action: ForeignKeyAction): this;
211
134
  }
212
- /** Every column type the builder can declare, name first, handed to `addColumn`/`alterColumn` callbacks too. */
213
- export interface ColumnFactory {
214
- /** Add an auto-incrementing primary key */
215
- id(name?: string, options?: BaseColumnOptions): ColumnBuilder;
216
- /** Add an integer column */
217
- integer(name: string, options?: BaseColumnOptions): ColumnBuilder;
218
- /** Add a smallint column */
219
- smallint(name: string, options?: BaseColumnOptions): ColumnBuilder;
220
- /** Add a bigint column */
221
- bigint(name: string, options?: BaseColumnOptions): ColumnBuilder;
222
- /** Add a float column */
223
- float(name: string, options?: BaseColumnOptions): ColumnBuilder;
224
- /** Add a double column */
225
- double(name: string, options?: BaseColumnOptions): ColumnBuilder;
226
- /** Add a decimal column */
227
- decimal(name: string, options?: DecimalColumnOptions): ColumnBuilder;
228
- /** Add a varchar column */
229
- string(name: string, options?: StringColumnOptions): ColumnBuilder;
230
- /** Add a char column */
231
- char(name: string, options?: StringColumnOptions): ColumnBuilder;
232
- /** Add a text column */
233
- text(name: string, options?: BaseColumnOptions): ColumnBuilder;
234
- /** Add a boolean column */
235
- boolean(name: string, options?: BaseColumnOptions): ColumnBuilder;
236
- /** Add a date column */
237
- date(name: string, options?: BaseColumnOptions): ColumnBuilder;
238
- /** Add a time column */
239
- time(name: string, options?: BaseColumnOptions): ColumnBuilder;
240
- /** Add a timestamp column */
241
- timestamp(name: string, options?: BaseColumnOptions): ColumnBuilder;
242
- /** Add a timestamptz column */
243
- timestamptz(name: string, options?: BaseColumnOptions): ColumnBuilder;
244
- /** Add a JSON column */
245
- json(name: string, options?: BaseColumnOptions): ColumnBuilder;
246
- /** Add a JSONB column (Postgres) */
247
- jsonb(name: string, options?: BaseColumnOptions): ColumnBuilder;
248
- /** Add a UUID column */
249
- uuid(name: string, options?: BaseColumnOptions): ColumnBuilder;
250
- /** Add a blob/bytea column */
251
- blob(name: string, options?: BaseColumnOptions): ColumnBuilder;
252
- /** Add a vector column (for embeddings) */
253
- vector(name: string, options?: VectorColumnOptions): ColumnBuilder;
135
+ /** Every column type a table declares, name first, handed to `addColumn`/`alterColumn` callbacks too. */
136
+ export interface TableColumnFactory {
137
+ id(name?: string): TableColumnBuilder;
138
+ integer(name: string): TableColumnBuilder;
139
+ smallint(name: string): TableColumnBuilder;
140
+ bigint(name: string): TableColumnBuilder;
141
+ float(name: string): TableColumnBuilder;
142
+ double(name: string): TableColumnBuilder;
143
+ decimal(name: string, precision?: number, scale?: number): TableColumnBuilder;
144
+ /** A `VARCHAR`, 255 long unless `length()` says otherwise. */
145
+ string(name: string): TableColumnBuilder;
146
+ char(name: string): TableColumnBuilder;
147
+ text(name: string): TableColumnBuilder;
148
+ boolean(name: string): TableColumnBuilder;
149
+ date(name: string): TableColumnBuilder;
150
+ time(name: string): TableColumnBuilder;
151
+ timestamp(name: string): TableColumnBuilder;
152
+ timestamptz(name: string): TableColumnBuilder;
153
+ json(name: string): TableColumnBuilder;
154
+ jsonb(name: string): TableColumnBuilder;
155
+ uuid(name: string): TableColumnBuilder;
156
+ blob(name: string): TableColumnBuilder;
157
+ vector(name: string, dimensions?: number): TableColumnBuilder;
254
158
  }
255
- /**
256
- * Interface for table builder (fluent API).
257
- */
258
- export interface TableBuilder extends ColumnFactory {
159
+ export interface TableBuilder extends TableColumnFactory {
259
160
  /** Add createdAt timestamp column */
260
- createdAt(): ColumnBuilder;
161
+ createdAt(): TableColumnBuilder;
261
162
  /** Add updatedAt timestamp column */
262
- updatedAt(): ColumnBuilder;
163
+ updatedAt(): TableColumnBuilder;
263
164
  /** Add both createdAt and updatedAt columns */
264
165
  timestamps(): void;
265
166
  /** Add composite primary key */
266
167
  primaryKey(columns: string[]): this;
267
- /** Add a composite unique index; takes the same options as `@Index`, or just its name. */
168
+ /** Add a composite unique index; takes the same options as an `indexes` entry, or just its name. */
268
169
  unique(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
269
- /** Add a composite index; takes the same options as `@Index`, or just its name. */
170
+ /** Add a composite index; takes the same options as an `indexes` entry, or just its name. */
270
171
  index(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
271
172
  /** Add table-level foreign key */
272
173
  foreignKey(columns: string[]): TableForeignKeyBuilder;
@@ -293,13 +194,13 @@ export interface TableForeignKeyBuilder {
293
194
  */
294
195
  export interface AlterTableBuilder {
295
196
  /** Add a column, declared exactly as in `createTable`: `addColumn((c) => c.timestamp('createdAt'))`. */
296
- addColumn(callback: (columns: ColumnFactory) => ColumnBuilder): this;
197
+ addColumn(callback: (columns: TableColumnFactory) => TableColumnBuilder): this;
297
198
  /** Drop a column from the table */
298
199
  dropColumn(name: string): this;
299
200
  /** Rename a column */
300
201
  renameColumn(oldName: string, newName: string): this;
301
202
  /** Redeclare a column, named and typed as it should end up. */
302
- alterColumn(callback: (columns: ColumnFactory) => ColumnBuilder): this;
203
+ alterColumn(callback: (columns: TableColumnFactory) => TableColumnBuilder): this;
303
204
  /** Add an index to the table */
304
205
  addIndex(columns: readonly IndexColumnInput[], options?: IndexOptions): this;
305
206
  /** Drop an index from the table */
@@ -325,14 +226,14 @@ export interface MigrationBuilder {
325
226
  /** Alter an existing table */
326
227
  alterTable(name: string, callback: (table: AlterTableBuilder) => void): Promise<void>;
327
228
  /** Add a column, declared exactly as in `createTable`: `addColumn('t', (c) => c.timestamp('at'))`. */
328
- addColumn(tableName: string, callback: (columns: ColumnFactory) => ColumnBuilder): Promise<void>;
229
+ addColumn(tableName: string, callback: (columns: TableColumnFactory) => TableColumnBuilder): Promise<void>;
329
230
  /** Drop a column from a table */
330
231
  dropColumn(tableName: string, columnName: string): Promise<void>;
331
232
  /** Redeclare a column, named and typed as it should end up. */
332
- alterColumn(tableName: string, callback: (columns: ColumnFactory) => ColumnBuilder): Promise<void>;
233
+ alterColumn(tableName: string, callback: (columns: TableColumnFactory) => TableColumnBuilder): Promise<void>;
333
234
  /** Rename a column */
334
235
  renameColumn(tableName: string, oldName: string, newName: string): Promise<void>;
335
- /** Create an index; takes the same options as `@Index`, so a generated migration can restate them. */
236
+ /** Create an index; takes the same options as an `indexes` entry, so a generated migration can restate them. */
336
237
  createIndex(tableName: string, columns: readonly IndexColumnInput[], options?: IndexOptions): Promise<void>;
337
238
  /** Drop an index */
338
239
  dropIndex(tableName: string, indexName: string): Promise<void>;
@@ -1,7 +1 @@
1
- /**
2
- * Migration Builder Types
3
- *
4
- * Type definitions for the fluent migration builder API.
5
- * Enables type-safe migrations without raw SQL.
6
- */
7
1
  export {};
@@ -44,7 +44,7 @@ export declare class EntityCodeGenerator {
44
44
  generateForTable(tableName: string): GeneratedEntity | undefined;
45
45
  private generateEntity;
46
46
  private buildImports;
47
- private buildEntityDecorators;
47
+ private buildEntityDecorator;
48
48
  private buildFields;
49
49
  /** The `@sync-added` JSDoc a generated member opens with, saying `what` it is, where asked for. */
50
50
  private syncDoc;
@@ -56,7 +56,7 @@ export declare class EntityCodeGenerator {
56
56
  private buildField;
57
57
  private buildFieldOptions;
58
58
  /**
59
- * The indexes this table needs an `@Index` for, which is every one a `@Field({ index })` cannot
59
+ * The indexes this table lists under `indexes`, which is every one a `.index()` cannot
60
60
  * carry on its own.
61
61
  */
62
62
  private declaredIndexes;
@@ -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,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;