uql-orm 0.104.0 → 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 +45 -41
  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,134 +1,128 @@
1
+ import { columns } from '../../entity/columnOptionsBuilder.js';
2
+ import { declaredColumn } from '../../schema/declaredColumn.js';
3
+ import { COLUMN_OPTIONS } from '../../type/index.js';
4
+ import { fieldOptionConflict } from '../../util/fieldOption.util.js';
5
+ import { constantSql, sql } from '../../util/sql.js';
6
+ import { UqlUsageError } from '../../util/uqlError.js';
7
+ /** A migration's SQL as written: it names no field, so it is the text of a `sql` interpolating nothing. */
8
+ function migrationSql(statement) {
9
+ const text = constantSql(statement);
10
+ if (text === undefined) {
11
+ throw new UqlUsageError("a migration's SQL binds nothing: write it as `sql` text interpolating no value");
12
+ }
13
+ return text;
14
+ }
1
15
  /**
2
- * Column Builder
3
- *
4
- * Fluent API for defining columns in migrations.
5
- */
6
- /**
7
- * Builder for column definitions with a fluent API. Each call replaces the definition it holds, and `build`
8
- * returns it. Columns are NOT NULL by default (safer).
16
+ * A table's column, named, over the `f` builder an entity column is: each method is that builder's, and `build` reads
17
+ * its options as the schema reads an entity's. Mutable, since the table collects it before its chain ends.
9
18
  */
