@remix-run/data-table 0.2.1 → 0.3.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 (66) hide show
  1. package/README.md +76 -74
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/lib/adapter.d.ts +10 -271
  5. package/dist/lib/adapter.d.ts.map +1 -1
  6. package/dist/lib/column.d.ts.map +1 -1
  7. package/dist/lib/column.js +10 -1
  8. package/dist/lib/migrations/directive.d.ts +12 -0
  9. package/dist/lib/migrations/directive.d.ts.map +1 -0
  10. package/dist/lib/migrations/directive.js +28 -0
  11. package/dist/lib/migrations/directory-name.d.ts +12 -0
  12. package/dist/lib/migrations/directory-name.d.ts.map +1 -0
  13. package/dist/lib/migrations/directory-name.js +18 -0
  14. package/dist/lib/migrations/journal-store.d.ts +1 -1
  15. package/dist/lib/migrations/journal-store.d.ts.map +1 -1
  16. package/dist/lib/migrations/journal-store.js +18 -18
  17. package/dist/lib/migrations/registry.d.ts +1 -1
  18. package/dist/lib/migrations/registry.js +1 -1
  19. package/dist/lib/migrations/runner.d.ts +2 -2
  20. package/dist/lib/migrations/runner.d.ts.map +1 -1
  21. package/dist/lib/migrations/runner.js +44 -71
  22. package/dist/lib/migrations-node.d.ts +7 -4
  23. package/dist/lib/migrations-node.d.ts.map +1 -1
  24. package/dist/lib/migrations-node.js +52 -41
  25. package/dist/lib/migrations.d.ts +19 -200
  26. package/dist/lib/migrations.d.ts.map +1 -1
  27. package/dist/lib/migrations.js +1 -38
  28. package/dist/lib/query.d.ts +33 -0
  29. package/dist/lib/query.d.ts.map +1 -1
  30. package/dist/lib/query.js +28 -0
  31. package/dist/lib/sql-helpers.d.ts +1 -7
  32. package/dist/lib/sql-helpers.d.ts.map +1 -1
  33. package/dist/lib/sql-helpers.js +0 -16
  34. package/dist/migrations.d.ts +2 -5
  35. package/dist/migrations.d.ts.map +1 -1
  36. package/dist/migrations.js +1 -3
  37. package/dist/sql-helpers.d.ts +1 -1
  38. package/dist/sql-helpers.d.ts.map +1 -1
  39. package/dist/sql-helpers.js +1 -1
  40. package/package.json +2 -2
  41. package/src/index.ts +1 -34
  42. package/src/lib/adapter.ts +10 -330
  43. package/src/lib/column.ts +14 -2
  44. package/src/lib/migrations/directive.ts +38 -0
  45. package/src/lib/migrations/directory-name.ts +23 -0
  46. package/src/lib/migrations/journal-store.ts +22 -18
  47. package/src/lib/migrations/registry.ts +1 -1
  48. package/src/lib/migrations/runner.ts +51 -85
  49. package/src/lib/migrations-node.ts +58 -38
  50. package/src/lib/migrations.ts +19 -224
  51. package/src/lib/query.ts +33 -0
  52. package/src/lib/sql-helpers.ts +1 -22
  53. package/src/migrations.ts +3 -13
  54. package/src/sql-helpers.ts +0 -1
  55. package/dist/lib/migrations/filename.d.ts +0 -12
  56. package/dist/lib/migrations/filename.d.ts.map +0 -1
  57. package/dist/lib/migrations/filename.js +0 -20
  58. package/dist/lib/migrations/helpers.d.ts +0 -11
  59. package/dist/lib/migrations/helpers.d.ts.map +0 -1
  60. package/dist/lib/migrations/helpers.js +0 -77
  61. package/dist/lib/migrations/schema-api.d.ts +0 -7
  62. package/dist/lib/migrations/schema-api.d.ts.map +0 -1
  63. package/dist/lib/migrations/schema-api.js +0 -326
  64. package/src/lib/migrations/filename.ts +0 -25
  65. package/src/lib/migrations/helpers.ts +0 -108
  66. package/src/lib/migrations/schema-api.ts +0 -417
