@remix-run/data-table 0.1.0 → 0.2.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 (111) hide show
  1. package/README.md +306 -55
  2. package/dist/index.d.ts +9 -5
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +4 -2
  5. package/dist/lib/adapter.d.ts +386 -16
  6. package/dist/lib/adapter.d.ts.map +1 -1
  7. package/dist/lib/column.d.ts +193 -0
  8. package/dist/lib/column.d.ts.map +1 -0
  9. package/dist/lib/column.js +302 -0
  10. package/dist/lib/database/execution-context.d.ts +10 -0
  11. package/dist/lib/database/execution-context.d.ts.map +1 -0
  12. package/dist/lib/database/execution-context.js +1 -0
  13. package/dist/lib/database/helpers.d.ts +26 -0
  14. package/dist/lib/database/helpers.d.ts.map +1 -0
  15. package/dist/lib/database/helpers.js +116 -0
  16. package/dist/lib/database/query-execution.d.ts +7 -0
  17. package/dist/lib/database/query-execution.d.ts.map +1 -0
  18. package/dist/lib/database/query-execution.js +401 -0
  19. package/dist/lib/database/relations.d.ts +4 -0
  20. package/dist/lib/database/relations.d.ts.map +1 -0
  21. package/dist/lib/database/relations.js +207 -0
  22. package/dist/lib/database/write-lifecycle.d.ts +13 -0
  23. package/dist/lib/database/write-lifecycle.d.ts.map +1 -0
  24. package/dist/lib/database/write-lifecycle.js +279 -0
  25. package/dist/lib/database.d.ts +141 -238
  26. package/dist/lib/database.d.ts.map +1 -1
  27. package/dist/lib/database.js +73 -1122
  28. package/dist/lib/errors.d.ts +9 -0
  29. package/dist/lib/errors.d.ts.map +1 -1
  30. package/dist/lib/errors.js +9 -0
  31. package/dist/lib/migrations/filename.d.ts +12 -0
  32. package/dist/lib/migrations/filename.d.ts.map +1 -0
  33. package/dist/lib/migrations/filename.js +20 -0
  34. package/dist/lib/migrations/helpers.d.ts +11 -0
  35. package/dist/lib/migrations/helpers.d.ts.map +1 -0
  36. package/dist/lib/migrations/helpers.js +77 -0
  37. package/dist/lib/migrations/journal-store.d.ts +15 -0
  38. package/dist/lib/migrations/journal-store.d.ts.map +1 -0
  39. package/dist/lib/migrations/journal-store.js +83 -0
  40. package/dist/lib/migrations/registry.d.ts +27 -0
  41. package/dist/lib/migrations/registry.d.ts.map +1 -0
  42. package/dist/lib/migrations/registry.js +51 -0
  43. package/dist/lib/migrations/runner.d.ts +20 -0
  44. package/dist/lib/migrations/runner.d.ts.map +1 -0
  45. package/dist/lib/migrations/runner.js +273 -0
  46. package/dist/lib/migrations/schema-api.d.ts +7 -0
  47. package/dist/lib/migrations/schema-api.d.ts.map +1 -0
  48. package/dist/lib/migrations/schema-api.js +326 -0
  49. package/dist/lib/migrations-node.d.ts +17 -0
  50. package/dist/lib/migrations-node.d.ts.map +1 -0
  51. package/dist/lib/migrations-node.js +65 -0
  52. package/dist/lib/migrations.d.ts +292 -0
  53. package/dist/lib/migrations.d.ts.map +1 -0
  54. package/dist/lib/migrations.js +38 -0
  55. package/dist/lib/operators.d.ts +3 -0
  56. package/dist/lib/operators.d.ts.map +1 -1
  57. package/dist/lib/query.d.ts +159 -0
  58. package/dist/lib/query.d.ts.map +1 -0
  59. package/dist/lib/query.js +401 -0
  60. package/dist/lib/references.d.ts +0 -1
  61. package/dist/lib/references.d.ts.map +1 -1
  62. package/dist/lib/sql-helpers.d.ts +50 -0
  63. package/dist/lib/sql-helpers.d.ts.map +1 -0
  64. package/dist/lib/sql-helpers.js +111 -0
  65. package/dist/lib/sql.d.ts +23 -6
  66. package/dist/lib/sql.d.ts.map +1 -1
  67. package/dist/lib/sql.js +19 -5
  68. package/dist/lib/table.d.ts +355 -40
  69. package/dist/lib/table.d.ts.map +1 -1
  70. package/dist/lib/table.js +113 -90
  71. package/dist/migrations/node.d.ts +2 -0
  72. package/dist/migrations/node.d.ts.map +1 -0
  73. package/dist/migrations/node.js +1 -0
  74. package/dist/migrations.d.ts +8 -0
  75. package/dist/migrations.d.ts.map +1 -0
  76. package/dist/migrations.js +5 -0
  77. package/dist/operators.d.ts +3 -0
  78. package/dist/operators.d.ts.map +1 -0
  79. package/dist/operators.js +1 -0
  80. package/dist/sql-helpers.d.ts +3 -0
  81. package/dist/sql-helpers.d.ts.map +1 -0
  82. package/dist/sql-helpers.js +1 -0
  83. package/package.json +23 -8
  84. package/src/index.ts +93 -10
  85. package/src/lib/adapter.ts +469 -25
  86. package/src/lib/column.ts +384 -0
  87. package/src/lib/database/execution-context.ts +15 -0
  88. package/src/lib/database/helpers.ts +216 -0
  89. package/src/lib/database/query-execution.ts +638 -0
  90. package/src/lib/database/relations.ts +332 -0
  91. package/src/lib/database/write-lifecycle.ts +487 -0
  92. package/src/lib/database.ts +246 -1848
  93. package/src/lib/errors.ts +10 -0
  94. package/src/lib/migrations/filename.ts +25 -0
  95. package/src/lib/migrations/helpers.ts +108 -0
  96. package/src/lib/migrations/journal-store.ts +122 -0
  97. package/src/lib/migrations/registry.ts +62 -0
  98. package/src/lib/migrations/runner.ts +374 -0
  99. package/src/lib/migrations/schema-api.ts +417 -0
  100. package/src/lib/migrations-node.ts +71 -0
  101. package/src/lib/migrations.ts +328 -0
  102. package/src/lib/operators.ts +3 -0
  103. package/src/lib/query.ts +958 -0
  104. package/src/lib/references.ts +0 -1
  105. package/src/lib/sql-helpers.ts +146 -0
  106. package/src/lib/sql.ts +23 -6
  107. package/src/lib/table.ts +484 -156
  108. package/src/migrations/node.ts +1 -0
  109. package/src/migrations.ts +26 -0
  110. package/src/operators.ts +18 -0
  111. package/src/sql-helpers.ts +9 -0