10
- export class ColumnDefinitionBuilder {
11
- column;
12
- constructor(name, type, options = {}) {
13
- const { references } = options;
14
- this.column = {
15
- name,
16
- type: options.unsigned === undefined ? type : { ...type, unsigned: options.unsigned },
17
- nullable: options.nullable ?? false,
18
- defaultValue: options.defaultValue,
19
- isPrimaryKey: options.primaryKey ?? false,
20
- isAutoIncrement: options.autoIncrement ?? false,
21
- isUnique: options.unique ?? false,
22
- enum: undefined,
23
- generatedAs: undefined,
24
- comment: options.comment,
25
- index: options.index,
26
- foreignKey: references && {
27
- references: { table: references.table, columns: [references.column ?? 'id'] },
28
- onDelete: references.onDelete,
29
- onUpdate: references.onUpdate,
30
- },
31
- };
32
- }
33
- set(change) {
34
- this.column = { ...this.column, ...change };
19
+ export class TableColumn {
20
+ #name;
21
+ #column;
22
+ #unsigned = false;
23
+ #target;
24
+ #onDelete;
25
+ #onUpdate;
26
+ constructor(name, column) {
27
+ this.#name = name;
28
+ this.#column = column;
29
+ }
30
+ chain(column) {
31
+ this.#column = column;
35
32
  return this;
36
33
  }
37
- /**
38
- * Make the column nullable or not nullable.
39
- */
40
- nullable(value = true) {
41
- return this.set({ nullable: value });
42
- }
43
- /**
44
- * Make the column NOT NULL.
45
- */
46
- notNullable() {
47
- return this.set({ nullable: false });
48
- }
49
- /**
50
- * Set a default value for the column.
51
- */
52
- defaultValue(value) {
53
- return this.set({ defaultValue: value });
54
- }
55
- /**
56
- * Mark as primary key.
57
- */
58
- primaryKey() {
59
- return this.set({ isPrimaryKey: true, nullable: false });
60
- }
61
- /**
62
- * Enable auto-increment (for integer types).
63
- */
34
+ nullable() {
35
+ return this.chain(this.#column.nullable());
36
+ }
37
+ default(value) {
38
+ return this.chain(this.#column.default(value));
39
+ }
40
+ id() {
41
+ return this.chain(this.#column.id());
42
+ }
64
43
  autoIncrement() {
65
- return this.set({ isAutoIncrement: true });
44
+ return this.chain(this.#column.autoIncrement());
66
45
  }
67
- /**
68
- * Add a unique constraint.
69
- */
70
46
  unique() {
71
- return this.set({ isUnique: true });
72
- }
73
- /**
74
- * Make the column one the database computes: `GENERATED ALWAYS AS (<sql>) STORED`.
75
- *
76
- * Takes the SQL as text, since a `CREATE TABLE` has nowhere to bind a value into - the same reason
77
- * a check expression and a partial-index predicate do.
78
- */
79
- computed(sql) {
80
- return this.set({ generatedAs: sql });
81
- }
82
- /**
83
- * Constrain the column to these values, as a `CHECK (col IN (...))` - what `@Field({ enum })` emits.
84
- */
47
+ return this.chain(this.#column.unique());
48
+ }
49
+ as(expression) {
50
+ return this.chain(this.#column.as(sql.text(expression)).stored());
51
+ }
52
+ length(length) {
53
+ return this.chain(this.#column.length(length));
54
+ }
55
+ precision(digits) {
56
+ return this.chain(this.#column.precision(digits));
57
+ }
58
+ scale(digits) {
59
+ return this.chain(this.#column.scale(digits));
60
+ }
85
61
  enum(values) {
86
- return this.set({ enum: values });
62
+ return this.chain(this.#column.with({ enum: values }));
87
63
  }
88
- /**
89
- * Add a comment to the column.
90
- */
91
64
  comment(text) {
92
- return this.set({ comment: text });
65
+ return this.chain(this.#column.comment(text));
93
66
  }
94
- /**
95
- * Add an index on this column.
96
- * @param name - Optional index name. If true, auto-generates name.
97
- */
98
67
  index(name) {
99
- return this.set({ index: name ?? true });
68
+ return this.chain(this.#column.index(name));
100
69
  }
101
- /**
102
- * Set as unsigned (MySQL/MariaDB).
103
- */
104
70
  unsigned() {
105
- return this.set({ type: { ...this.column.type, unsigned: true } });
71
+ this.#unsigned = true;
72
+ return this;
106
73
  }
107
- /**
108
- * Add a foreign key reference.
109
- * Returns a ForeignKeyBuilder for additional options.
110
- */
111
74
  references(table, column = 'id') {
112
- return this.set({ foreignKey: { references: { table, columns: [column] } } });
75
+ this.#target = { table, columns: [column] };
76
+ return this;
113
77
  }
114
- /**
115
- * Set ON DELETE action for foreign key.
116
- */
117
78
  onDelete(action) {
118
- const { foreignKey } = this.column;
119
- return foreignKey ? this.set({ foreignKey: { ...foreignKey, onDelete: action } }) : this;
79
+ this.#onDelete = action;
80
+ return this;
120
81
  }
121
- /**
122
- * Set ON UPDATE action for foreign key.
123
- */
124
82
  onUpdate(action) {
125
- const { foreignKey } = this.column;
126
- return foreignKey ? this.set({ foreignKey: { ...foreignKey, onUpdate: action } }) : this;
83
+ this.#onUpdate = action;
84
+ return this;
127
85
  }
128
- /**
129
- * Build and return the column definition.
130
- */
86
+ /** A key here is never implied to auto-increment: a migration states what it creates. */
131
87
  build() {
132
- return this.column;
88
+ const field = this.#column[COLUMN_OPTIONS];
89
+ const conflict = fieldOptionConflict(field);
90
+ if (conflict) {
91
+ throw new UqlUsageError(`'${this.#name}' ${conflict}`);
92
+ }
93
+ const column = declaredColumn(field, { name: this.#name, soleKey: false, compile: migrationSql });
94
+ return {
95
+ ...column,
96
+ type: this.#unsigned ? { ...column.type, unsigned: true } : column.type,
97
+ enum: field.enum,
98
+ index: field.index,
99
+ foreignKey: this.#target && { references: this.#target, onDelete: this.#onDelete, onUpdate: this.#onUpdate },
100
+ };
133
101
  }
134
102
  }
103
+ /** Every column type, named and typed as `f` types it; `add` receives each column it makes. */
104
+ export function tableColumns(add) {
105
+ const named = (name, column) => add(new TableColumn(name, column));
106
+ return {
107
+ id: (name = 'id') => named(name, columns.bigint().id().autoIncrement()),
108
+ integer: (name) => named(name, columns.column('int')),
109
+ smallint: (name) => named(name, columns.column('smallint')),
110
+ bigint: (name) => named(name, columns.bigint()),
111
+ float: (name) => named(name, columns.column('float')),
112
+ double: (name) => named(name, columns.column('double')),
113
+ decimal: (name, precision, scale) => named(name, columns.decimal(precision, scale)),
114
+ string: (name) => named(name, columns.string().length(255)),
115
+ char: (name) => named(name, columns.column('char').length(1)),
116
+ text: (name) => named(name, columns.text()),
117
+ boolean: (name) => named(name, columns.boolean()),
118
+ date: (name) => named(name, columns.column('date')),
119
+ time: (name) => named(name, columns.column('time')),
120
+ timestamp: (name) => named(name, columns.column('timestamp')),
121
+ timestamptz: (name) => named(name, columns.column('timestamptz')),
122
+ json: (name) => named(name, columns.json()),
123
+ jsonb: (name) => named(name, columns.jsonb()),
124
+ uuid: (name) => named(name, columns.uuid()),
125
+ blob: (name) => named(name, columns.column('blob')),
126
+ vector: (name, dimensions) => named(name, dimensions === undefined ? columns.column('vector') : columns.vector(dimensions)),
127
+ };
128
+ }
@@ -1,5 +1,5 @@
1
1
  import type { IndexColumnInput, IndexOptions } from '../../type/index.js';
2
- import type { AnyMigrationOperation, ForeignKeyOptions, ForeignKeyTarget, AlterTableBuilder, ColumnBuilder, ColumnFactory, MigrationBuilder, TableBuilder } from './types.js';
2
+ import type { AnyMigrationOperation, ForeignKeyOptions, ForeignKeyTarget, AlterTableBuilder, MigrationBuilder, TableBuilder, TableColumnBuilder, TableColumnFactory } from './types.js';
3
3
  /**
4
4
  * The type-safe migration builder: each change is declared once, as an operation handed to `apply`.
5
5
  * `migrationBuilderFor` builds one running the statements its querier's generator writes for each.
@@ -14,9 +14,9 @@ export declare class MigrationOperationBuilder implements MigrationBuilder {
14
14
  }): Promise<void>;
15
15
  renameTable(oldName: string, newName: string): Promise<void>;
16
16
  alterTable(name: string, callback: (table: AlterTableBuilder) => void): Promise<void>;
17
- addColumn(tableName: string, callback: (columns: ColumnFactory) => ColumnBuilder): Promise<void>;
17
+ addColumn(tableName: string, callback: (columns: TableColumnFactory) => TableColumnBuilder): Promise<void>;
18
18
  dropColumn(tableName: string, columnName: string): Promise<void>;
19
- alterColumn(tableName: string, callback: (columns: ColumnFactory) => ColumnBuilder): Promise<void>;
19
+ alterColumn(tableName: string, callback: (columns: TableColumnFactory) => TableColumnBuilder): Promise<void>;
20
20
  renameColumn(tableName: string, oldName: string, newName: string): Promise<void>;
21
21
  createIndex(tableName: string, columns: readonly IndexColumnInput[], options?: IndexOptions): Promise<void>;
22
22
  dropIndex(tableName: string, indexName: string): Promise<void>;
@@ -1,9 +1,10 @@
1
1
  import { UqlUsageError } from '../../util/uqlError.js';
2
2
  import { indexDefinition } from '../generator/definitionToNode.js';
3
- import { TableDefinitionBuilder } from './tableBuilder.js';
4
- /** One column declared through `createTable`'s vocabulary, a throwaway {@link TableDefinitionBuilder}, so its type is stated. */
3
+ import { tableColumns } from './columnBuilder.js';
4
+ import { tableBuilder } from './tableBuilder.js';
5
+ /** One column declared through `createTable`'s vocabulary, so its type is stated. */
5
6
  function buildOneColumn(callback) {
6
- return callback(new TableDefinitionBuilder('')).build();
7
+ return callback(tableColumns((column) => column)).build();
7
8
  }
8
9
  /** The operations one `alterTable` callback declares, collected in order, since its methods are synchronous. */
9
10
  class AlterTableOperations {
@@ -89,9 +90,9 @@ export class MigrationOperationBuilder {
89
90
  this.apply = apply;
90
91
  }
91
92
  createTable(name, callback) {
92
- const builder = new TableDefinitionBuilder(name);
93
- callback(builder);
94
- return this.apply({ type: 'createTable', table: builder.build() });
93
+ const table = tableBuilder(name);
94
+ callback(table);
95
+ return this.apply({ type: 'createTable', table: table.build() });
95
96
  }
96
97
  dropTable(name, options = {}) {
97
98
  return this.apply({ type: 'dropTable', tableName: name, ifExists: options.ifExists, cascade: options.cascade });
@@ -1,55 +1,3 @@
1
- /**
2
- * Table Builder
3
- *
4
- * Fluent API for defining tables in migrations.
5
- */
6
- import type { IndexColumnInput, IndexOptions } from '../../type/index.js';
7
- import type { BaseColumnOptions, DecimalColumnOptions, ColumnBuilder, TableBuilder, TableForeignKeyBuilder, StringColumnOptions, TableDefinition, VectorColumnOptions } from './types.js';
8
- /**
9
- * Builder for table definitions with a fluent API.
10
- */
11
- export declare class TableDefinitionBuilder implements TableBuilder {
12
- private _name;
13
- private _columnBuilders;
14
- private _primaryKey?;
15
- private _indexes;
16
- private _foreignKeyBuilders;
17
- private _comment?;
18
- constructor(name: string);
19
- /** Big, matching an entity's `@Id`: a key is spelled from this type, so it has to state the real one. */
20
- id(name?: string, options?: BaseColumnOptions): ColumnBuilder;
21
- integer(name: string, options?: BaseColumnOptions): ColumnBuilder;
22
- smallint(name: string, options?: BaseColumnOptions): ColumnBuilder;
23
- bigint(name: string, options?: BaseColumnOptions): ColumnBuilder;
24
- float(name: string, options?: BaseColumnOptions): ColumnBuilder;
25
- double(name: string, options?: BaseColumnOptions): ColumnBuilder;
26
- decimal(name: string, options?: DecimalColumnOptions): ColumnBuilder;
27
- string(name: string, options?: StringColumnOptions): ColumnBuilder;
28
- char(name: string, options?: StringColumnOptions): ColumnBuilder;
29
- text(name: string, options?: BaseColumnOptions): ColumnBuilder;
30
- boolean(name: string, options?: BaseColumnOptions): ColumnBuilder;
31
- date(name: string, options?: BaseColumnOptions): ColumnBuilder;
32
- time(name: string, options?: BaseColumnOptions): ColumnBuilder;
33
- timestamp(name: string, options?: BaseColumnOptions): ColumnBuilder;
34
- timestamptz(name: string, options?: BaseColumnOptions): ColumnBuilder;
35
- json(name: string, options?: BaseColumnOptions): ColumnBuilder;
36
- /** One canonical json category; the dialect decides between `JSON` and `JSONB`. */
37
- jsonb(name: string, options?: BaseColumnOptions): ColumnBuilder;
38
- uuid(name: string, options?: BaseColumnOptions): ColumnBuilder;
39
- blob(name: string, options?: BaseColumnOptions): ColumnBuilder;
40
- vector(name: string, options?: VectorColumnOptions): ColumnBuilder;
41
- private add;
42
- createdAt(): ColumnBuilder;
43
- updatedAt(): ColumnBuilder;
44
- private timestampNow;
45
- timestamps(): void;
46
- primaryKey(columns: string[]): this;
47
- unique(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
48
- index(columns: readonly IndexColumnInput[], options?: string | IndexOptions): this;
49
- foreignKey(columns: string[]): TableForeignKeyBuilder;
50
- comment(text: string): this;
51
- /**
52
- * Build the table definition.
53
- */
54
- build(): TableDefinition;
55
- }
1
+ import type { TableBuilder } from './types.js';
2
+ /** A table as `createTable`'s callback declares it: its columns in `f`'s vocabulary, then what spans several. */
3
+ export declare function tableBuilder(name: string): TableBuilder;
@@ -1,215 +1,99 @@
1
- /**
2
- * Table Builder
3
- *
4
- * Fluent API for defining tables in migrations.
5
- */
6
- import { DATE_PRECISION } from '../../util/date.js';
7
1
  import { declaredIndexName } from '../../util/ddlExpression.util.js';
8
2
  import { currentTimestamp } from '../../util/sql.js';
9
3
  import { columnForeignKey, columnIndex, indexDefinition } from '../generator/definitionToNode.js';
10
- import { ColumnDefinitionBuilder } from './columnBuilder.js';
4
+ import { tableColumns } from './columnBuilder.js';
11
5
  /** Normalizes `table.index` options, where a bare string is the index name. */
12
6
  function namedOptions(options) {
13
7
  return typeof options === 'string' ? { name: options } : (options ?? {});
14
8
  }
15
- /**
16
- * Builder for table-level foreign keys.
17
- */
18
- class TableForeignKeyDefinitionBuilder {
19
- _columns;
20
- _referencedTable;
21
- _referencedColumns = [];
22
- _onDelete;
23
- _onUpdate;
24
- _name;
25
- constructor(_columns) {
26
- this._columns = _columns;
27
- }
28
- references(table, columns) {
29
- this._referencedTable = table;
30
- this._referencedColumns = columns;
31
- return this;
32
- }
33
- onDelete(action) {
34
- this._onDelete = action;
35
- return this;
36
- }
37
- onUpdate(action) {
38
- this._onUpdate = action;
39
- return this;
40
- }
41
- name(name) {
42
- this._name = name;
43
- return this;
44
- }
45
- /**
46
- * Build the foreign key definition.
47
- */
48
- build() {
49
- if (!this._referencedTable)
50
- return undefined;
51
- return {
52
- name: this._name,
53
- columns: this._columns,
54
- references: { table: this._referencedTable, columns: this._referencedColumns },
55
- onDelete: this._onDelete,
56
- onUpdate: this._onUpdate,
57
- };
58
- }
9
+ function foreignKeyDefinition(columns) {
10
+ let references;
11
+ let onDelete;
12
+ let onUpdate;
13
+ let name;
14
+ return {
15
+ references(table, referenced) {
16
+ references = { table, columns: referenced };
17
+ return this;
18
+ },
19
+ onDelete(action) {
20
+ onDelete = action;
21
+ return this;
22
+ },
23
+ onUpdate(action) {
24
+ onUpdate = action;
25
+ return this;
26
+ },
27
+ name(constraint) {
28
+ name = constraint;
29
+ return this;
30
+ },
31
+ build() {
32
+ if (!references)
33
+ return undefined;
34
+ return { name, columns, references, onDelete, onUpdate };
35
+ },
36
+ };
59
37
  }
60
- /**
61
- * Builder for table definitions with a fluent API.
62
- */
63
- export class TableDefinitionBuilder {
64
- _name;
65
- _columnBuilders = [];
66
- _primaryKey;
67
- _indexes = [];
68
- _foreignKeyBuilders = [];
69
- _comment;
70
- constructor(name) {
71
- this._name = name;
72
- }
73
- /** Big, matching an entity's `@Id`: a key is spelled from this type, so it has to state the real one. */
74
- id(name = 'id', options = {}) {
75
- return this.add(name, { category: 'integer', size: 'big' }, { ...options, primaryKey: true, autoIncrement: true });
76
- }
77
- integer(name, options) {
78
- return this.add(name, { category: 'integer' }, options);
79
- }
80
- smallint(name, options) {
81
- return this.add(name, { category: 'integer', size: 'small' }, options);
82
- }
83
- bigint(name, options) {
84
- return this.add(name, { category: 'integer', size: 'big' }, options);
85
- }
86
- float(name, options) {
87
- return this.add(name, { category: 'float' }, options);
88
- }
89
- double(name, options) {
90
- return this.add(name, { category: 'float', size: 'big' }, options);
91
- }
92
- decimal(name, options = {}) {
93
- const { precision, scale, ...rest } = options;
94
- return this.add(name, { category: 'decimal', precision, scale }, rest);
95
- }
96
- string(name, options = {}) {
97
- const { length = 255, ...rest } = options;
98
- return this.add(name, { category: 'string', length }, rest);
99
- }
100
- char(name, options = {}) {
101
- const { length = 1, ...rest } = options;
102
- return this.add(name, { category: 'string', length }, rest);
103
- }
104
- text(name, options) {
105
- return this.add(name, { category: 'string' }, options);
106
- }
107
- boolean(name, options) {
108
- return this.add(name, { category: 'boolean' }, options);
109
- }
110
- date(name, options) {
111
- return this.add(name, { category: 'date' }, options);
112
- }
113
- time(name, options) {
114
- return this.add(name, { category: 'time' }, options);
115
- }
116
- timestamp(name, options) {
117
- return this.add(name, { category: 'timestamp', precision: DATE_PRECISION }, options);
118
- }
119
- timestamptz(name, options) {
120
- return this.add(name, { category: 'timestamp', withTimezone: true, precision: DATE_PRECISION }, options);
121
- }
122
- json(name, options) {
123
- return this.add(name, { category: 'json' }, options);
124
- }
125
- /** One canonical json category; the dialect decides between `JSON` and `JSONB`. */
126
- jsonb(name, options) {
127
- return this.add(name, { category: 'json' }, options);
128
- }
129
- uuid(name, options) {
130
- return this.add(name, { category: 'uuid' }, options);
131
- }
132
- blob(name, options) {
133
- return this.add(name, { category: 'blob' }, options);
134
- }
135
- vector(name, options = {}) {
136
- const { dimensions, ...rest } = options;
137
- return this.add(name, { category: 'vector', length: dimensions }, rest);
138
- }
139
- add(name, type, options = {}) {
140
- const column = new ColumnDefinitionBuilder(name, type, options);
141
- this._columnBuilders.push(column);
38
+ /** A table as `createTable`'s callback declares it: its columns in `f`'s vocabulary, then what spans several. */
39
+ export function tableBuilder(name) {
40
+ const columns = [];
41
+ const indexes = [];
42
+ const foreignKeyBuilders = [];
43
+ let primaryKey;
44
+ let comment;
45
+ const factory = tableColumns((column) => {
46
+ columns.push(column);
142
47
  return column;
143
- }
144
- createdAt() {
145
- return this.timestampNow('createdAt');
146
- }
147
- updatedAt() {
148
- return this.timestampNow('updatedAt');
149
- }
150
- timestampNow(name) {
151
- return this.timestamptz(name, { defaultValue: currentTimestamp });
152
- }
153
- timestamps() {
154
- this.createdAt();
155
- this.updatedAt();
156
- }
157
- primaryKey(columns) {
158
- this._primaryKey = columns;
159
- return this;
160
- }
161
- unique(columns, options) {
162
- this._indexes.push(indexDefinition(columns, { ...namedOptions(options), unique: true }, true));
163
- return this;
164
- }
165
- index(columns, options) {
166
- this._indexes.push(indexDefinition(columns, namedOptions(options)));
167
- return this;
168
- }
169
- foreignKey(columns) {
170
- const fk = new TableForeignKeyDefinitionBuilder(columns);
171
- this._foreignKeyBuilders.push(fk);
172
- return fk;
173
- }
174
- comment(text) {
175
- this._comment = text;
176
- return this;
177
- }
178
- /**
179
- * Build the table definition.
180
- */
181
- build() {
182
- // Build all columns from builders
183
- const columns = this._columnBuilders.map((cb) => cb.build());
184
- // Collect column-level indexes, skipping one a table-level index already names.
185
- const taken = new Set(this._indexes
186
- .filter((idx) => idx.where === undefined)
187
- .map((idx) => declaredIndexName(idx.name, this._name, idx.entries, { unique: idx.uniqueName })));
188
- for (const col of columns) {
189
- const index = columnIndex(this._name, col);
190
- if (index && !taken.has(index.name)) {
191
- this._indexes.push(index);
48
+ });
49
+ const timestampNow = (column) => factory.timestamptz(column).default(currentTimestamp);
50
+ return {
51
+ ...factory,
52
+ createdAt: () => timestampNow('createdAt'),
53
+ updatedAt: () => timestampNow('updatedAt'),
54
+ timestamps() {
55
+ timestampNow('createdAt');
56
+ timestampNow('updatedAt');
57
+ },
58
+ primaryKey(keyColumns) {
59
+ primaryKey = keyColumns;
60
+ return this;
61
+ },
62
+ unique(entries, options) {
63
+ indexes.push(indexDefinition(entries, { ...namedOptions(options), unique: true }, true));
64
+ return this;
65
+ },
66
+ index(entries, options) {
67
+ indexes.push(indexDefinition(entries, namedOptions(options)));
68
+ return this;
69
+ },
70
+ foreignKey(keyColumns) {
71
+ const foreignKey = foreignKeyDefinition(keyColumns);
72
+ foreignKeyBuilders.push(foreignKey);
73
+ return foreignKey;
74
+ },
75
+ comment(text) {
76
+ comment = text;
77
+ return this;
78
+ },
79
+ build() {
80
+ const built = columns.map((column) => column.build());
81
+ // Column-level indexes, skipping one a table-level index already names.
82
+ const taken = new Set(indexes
83
+ .filter((index) => index.where === undefined)
84
+ .map((index) => declaredIndexName(index.name, name, index.entries, { unique: index.uniqueName })));
85
+ const columnIndexes = built.flatMap((column) => {
86
+ const index = columnIndex(name, column);
87
+ if (!index || taken.has(index.name))
88
+ return [];
192
89
  taken.add(index.name);
193
- }
194
- }
195
- // Build foreign keys
196
- const foreignKeys = this._foreignKeyBuilders
197
- .map((fk) => fk.build())
198
- .filter((fk) => fk !== undefined);
199
- // Collect column-level foreign keys
200
- for (const col of columns) {
201
- const foreignKey = columnForeignKey(col);
202
- if (foreignKey) {
203
- foreignKeys.push(foreignKey);
204
- }
205
- }
206
- return {
207
- name: this._name,
208
- columns,
209
- primaryKey: this._primaryKey,
210
- indexes: this._indexes,
211
- foreignKeys,
212
- comment: this._comment,
213
- };
214
- }
90
+ return [index];
91
+ });
92
+ const foreignKeys = [
93
+ ...foreignKeyBuilders.map((foreignKey) => foreignKey.build()),
94
+ ...built.map(columnForeignKey),
95
+ ].filter((foreignKey) => foreignKey !== undefined);
96
+ return { name, columns: built, primaryKey, indexes: [...indexes, ...columnIndexes], foreignKeys, comment };
97
+ },
98
+ };
215
99
  }