package/src/lib/query.ts CHANGED
@@ -143,6 +143,11 @@ type QueryResultMap<row extends Record<string, unknown>, loaded extends Record<s
143
143
  upsert: WriteResult | WriteRowResult<row>
144
144
  }
145
145
 
146
+ /**
147
+ * Convenience alias for any {@link Query} regardless of its source, columns,
148
+ * row shape, loaded relations, or execution phase. Use this in helper APIs
149
+ * that accept a query but don't care about the specific generic parameters.
150
+ */
146
151
  export type AnyQuery = Query<any, any, any, any, any>
147
152
 
148
153
  type QuerySource<input extends AnyQuery> =
@@ -212,6 +217,17 @@ export const querySnapshot = Symbol('querySnapshot')
212
217
 
213
218
  declare const queryTypeBrand: unique symbol
214
219
 
220
+ /**
221
+ * Type-safe query builder for `@remix-run/data-table` sources. Construct via
222
+ * {@link query} and chain calls (`select`, `where`, `orderBy`, etc.) to build
223
+ * up a plan; run it by `await`-ing on a runtime-bound query, or by passing an
224
+ * unbound one to a runtime.
225
+ *
226
+ * The five generic parameters track, in order: the source/table, the column
227
+ * type map, the projected row shape, any loaded relations, and the
228
+ * binding/execution-mode phase. Most consumers do not need to spell them out
229
+ * — `query(table)` infers everything.
230
+ */
215
231
  export class Query<
216
232
  source extends AnyQuerySource,
217
233
  columnTypes extends Record<string, unknown> = QuerySourceColumnTypes<source>,
@@ -684,6 +700,23 @@ export class Query<
684
700
  }
685
701
  }
686
702
 
703
+ /**
704
+ * Begin a {@link Query} against a `@remix-run/data-table` source. The returned
705
+ * builder is in `'all'` execution mode and unbound; chain `select`, `where`,
706
+ * `orderBy`, etc. to refine the plan, and `await` it after binding it to a
707
+ * runtime to materialize results.
708
+ *
709
+ * @param table The table or source to query.
710
+ * @returns An unbound {@link Query} builder rooted at `table`.
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * let activeUsers = await query(users)
715
+ * .where({ status: 'active' })
716
+ * .orderBy('createdAt', 'desc')
717
+ * .select(['id', 'email'])
718
+ * ```
719
+ */
687
720
  export function query<
688
721
  tableName extends string,
689
722
  row extends Record<string, unknown>,
@@ -1,31 +1,10 @@
1
- import type { DataManipulationOperation, DataMigrationOperation, TableRef } from './adapter.ts'
1
+ import type { TableRef } from './adapter.ts'
2
2
 
3
3
  /**
4
4
  * Function used to quote SQL identifiers for a dialect.
5
5
  */
6
6
  export type QuoteIdentifier = (value: string) => string
7
7
 