package/src/lib/errors.ts CHANGED
@@ -2,7 +2,14 @@
2
2
  * Base error for all `data-table` failures.
3
3
  */
4
4
  export class DataTableError extends Error {
5
+ /**
6
+ * Stable error code identifying the failure category.
7
+ */
5
8
  code: string
9
+
10
+ /**
11
+ * Optional structured metadata attached to the failure.
12
+ */
6
13
  metadata?: Record<string, unknown>
7
14
 
8
15
  constructor(
@@ -24,6 +31,9 @@ export class DataTableError extends Error {
24
31
  * Thrown when input data fails schema validation.
25
32
  */
26
33
  export class DataTableValidationError extends DataTableError {
34
+ /**
35
+ * Validation issues reported by the schema validator.
36
+ */
27
37
  issues: ReadonlyArray<unknown>
28
38
 
29
39
  constructor(
@@ -0,0 +1,25 @@
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
+ }
@@ -0,0 +1,108 @@
1
+ import type { TableRef } from '../adapter.ts'
2
+ import type { IndexColumns, KeyColumns } from '../migrations.ts'
3
+
4
+ export function toTableRef(name: string): TableRef {
5
+ let segments = name.split('.')
6
+
7
+ if (segments.length === 1) {
8
+ return { name }
9
+ }
10
+
11
+ return {
12
+ schema: segments[0],
13
+ name: segments.slice(1).join('.'),
14
+ }
15
+ }
16
+
17
+ export function normalizeIndexColumns(columns: IndexColumns): string[] {
18
+ return normalizeKeyColumns(columns)
19
+ }
20
+
21
+ export function normalizeKeyColumns(columns: KeyColumns): string[] {
22
+ if (Array.isArray(columns)) {
23
+ return [...columns]
24
+ }
25
+
26
+ return [columns]
27
+ }
28
+
29
+ function normalizeNamePart(value: string): string {
30
+ let normalized = value
31
+ .toLowerCase()
32
+ .replace(/[^a-z0-9]+/g, '_')
33
+ .replace(/^_+|_+$/g, '')
34
+
35
+ if (normalized.length === 0) {
36
+ return 'item'
37
+ }
38
+
39
+ return normalized
40
+ }
41
+
42
+ function tableNamePart(table: TableRef): string {
43
+ if (table.schema) {
44
+ return normalizeNamePart(table.schema + '_' + table.name)
45
+ }
46
+
47
+ return normalizeNamePart(table.name)
48
+ }
49
+
50
+ function hashString(value: string): number {
51
+ let hash = 5381
52
+
53
+ for (let index = 0; index < value.length; index++) {
54
+ hash = ((hash << 5) + hash) ^ value.charCodeAt(index)
55
+ }
56
+
57
+ return hash >>> 0
58
+ }
59
+
60
+ function withNameLimit(name: string): string {
61
+ let limit = 63
62
+
63
+ if (name.length <= limit) {
64
+ return name
65
+ }
66
+
67
+ let suffix = hashString(name).toString(36).padStart(8, '0').slice(0, 8)
68
+ return name.slice(0, limit - 9) + '_' + suffix
69
+ }
70
+
71
+ function columnsNamePart(columns: string[]): string {
72
+ return columns.map((column) => normalizeNamePart(column)).join('_')
73
+ }
74
+
75
+ export function createPrimaryKeyName(table: TableRef): string {
76
+ return withNameLimit(tableNamePart(table) + '_pk')
77
+ }
78
+
79
+ export function createUniqueName(table: TableRef, columns: string[]): string {
80
+ return withNameLimit(tableNamePart(table) + '_' + columnsNamePart(columns) + '_uq')
81
+ }
82
+
83
+ export function createForeignKeyName(
84
+ table: TableRef,
85
+ columns: string[],
86
+ references: TableRef,
87
+ referenceColumns: string[],
88
+ ): string {
89
+ let base =
90
+ tableNamePart(table) +
91
+ '_' +
92
+ columnsNamePart(columns) +
93
+ '_' +
94
+ tableNamePart(references) +
95
+ '_' +
96
+ columnsNamePart(referenceColumns) +
97
+ '_fk'
98
+ return withNameLimit(base)
99
+ }
100
+
101
+ export function createCheckName(table: TableRef, expression: string): string {
102
+ let suffix = hashString(expression).toString(36)
103
+ return withNameLimit(tableNamePart(table) + '_chk_' + suffix)
104
+ }
105
+
106
+ export function createIndexName(table: TableRef, columns: string[]): string {
107
+ return withNameLimit(tableNamePart(table) + '_' + columnsNamePart(columns) + '_idx')
108
+ }
@@ -0,0 +1,122 @@
1
+ import type { DatabaseAdapter, TransactionToken } from '../adapter.ts'
2
+ import { rawSql } from '../sql.ts'
3
+ import type { MigrationDescriptor, MigrationJournalRow } from '../migrations.ts'
4
+
5
+ export function normalizeChecksum(migration: MigrationDescriptor): string {
6
+ if (migration.checksum) {
7
+ return migration.checksum
8
+ }
9
+
10
+ return migration.id + ':' + migration.name
11
+ }
12
+
13
+ export async function ensureMigrationJournal(
14
+ adapter: DatabaseAdapter,
15
+ tableName: string,
16
+ ): Promise<void> {
17
+ await adapter.migrate({
18
+ operation: {
19
+ kind: 'createTable',
20
+ table: { name: tableName },
21
+ ifNotExists: true,
22
+ columns: {
23
+ id: { type: 'varchar', length: 64, nullable: false, primaryKey: true },
24
+ name: { type: 'varchar', length: 255, nullable: false },
25
+ checksum: { type: 'varchar', length: 128, nullable: false },
26
+ batch: { type: 'integer', nullable: false },
27
+ applied_at: { type: 'timestamp', nullable: false, default: { kind: 'now' } },
28
+ },
29
+ },
30
+ })
31
+ }
32
+
33
+ export async function hasMigrationJournal(
34
+ adapter: DatabaseAdapter,
35
+ tableName: string,
36
+ ): Promise<boolean> {
37
+ try {
38
+ await adapter.execute({
39
+ operation: {
40
+ kind: 'raw',
41
+ sql: rawSql('select 1 from ' + tableName + ' limit 1'),
42
+ },
43
+ })
44
+
45
+ return true
46
+ } catch {
47
+ return false
48
+ }
49
+ }
50
+
51
+ export async function loadJournalRows(
52
+ adapter: DatabaseAdapter,
53
+ tableName: string,
54
+ ): Promise<MigrationJournalRow[]> {
55
+ let result = await adapter.execute({
56
+ operation: {
57
+ kind: 'raw',
58
+ sql: rawSql(
59
+ 'select id, name, checksum, batch, applied_at from ' + tableName + ' order by id asc',
60
+ ),
61
+ },
62
+ })
63
+
64
+ let rows = result.rows ?? []
65
+
66
+ return rows.map((row) => ({
67
+ id: String(row.id),
68
+ name: String(row.name),
69
+ checksum: String(row.checksum),
70
+ batch: Number(row.batch),
71
+ appliedAt: new Date(String(row.applied_at)),
72
+ }))
73
+ }
74
+
75
+ export async function insertJournalRow(
76
+ adapter: DatabaseAdapter,
77
+ tableName: string,
78
+ row: {
79
+ id: string
80
+ name: string
81
+ checksum: string
82
+ batch: number
83
+ },
84
+ transaction?: TransactionToken,
85
+ ): Promise<void> {
86
+ await adapter.execute({
87
+ operation: {
88
+ kind: 'raw',
89
+ sql: rawSql('insert into ' + tableName + ' (id, name, checksum, batch) values (?, ?, ?, ?)', [
90
+ row.id,
91
+ row.name,
92
+ row.checksum,
93
+ row.batch,
94
+ ]),
95
+ },
96
+ transaction,
97
+ })
98
+ }
99
+
100
+ export async function deleteJournalRow(
101
+ adapter: DatabaseAdapter,
102
+ tableName: string,
103
+ id: string,
104
+ transaction?: TransactionToken,
105
+ ): Promise<void> {
106
+ await adapter.execute({
107
+ operation: {
108
+ kind: 'raw',
109
+ sql: rawSql('delete from ' + tableName + ' where id = ?', [id]),
110
+ },
111
+ transaction,
112
+ })
113
+ }
114
+
115
+ export function getBatch(rows: MigrationJournalRow[]): number {
116
+ if (rows.length === 0) {
117
+ return 1
118
+ }
119
+
120
+ let max = Math.max(...rows.map((row) => row.batch))
121
+ return max + 1
122
+ }
@@ -0,0 +1,62 @@
1
+ import type { MigrationDescriptor, MigrationRegistry } from '../migrations.ts'
2
+
3
+ /**
4
+ * Returns a new array of migrations ordered by migration id.
5
+ * @param migrations Migration descriptors to sort.
6
+ * @returns A newly sorted migration descriptor array.
7
+ */
8
+ export function sortMigrations(migrations: MigrationDescriptor[]): MigrationDescriptor[] {
9
+ return [...migrations].sort((left, right) => left.id.localeCompare(right.id))
10
+ }
11
+
12
+ /**
13
+ * Resolves a migration source into a sorted migration list.
14
+ * @param input Migration list or registry.
15
+ * @returns A sorted migration descriptor list.
16
+ */
17
+ export function resolveMigrations(
18
+ input: MigrationDescriptor[] | MigrationRegistry,
19
+ ): MigrationDescriptor[] {
20
+ if (Array.isArray(input)) {
21
+ return sortMigrations(input)
22
+ }
23
+
24
+ return input.list()
25
+ }
26
+
27
+ /**
28
+ * Creates an in-memory migration registry.
29
+ * @param initial Optional initial migration list.
30
+ * @returns A migration registry with duplicate-id protection.
31
+ * @example
32
+ * ```ts
33
+ * import { createMigrationRegistry } from 'remix/data-table/migrations'
34
+ *
35
+ * let registry = createMigrationRegistry()
36
+ * registry.register({ id, name, migration })
37
+ * ```
38
+ */
39
+ export function createMigrationRegistry(initial: MigrationDescriptor[] = []): MigrationRegistry {
40
+ let migrations = new Map<string, MigrationDescriptor>()
41
+
42
+ for (let migration of initial) {
43
+ if (migrations.has(migration.id)) {
44
+ throw new Error('Duplicate migration id: ' + migration.id)
45
+ }
46
+
47
+ migrations.set(migration.id, migration)
48
+ }
49
+
50
+ return {
51
+ register(migration: MigrationDescriptor) {
52
+ if (migrations.has(migration.id)) {
53
+ throw new Error('Duplicate migration id: ' + migration.id)
54
+ }
55
+
56
+ migrations.set(migration.id, migration)
57
+ },
58
+ list() {
59
+ return sortMigrations(Array.from(migrations.values()))
60
+ },
61
+ }
62
+ }
@@ -0,0 +1,374 @@
1
+ import { createDatabase, createDatabaseWithTransaction } from '../database.ts'
2
+ import type { Database } from '../database.ts'
3
+ import type { DatabaseAdapter, TransactionToken } from '../adapter.ts'
4
+ import type { SqlStatement } from '../sql.ts'
5
+ import type {
6
+ MigrateOptions,
7
+ MigrateResult,
8
+ MigrationContext,
9
+ MigrationDescriptor,
10
+ MigrationDirection,
11
+ MigrationJournalRow,
12
+ MigrationRegistry,
13
+ MigrationRunner,
14
+ MigrationRunnerOptions,
15
+ MigrationStatus,
16
+ MigrationStatusEntry,
17
+ } from '../migrations.ts'
18
+
19
+ import {
20
+ deleteJournalRow,
21
+ ensureMigrationJournal,
22
+ getBatch,
23
+ hasMigrationJournal,
24
+ insertJournalRow,
25
+ loadJournalRows,
26
+ normalizeChecksum,
27
+ } from './journal-store.ts'
28
+ import { resolveMigrations } from './registry.ts'
29
+ import { createMigrationSchema } from './schema-api.ts'
30
+
31
+ type RunMigrationsInput = {
32
+ adapter: DatabaseAdapter
33
+ migrations: MigrationDescriptor[]
34
+ journalTable: string
35
+ direction: MigrationDirection
36
+ options: MigrateOptions
37
+ }
38
+
39
+ function assertStepOption(step: number | undefined): void {
40
+ if (step === undefined) {
41
+ return
42
+ }
43
+
44
+ if (!Number.isInteger(step) || step < 1) {
45
+ throw new Error('Invalid migration step option. Expected a positive integer.')
46
+ }
47
+ }
48
+
49
+ function assertMigrateOptions(options: MigrateOptions): void {
50
+ if (options.to !== undefined && options.step !== undefined) {
51
+ throw new Error('Cannot combine "to" and "step" migration options in the same run')
52
+ }
53
+ }
54
+
55
+ function assertTargetOption(migrations: MigrationDescriptor[], to: string | undefined): void {
56
+ if (!to) {
57
+ return
58
+ }
59
+
60
+ let target = migrations.find((migration) => migration.id === to)
61
+
62
+ if (!target) {
63
+ throw new Error('Unknown migration target: ' + to)
64
+ }
65
+ }
66
+
67
+ function assertNoMigrationDrift(
68
+ migrations: MigrationDescriptor[],
69
+ journal: MigrationJournalRow[],
70
+ ): void {
71
+ let migrationMap = new Map(migrations.map((migration) => [migration.id, migration]))
72
+
73
+ for (let row of journal) {
74
+ let migration = migrationMap.get(row.id)
75
+
76
+ if (!migration) {
77
+ continue
78
+ }
79
+
80
+ let expected = normalizeChecksum(migration)
81
+
82
+ if (expected !== row.checksum) {
83
+ throw new Error(
84
+ 'Migration checksum drift detected for "' +
85
+ row.id +
86
+ '" (journal=' +
87
+ row.checksum +
88
+ ', current=' +
89
+ expected +
90
+ ')',
91
+ )
92
+ }
93
+ }
94
+ }
95
+
96
+ function createDryRunDatabase(adapter: DatabaseAdapter): Database {
97
+ let error = new Error('Cannot execute data operations while running migrations with dryRun')
98
+ let throwDryRunError = async (): Promise<never> => {
99
+ throw error
100
+ }
101
+ let dryRunAdapter: DatabaseAdapter = {
102
+ dialect: adapter.dialect,
103
+ capabilities: adapter.capabilities,
104
+ compileSql(operation) {
105
+ return adapter.compileSql(operation)
106
+ },
107
+ async hasTable(table) {
108
+ return adapter.hasTable(table)
109
+ },
110
+ async hasColumn(table, column) {
111
+ return adapter.hasColumn(table, column)
112
+ },
113
+ execute: throwDryRunError,
114
+ migrate: throwDryRunError,
115
+ beginTransaction: throwDryRunError,
116
+ commitTransaction: throwDryRunError,
117
+ rollbackTransaction: throwDryRunError,
118
+ createSavepoint: throwDryRunError,
119
+ rollbackToSavepoint: throwDryRunError,
120
+ releaseSavepoint: throwDryRunError,
121
+ }
122
+
123
+ return createDatabase(dryRunAdapter)
124
+ }
125
+
126
+ async function runMigrations(input: RunMigrationsInput): Promise<MigrateResult> {
127
+ let adapter = input.adapter
128
+ let migrations = input.migrations
129
+ let journalTable = input.journalTable
130
+ let dryRun = Boolean(input.options.dryRun)
131
+ let target = input.options.to
132
+ let step = input.options.step
133
+
134
+ assertMigrateOptions(input.options)
135
+ assertStepOption(step)
136
+ assertTargetOption(migrations, target)
137
+
138
+ let sql: SqlStatement[] = []
139
+
140
+ await adapter.acquireMigrationLock?.()
141
+
142
+ try {
143
+ let journal: MigrationJournalRow[] = []
144
+
145
+ if (dryRun) {
146
+ let canReadJournal = await hasMigrationJournal(adapter, journalTable)
147
+
148
+ if (canReadJournal) {
149
+ journal = await loadJournalRows(adapter, journalTable)
150
+ }
151
+ } else {
152
+ await ensureMigrationJournal(adapter, journalTable)
153
+ journal = await loadJournalRows(adapter, journalTable)
154
+ }
155
+
156
+ let appliedMap = new Map(journal.map((row) => [row.id, row]))
157
+ assertNoMigrationDrift(migrations, journal)
158
+ let toRun: MigrationDescriptor[] = []
159
+
160
+ if (input.direction === 'up') {
161
+ for (let migration of migrations) {
162
+ if (!appliedMap.has(migration.id)) {
163
+ toRun.push(migration)
164
+ }
165
+ }
166
+
167
+ if (target) {
168
+ toRun = toRun.filter((migration) => migration.id <= target)
169
+ }
170
+
171
+ if (step !== undefined) {
172
+ toRun = toRun.slice(0, step)
173
+ }
174
+ } else {
175
+ let appliedMigrations = migrations
176
+ .filter((migration) => appliedMap.has(migration.id))
177
+ .reverse()
178
+
179
+ if (target) {
180
+ appliedMigrations = appliedMigrations.filter((migration) => migration.id >= target)
181
+ }
182
+
183
+ if (step !== undefined) {
184
+ appliedMigrations = appliedMigrations.slice(0, step)
185
+ }
186
+
187
+ toRun = appliedMigrations
188
+ }
189
+
190
+ let applied: MigrationStatusEntry[] = []
191
+ let reverted: MigrationStatusEntry[] = []
192
+ let batch = getBatch(journal)
193
+
194
+ for (let migration of toRun) {
195
+ if (
196
+ migration.migration.transaction === 'required' &&
197
+ !adapter.capabilities.transactionalDdl
198
+ ) {
199
+ throw new Error(
200
+ 'Migration "' +
201
+ migration.id +
202
+ '" requires transactional DDL, but adapter does not support it',
203
+ )
204
+ }
205
+
206
+ let shouldUseTransaction =
207
+ !dryRun &&
208
+ migration.migration.transaction !== 'none' &&
209
+ adapter.capabilities.transactionalDdl
210
+ let token: TransactionToken | undefined
211
+
212
+ if (shouldUseTransaction) {
213
+ token = await adapter.beginTransaction()
214
+ }
215
+
216
+ let db = dryRun
217
+ ? createDryRunDatabase(adapter)
218
+ : token
219
+ ? createDatabaseWithTransaction(adapter, token)
220
+ : createDatabase(adapter)
221
+
222
+ let schema = createMigrationSchema(
223
+ db,
224
+ async (operation) => {
225
+ let compiled = adapter.compileSql(operation)
226
+ sql.push(...compiled)
227
+
228
+ if (!dryRun) {
229
+ await adapter.migrate({ operation, transaction: token })
230
+ }
231
+ },
232
+ { transaction: token },
233
+ )
234
+ let context: MigrationContext = {
235
+ db,
236
+ schema,
237
+ }
238
+
239
+ try {
240
+ if (input.direction === 'up') {
241
+ await migration.migration.up(context)
242
+
243
+ if (!dryRun) {
244
+ await insertJournalRow(
245
+ adapter,
246
+ journalTable,
247
+ {
248
+ id: migration.id,
249
+ name: migration.name,
250
+ checksum: normalizeChecksum(migration),
251
+ batch,
252
+ },
253
+ token,
254
+ )
255
+ }
256
+
257
+ applied.push({
258
+ id: migration.id,
259
+ name: migration.name,
260
+ status: 'applied',
261
+ })
262
+ } else {
263
+ await migration.migration.down(context)
264
+
265
+ if (!dryRun) {
266
+ await deleteJournalRow(adapter, journalTable, migration.id, token)
267
+ }
268
+
269
+ reverted.push({
270
+ id: migration.id,
271
+ name: migration.name,
272
+ status: 'pending',
273
+ })
274
+ }
275
+
276
+ if (token) {
277
+ await adapter.commitTransaction(token)
278
+ }
279
+ } catch (error) {
280
+ if (token) {
281
+ await adapter.rollbackTransaction(token)
282
+ }
283
+
284
+ throw error
285
+ }
286
+ }
287
+
288
+ return {
289
+ applied,
290
+ reverted,
291
+ sql,
292
+ }
293
+ } finally {
294
+ await adapter.releaseMigrationLock?.()
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Creates a migration runner for applying/reverting migrations against an adapter.
300
+ * @param adapter Database adapter used to compile and execute migration operations.
301
+ * @param migrations Migration descriptors or registry.
302
+ * @param options Optional runner configuration.
303
+ * @returns A migration runner instance.
304
+ * @example
305
+ * ```ts
306
+ * import { createMigrationRunner } from 'remix/data-table/migrations'
307
+ *
308
+ * let runner = createMigrationRunner(adapter, migrations, {
309
+ * journalTable: 'app_migrations',
310
+ * })
311
+ * await runner.up()
312
+ * ```
313
+ */
314
+ export function createMigrationRunner(
315
+ adapter: DatabaseAdapter,
316
+ migrations: MigrationDescriptor[] | MigrationRegistry,
317
+ options: MigrationRunnerOptions = {},
318
+ ): MigrationRunner {
319
+ let journalTable = options.journalTable ?? 'data_table_migrations'
320
+
321
+ return {
322
+ async up(runOptions: MigrateOptions = {}): Promise<MigrateResult> {
323
+ return runMigrations({
324
+ adapter,
325
+ migrations: resolveMigrations(migrations),
326
+ journalTable,
327
+ direction: 'up',
328
+ options: runOptions,
329
+ })
330
+ },
331
+ async down(runOptions: MigrateOptions = {}): Promise<MigrateResult> {
332
+ return runMigrations({
333
+ adapter,
334
+ migrations: resolveMigrations(migrations),
335
+ journalTable,
336
+ direction: 'down',
337
+ options: runOptions,
338
+ })
339
+ },
340
+ async status(): Promise<MigrationStatusEntry[]> {
341
+ await ensureMigrationJournal(adapter, journalTable)
342
+
343
+ let journal = await loadJournalRows(adapter, journalTable)
344
+ let journalMap = new Map(journal.map((row) => [row.id, row]))
345
+ let sortedMigrations = resolveMigrations(migrations)
346
+
347
+ return sortedMigrations.map((migration) => {
348
+ let journalRow = journalMap.get(migration.id)
349
+
350
+ if (!journalRow) {
351
+ return {
352
+ id: migration.id,
353
+ name: migration.name,
354
+ status: 'pending' as MigrationStatus,
355
+ }
356
+ }
357
+
358
+ let checksum = normalizeChecksum(migration)
359
+
360
+ return {
361
+ id: migration.id,
362
+ name: migration.name,
363
+ status:
364
+ checksum === journalRow.checksum
365
+ ? ('applied' as MigrationStatus)
366
+ : ('drifted' as MigrationStatus),
367
+ appliedAt: journalRow.appliedAt,
368
+ batch: journalRow.batch,
369
+ checksum: journalRow.checksum,
370
+ }
371
+ })
372
+ },
373
+ }
374
+ }