8
- /**
9
- * Type guard that narrows an operation to the data-manipulation union.
10
- * @param operation Operation to inspect.
11
- * @returns `true` when the operation is a data-manipulation operation.
12
- */
13
- export function isDataManipulationOperation(
14
- operation: DataManipulationOperation | DataMigrationOperation,
15
- ): operation is DataManipulationOperation {
16
- return (
17
- operation.kind === 'select' ||
18
- operation.kind === 'count' ||
19
- operation.kind === 'exists' ||
20
- operation.kind === 'insert' ||
21
- operation.kind === 'insertMany' ||
22
- operation.kind === 'update' ||
23
- operation.kind === 'delete' ||
24
- operation.kind === 'upsert' ||
25
- operation.kind === 'raw'
26
- )
27
- }
28
-
29
8
  /**
30
9
  * Normalizes an arbitrary join type string into `inner`, `left`, or `right`.
31
10
  * @param type Input join type.
package/src/migrations.ts CHANGED
@@ -1,26 +1,16 @@
1
1
  export type {
2
- AlterTableBuilder,
3
- CreateMigrationInput,
4
- Migration,
5
- MigrationContext,
2
+ MigrateOptions,
3
+ MigrateResult,
6
4
  MigrationDescriptor,
7
5
  MigrationDirection,
8
6
  MigrationJournalRow,
9
- MigrationSchema,
10
7
  MigrationRegistry,
11
8
  MigrationRunner,
12
9
  MigrationRunnerOptions,
13
10
  MigrationStatus,
14
11
  MigrationStatusEntry,
15
12
  MigrationTransactionMode,
16
- MigrateOptions,
17
- MigrateResult,
18
- KeyColumns,
19
- TableInput,
20
13
  } from './lib/migrations.ts'
21
- export { createMigration } from './lib/migrations.ts'
22
- export type { ColumnNamespace } from './lib/column.ts'
23
- export { ColumnBuilder, column } from './lib/column.ts'
24
14
  export { createMigrationRegistry } from './lib/migrations/registry.ts'
25
15
  export { createMigrationRunner } from './lib/migrations/runner.ts'
26
- export { parseMigrationFilename } from './lib/migrations/filename.ts'
16
+ export { parseMigrationDirectoryName } from './lib/migrations/directory-name.ts'
@@ -1,7 +1,6 @@
1
1
  export type { QuoteIdentifier } from './lib/sql-helpers.ts'
2
2
  export {
3
3
  collectColumns,
4
- isDataManipulationOperation,
5
4
  normalizeJoinType,
6
5
  quoteLiteral,
7
6
  quotePath,
@@ -1,12 +0,0 @@
1
- /**
2
- * Parses a migration filename into `{ id, name }`.
3
- *
4
- * Expected format: `YYYYMMDDHHmmss_name.(ts|js|mts|mjs|cts|cjs)`.
5
- * @param filename Migration file basename.
6
- * @returns Parsed migration id and name.
7
- */
8
- export declare function parseMigrationFilename(filename: string): {
9
- id: string;
10
- name: string;
11
- };
12
- //# sourceMappingURL=filename.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"filename.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/filename.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAerF"}
@@ -1,20 +0,0 @@
1
- const migrationFilenamePattern = /^(\d{14})_(.+)\.(?:m?ts|m?js|cts|cjs)$/;
2
- /**
3
- * Parses a migration filename into `{ id, name }`.
4
- *
5
- * Expected format: `YYYYMMDDHHmmss_name.(ts|js|mts|mjs|cts|cjs)`.
6
- * @param filename Migration file basename.
7
- * @returns Parsed migration id and name.
8
- */
9
- export function parseMigrationFilename(filename) {
10
- let match = filename.match(migrationFilenamePattern);
11
- if (!match) {
12
- throw new Error('Invalid migration filename "' +
13
- filename +
14
- '". Expected format YYYYMMDDHHmmss_name.ts (or .js/.mts/.mjs/.cts/.cjs)');
15
- }
16
- return {
17
- id: match[1],
18
- name: match[2],
19
- };
20
- }
@@ -1,11 +0,0 @@
1
- import type { TableRef } from '../adapter.ts';
2
- import type { IndexColumns, KeyColumns } from '../migrations.ts';
3
- export declare function toTableRef(name: string): TableRef;
4
- export declare function normalizeIndexColumns(columns: IndexColumns): string[];
5
- export declare function normalizeKeyColumns(columns: KeyColumns): string[];
6
- export declare function createPrimaryKeyName(table: TableRef): string;
7
- export declare function createUniqueName(table: TableRef, columns: string[]): string;
8
- export declare function createForeignKeyName(table: TableRef, columns: string[], references: TableRef, referenceColumns: string[]): string;
9
- export declare function createCheckName(table: TableRef, expression: string): string;
10
- export declare function createIndexName(table: TableRef, columns: string[]): string;
11
- //# sourceMappingURL=helpers.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAEhE,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAWjD;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,GAAG,MAAM,EAAE,CAErE;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,EAAE,CAMjE;AAgDD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CAE5D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAE3E;AAED,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,QAAQ,EACf,OAAO,EAAE,MAAM,EAAE,EACjB,UAAU,EAAE,QAAQ,EACpB,gBAAgB,EAAE,MAAM,EAAE,GACzB,MAAM,CAWR;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3E;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,CAE1E"}
@@ -1,77 +0,0 @@
1
- export function toTableRef(name) {
2
- let segments = name.split('.');
3
- if (segments.length === 1) {
4
- return { name };
5
- }
6
- return {
7
- schema: segments[0],
8
- name: segments.slice(1).join('.'),
9
- };
10
- }
11
- export function normalizeIndexColumns(columns) {
12
- return normalizeKeyColumns(columns);
13
- }
14
- export function normalizeKeyColumns(columns) {
15
- if (Array.isArray(columns)) {
16
- return [...columns];
17
- }
18
- return [columns];
19
- }
20
- function normalizeNamePart(value) {
21
- let normalized = value
22
- .toLowerCase()
23
- .replace(/[^a-z0-9]+/g, '_')
24
- .replace(/^_+|_+$/g, '');
25
- if (normalized.length === 0) {
26
- return 'item';
27
- }
28
- return normalized;
29
- }
30
- function tableNamePart(table) {
31
- if (table.schema) {
32
- return normalizeNamePart(table.schema + '_' + table.name);
33
- }
34
- return normalizeNamePart(table.name);
35
- }
36
- function hashString(value) {
37
- let hash = 5381;
38
- for (let index = 0; index < value.length; index++) {
39
- hash = ((hash << 5) + hash) ^ value.charCodeAt(index);
40
- }
41
- return hash >>> 0;
42
- }
43
- function withNameLimit(name) {
44
- let limit = 63;
45
- if (name.length <= limit) {
46
- return name;
47
- }
48
- let suffix = hashString(name).toString(36).padStart(8, '0').slice(0, 8);
49
- return name.slice(0, limit - 9) + '_' + suffix;
50
- }
51
- function columnsNamePart(columns) {
52
- return columns.map((column) => normalizeNamePart(column)).join('_');
53
- }
54
- export function createPrimaryKeyName(table) {
55
- return withNameLimit(tableNamePart(table) + '_pk');
56
- }
57
- export function createUniqueName(table, columns) {
58
- return withNameLimit(tableNamePart(table) + '_' + columnsNamePart(columns) + '_uq');
59
- }
60
- export function createForeignKeyName(table, columns, references, referenceColumns) {
61
- let base = tableNamePart(table) +
62
- '_' +
63
- columnsNamePart(columns) +
64
- '_' +
65
- tableNamePart(references) +
66
- '_' +
67
- columnsNamePart(referenceColumns) +
68
- '_fk';
69
- return withNameLimit(base);
70
- }
71
- export function createCheckName(table, expression) {
72
- let suffix = hashString(expression).toString(36);
73
- return withNameLimit(tableNamePart(table) + '_chk_' + suffix);
74
- }
75
- export function createIndexName(table, columns) {
76
- return withNameLimit(tableNamePart(table) + '_' + columnsNamePart(columns) + '_idx');
77
- }
@@ -1,7 +0,0 @@
1
- import type { Database } from '../database.ts';
2
- import type { DataMigrationOperation, TransactionToken } from '../adapter.ts';
3
- import type { MigrationSchema } from '../migrations.ts';
4
- export declare function createMigrationSchema(db: Database, emit: (operation: DataMigrationOperation) => Promise<void>, options?: {
5
- transaction?: TransactionToken;
6
- }): MigrationSchema;
7
- //# sourceMappingURL=schema-api.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema-api.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/schema-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAC9C,OAAO,KAAK,EAKV,sBAAsB,EAItB,gBAAgB,EAEjB,MAAM,eAAe,CAAA;AAItB,OAAO,KAAK,EAKV,eAAe,EAGhB,MAAM,kBAAkB,CAAA;AA+PzB,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,QAAQ,EACZ,IAAI,EAAE,CAAC,SAAS,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,EAC1D,OAAO,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,gBAAgB,CAAA;CAAE,GAC3C,eAAe,CAqIjB"}
@@ -1,326 +0,0 @@
1
- import { rawSql } from "../sql.js";
2
- import { getTableColumnDefinitions, getTableName, getTablePrimaryKey } from "../table.js";
3
- import { ColumnBuilder } from "../column.js";
4
- import { createCheckName, createForeignKeyName, createIndexName, createPrimaryKeyName, createUniqueName, normalizeIndexColumns, normalizeKeyColumns, toTableRef, } from "./helpers.js";
5
- function asColumnDefinition(definition) {
6
- if (definition instanceof ColumnBuilder) {
7
- return definition.build();
8
- }
9
- return definition;
10
- }
11
- function asTableRef(value) {
12
- if (typeof value === 'string') {
13
- return toTableRef(value);
14
- }
15
- return toTableRef(getTableName(value));
16
- }
17
- function lowerTableForCreate(table) {
18
- let tableRef = toTableRef(getTableName(table));
19
- let sourceColumnDefinitions = getTableColumnDefinitions(table);
20
- let columns = {};
21
- let uniques = [];
22
- let checks = [];
23
- let foreignKeys = [];
24
- for (let columnName in sourceColumnDefinitions) {
25
- if (!Object.prototype.hasOwnProperty.call(sourceColumnDefinitions, columnName)) {
26
- continue;
27
- }
28
- let sourceDefinition = sourceColumnDefinitions[columnName];
29
- let columnDefinition = {
30
- ...sourceDefinition,
31
- checks: undefined,
32
- references: undefined,
33
- primaryKey: undefined,
34
- };
35
- let unique = sourceDefinition.unique;
36
- if (unique) {
37
- let uniqueName = typeof unique === 'object' && unique.name
38
- ? unique.name
39
- : createUniqueName(tableRef, [columnName]);
40
- uniques.push({
41
- name: uniqueName,
42
- columns: [columnName],
43
- });
44
- columnDefinition.unique = undefined;
45
- }
46
- if (sourceDefinition.checks) {
47
- for (let check of sourceDefinition.checks) {
48
- checks.push({
49
- name: check.name || createCheckName(tableRef, check.expression),
50
- expression: check.expression,
51
- });
52
- }
53
- }
54
- if (sourceDefinition.references) {
55
- let referenceColumns = [...sourceDefinition.references.columns];
56
- let referencesTable = { ...sourceDefinition.references.table };
57
- foreignKeys.push({
58
- name: sourceDefinition.references.name ||
59
- createForeignKeyName(tableRef, [columnName], referencesTable, referenceColumns),
60
- columns: [columnName],
61
- references: {
62
- table: referencesTable,
63
- columns: referenceColumns,
64
- },
65
- onDelete: sourceDefinition.references.onDelete,
66
- onUpdate: sourceDefinition.references.onUpdate,
67
- });
68
- }
69
- columns[columnName] = columnDefinition;
70
- }
71
- let primaryKeyColumns = [...getTablePrimaryKey(table)];
72
- let primaryKey;
73
- if (primaryKeyColumns.length > 0) {
74
- primaryKey = {
75
- columns: primaryKeyColumns,
76
- name: createPrimaryKeyName(tableRef),
77
- };
78
- }
79
- return {
80
- kind: 'createTable',
81
- table: tableRef,
82
- columns,
83
- primaryKey,
84
- uniques: uniques.length > 0 ? uniques : undefined,
85
- checks: checks.length > 0 ? checks : undefined,
86
- foreignKeys: foreignKeys.length > 0 ? foreignKeys : undefined,
87
- };
88
- }
89
- class AlterTableBuilderRuntime {
90
- alterChanges = [];
91
- extraStatements = [];
92
- table;
93
- constructor(table) {
94
- this.table = table;
95
- }
96
- addColumn(name, definition) {
97
- this.alterChanges.push({
98
- kind: 'addColumn',
99
- column: name,
100
- definition: asColumnDefinition(definition),
101
- });
102
- }
103
- changeColumn(name, definition) {
104
- this.alterChanges.push({
105
- kind: 'changeColumn',
106
- column: name,
107
- definition: asColumnDefinition(definition),
108
- });
109
- }
110
- renameColumn(from, to) {
111
- this.alterChanges.push({ kind: 'renameColumn', from, to });
112
- }
113
- dropColumn(name, options) {
114
- this.alterChanges.push({ kind: 'dropColumn', column: name, ifExists: options?.ifExists });
115
- }
116
- addPrimaryKey(columns, options) {
117
- let normalizedColumns = normalizeKeyColumns(columns);
118
- this.alterChanges.push({
119
- kind: 'addPrimaryKey',
120
- constraint: {
121
- columns: normalizedColumns,
122
- name: options?.name ?? createPrimaryKeyName(this.table),
123
- },
124
- });
125
- }
126
- dropPrimaryKey(name) {
127
- this.alterChanges.push({ kind: 'dropPrimaryKey', name });
128
- }
129
- addUnique(columns, options) {
130
- let normalizedColumns = normalizeKeyColumns(columns);
131
- this.alterChanges.push({
132
- kind: 'addUnique',
133
- constraint: {
134
- columns: normalizedColumns,
135
- name: options?.name ?? createUniqueName(this.table, normalizedColumns),
136
- },
137
- });
138
- }
139
- dropUnique(name) {
140
- this.alterChanges.push({ kind: 'dropUnique', name });
141
- }
142
- addForeignKey(columns, refTable, refColumns, options) {
143
- let normalizedColumns = normalizeKeyColumns(columns);
144
- let normalizedReferenceColumns = refColumns ? normalizeKeyColumns(refColumns) : ['id'];
145
- let referenceTable = asTableRef(refTable);
146
- this.alterChanges.push({
147
- kind: 'addForeignKey',
148
- constraint: {
149
- columns: normalizedColumns,
150
- references: {
151
- table: referenceTable,
152
- columns: normalizedReferenceColumns,
153
- },
154
- name: options?.name ??
155
- createForeignKeyName(this.table, normalizedColumns, referenceTable, normalizedReferenceColumns),
156
- onDelete: options?.onDelete,
157
- onUpdate: options?.onUpdate,
158
- },
159
- });
160
- }
161
- dropForeignKey(name) {
162
- this.alterChanges.push({ kind: 'dropForeignKey', name });
163
- }
164
- addCheck(expression, options) {
165
- this.alterChanges.push({
166
- kind: 'addCheck',
167
- constraint: {
168
- expression,
169
- name: options?.name ?? createCheckName(this.table, expression),
170
- },
171
- });
172
- }
173
- dropCheck(name) {
174
- this.alterChanges.push({ kind: 'dropCheck', name });
175
- }
176
- addIndex(columns, options) {
177
- let normalizedColumns = normalizeIndexColumns(columns);
178
- let { name, ifNotExists, ...indexOptions } = options ?? {};
179
- this.extraStatements.push({
180
- kind: 'createIndex',
181
- index: {
182
- table: this.table,
183
- name: name ?? createIndexName(this.table, normalizedColumns),
184
- columns: normalizedColumns,
185
- ...indexOptions,
186
- },
187
- ifNotExists,
188
- });
189
- }
190
- dropIndex(name) {
191
- this.extraStatements.push({
192
- kind: 'dropIndex',
193
- table: this.table,
194
- name,
195
- });
196
- }
197
- comment(text) {
198
- this.alterChanges.push({ kind: 'setTableComment', comment: text });
199
- }
200
- }
201
- export function createMigrationSchema(db, emit, options) {
202
- return {
203
- async createTable(table, options) {
204
- let operation = lowerTableForCreate(table);
205
- operation.ifNotExists = options?.ifNotExists;
206
- await emit(operation);
207
- },
208
- async alterTable(input, migrate, options) {
209
- let tableRef = asTableRef(input);
210
- let builder = new AlterTableBuilderRuntime(tableRef);
211
- migrate(builder);
212
- if (builder.alterChanges.length > 0) {
213
- await emit({
214
- kind: 'alterTable',
215
- table: tableRef,
216
- changes: builder.alterChanges,
217
- ifExists: options?.ifExists,
218
- });
219
- }
220
- for (let operation of builder.extraStatements) {
221
- await emit(operation);
222
- }
223
- },
224
- async renameTable(from, to) {
225
- await emit({ kind: 'renameTable', from: asTableRef(from), to: toTableRef(to) });
226
- },
227
- async dropTable(table, options) {
228
- await emit({
229
- kind: 'dropTable',
230
- table: asTableRef(table),
231
- ifExists: options?.ifExists,
232
- cascade: options?.cascade,
233
- });
234
- },
235
- async createIndex(table, columns, options) {
236
- let tableRef = asTableRef(table);
237
- let normalizedColumns = normalizeIndexColumns(columns);
238
- let { name, ifNotExists, ...indexOptions } = options ?? {};
239
- await emit({
240
- kind: 'createIndex',
241
- index: {
242
- table: tableRef,
243
- name: name ?? createIndexName(tableRef, normalizedColumns),
244
- columns: normalizedColumns,
245
- ...indexOptions,
246
- },
247
- ifNotExists,
248
- });
249
- },
250
- async dropIndex(table, name, options) {
251
- await emit({
252
- kind: 'dropIndex',
253
- table: asTableRef(table),
254
- name,
255
- ifExists: options?.ifExists,
256
- });
257
- },
258
- async renameIndex(table, from, to) {
259
- await emit({
260
- kind: 'renameIndex',
261
- table: asTableRef(table),
262
- from,
263
- to,
264
- });
265
- },
266
- async addForeignKey(table, columns, refTable, refColumns, options) {
267
- let tableRef = asTableRef(table);
268
- let normalizedColumns = normalizeKeyColumns(columns);
269
- let referenceTable = asTableRef(refTable);
270
- let normalizedReferenceColumns = refColumns ? normalizeKeyColumns(refColumns) : ['id'];
271
- await emit({
272
- kind: 'addForeignKey',
273
- table: tableRef,
274
- constraint: {
275
- columns: normalizedColumns,
276
- references: {
277
- table: referenceTable,
278
- columns: normalizedReferenceColumns,
279
- },
280
- name: options?.name ??
281
- createForeignKeyName(tableRef, normalizedColumns, referenceTable, normalizedReferenceColumns),
282
- onDelete: options?.onDelete,
283
- onUpdate: options?.onUpdate,
284
- },
285
- });
286
- },
287
- async dropForeignKey(table, name) {
288
- await emit({
289
- kind: 'dropForeignKey',
290
- table: asTableRef(table),
291
- name,
292
- });
293
- },
294
- async addCheck(table, expression, options) {
295
- let tableRef = asTableRef(table);
296
- await emit({
297
- kind: 'addCheck',
298
- table: tableRef,
299
- constraint: {
300
- expression,
301
- name: options?.name ?? createCheckName(tableRef, expression),
302
- },
303
- });
304
- },
305
- async dropCheck(table, name) {
306
- await emit({
307
- kind: 'dropCheck',
308
- table: asTableRef(table),
309
- name,
310
- });
311
- },
312
- async plan(sql) {
313
- let statement = typeof sql === 'string' ? rawSql(sql) : sql;
314
- await emit({
315
- kind: 'raw',
316
- sql: statement,
317
- });
318
- },
319
- async hasTable(table) {
320
- return db.adapter.hasTable(asTableRef(table), options?.transaction);
321
- },
322
- async hasColumn(table, columnName) {
323
- return db.adapter.hasColumn(asTableRef(table), columnName, options?.transaction);
324
- },
325
- };
326
- }
@@ -1,25 +0,0 @@
1
- const migrationFilenamePattern = /^(\d{14})_(.+)\.(?:m?ts|m?js|cts|cjs)$/
2
-
3
- /**
4
- * Parses a migration filename into `{ id, name }`.
5
- *
6
- * Expected format: `YYYYMMDDHHmmss_name.(ts|js|mts|mjs|cts|cjs)`.
7
- * @param filename Migration file basename.
8
- * @returns Parsed migration id and name.
9
- */
10
- export function parseMigrationFilename(filename: string): { id: string; name: string } {
11
- let match = filename.match(migrationFilenamePattern)
12
-
13
- if (!match) {
14
- throw new Error(
15
- 'Invalid migration filename "' +
16
- filename +
17
- '". Expected format YYYYMMDDHHmmss_name.ts (or .js/.mts/.mjs/.cts/.cjs)',
18
- )
19
- }
20
-
21
- return {
22
- id: match[1],
23
- name: match[2],
24
- }
25
- }