-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
MigrateDev.ts
484 lines (417 loc) · 15.1 KB
/
MigrateDev.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import {
arg,
Command,
format,
HelpError,
isError,
getSchemaPath,
getCommandWithExecutor,
isCi,
link,
} from '@prisma/sdk'
import Debug from '@prisma/debug'
import chalk from 'chalk'
import prompt from 'prompts'
import path from 'path'
import { Migrate } from '../Migrate'
import { UserFacingErrorWithMeta } from '../types'
import { ensureDatabaseExists, getDbInfo } from '../utils/ensureDatabaseExists'
import {
PreviewFlagError,
ExperimentalFlagWithNewMigrateError,
EarlyAccessFeatureFlagWithNewMigrateError,
} from '../utils/flagErrors'
import { NoSchemaFoundError, EnvNonInteractiveError } from '../utils/errors'
import { printMigrationId } from '../utils/printMigrationId'
import { printFilesFromMigrationIds } from '../utils/printFiles'
import {
handleUnexecutableSteps,
handleWarnings,
} from '../utils/handleEvaluateDataloss'
import { getMigrationName } from '../utils/promptForMigrationName'
import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate'
import { printDatasource } from '../utils/printDatasource'
const debug = Debug('migrate:dev')
export class MigrateDev implements Command {
public static new(): MigrateDev {
return new MigrateDev()
}
private static help = format(`
Create a migration from changes in Prisma schema, apply it to the database, trigger generators (e.g. Prisma Client)
${chalk.bold.yellow('WARNING')} ${chalk.bold(
`Prisma's migration functionality is currently in Preview (${link(
'https://pris.ly/d/preview',
)}).`,
)}
${chalk.dim(
'When using any of the commands below you need to explicitly opt-in via the --preview-feature flag.',
)}
${chalk.bold('Usage')}
${chalk.dim('$')} prisma migrate dev [options] --preview-feature
${chalk.bold('Options')}
-h, --help Display this help message
--schema Custom path to your Prisma schema
-n, --name Name the migration
--create-only Create a new migration but do not apply it
The migration will be empty if there are no changes in Prisma schema
--skip-generate Skip triggering generators (e.g. Prisma Client)
${chalk.bold('Examples')}
Create a migration from changes in Prisma schema, apply it to the database, trigger generators (e.g. Prisma Client)
${chalk.dim('$')} prisma migrate dev --preview-feature
Specify a schema
${chalk.dim(
'$',
)} prisma migrate dev --schema=./schema.prisma --preview-feature
Create a migration without applying it
${chalk.dim('$')} prisma migrate dev --create-only --preview-feature
`)
public async parse(argv: string[]): Promise<string | Error> {
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
'--name': String,
'-n': '--name',
// '--force': Boolean,
// '-f': '--force',
'--create-only': Boolean,
'--schema': String,
'--skip-generate': Boolean,
'--experimental': Boolean,
'--preview-feature': Boolean,
'--early-access-feature': Boolean,
'--telemetry-information': String,
})
if (isError(args)) {
return this.help(args.message)
}
if (args['--help']) {
return this.help()
}
if (args['--experimental']) {
throw new ExperimentalFlagWithNewMigrateError()
}
if (args['--early-access-feature']) {
throw new EarlyAccessFeatureFlagWithNewMigrateError()
}
if (!args['--preview-feature']) {
throw new PreviewFlagError()
}
const schemaPath = await getSchemaPath(args['--schema'])
if (!schemaPath) {
throw new NoSchemaFoundError()
}
console.info(
chalk.dim(
`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`,
),
)
await printDatasource(schemaPath)
console.info() // empty line
throwUpgradeErrorIfOldMigrate(schemaPath)
// Automatically create the database if it doesn't exist
const wasDbCreated = await ensureDatabaseExists('create', true, schemaPath)
if (wasDbCreated) {
console.info(wasDbCreated)
}
const migrate = new Migrate(schemaPath)
const diagnoseResult = await migrate.diagnoseMigrationHistory({
optInToShadowDatabase: true,
})
debug({ diagnoseResult })
let isResetNeeded = false
const isResetNeededAfterCreate = false
let migrationIdsFromDatabaseIsBehind: string[] = []
let migrationIdsFromAfterReset: string[] = []
if (diagnoseResult.errorInUnappliedMigration) {
if (diagnoseResult.errorInUnappliedMigration.error_code === 'P3006') {
const failedMigrationError = diagnoseResult.errorInUnappliedMigration as UserFacingErrorWithMeta
throw new Error(
`The migration ${
failedMigrationError.meta.migration_name
} failed when applied to the shadow database.
${chalk.green(
`Fix the migration script and run ${getCommandWithExecutor(
'prisma migrate dev --preview-feature',
)} again.`,
)}
${failedMigrationError.error_code}
${failedMigrationError.message}`,
)
} else {
throw new Error(`${diagnoseResult.errorInUnappliedMigration.error_code}
${diagnoseResult.errorInUnappliedMigration.message}`)
}
}
const hasFailedMigrations = diagnoseResult.failedMigrationNames.length > 0
const hasModifiedMigrations = diagnoseResult.editedMigrationNames.length > 0
// if failed migration(s) or modified migration(s) print and got to reset
if (hasFailedMigrations || hasModifiedMigrations) {
isResetNeeded = true
if (hasFailedMigrations) {
// migration(s), usually one, that failed to apply the the database (which may have data)
console.info(
`The following migration(s) failed to apply:\n- ${diagnoseResult.failedMigrationNames.join(
'\n- ',
)}\n`,
)
}
if (hasModifiedMigrations) {
// migration(s) that were modified since they were applied to the db.
console.info(
`The following migration(s) were modified after they were applied:
- ${diagnoseResult.editedMigrationNames.join('\n- ')}\n`,
)
if (diagnoseResult.drift?.diagnostic === 'migrationFailedToApply') {
// Migration has a problem (failed to cleanly apply to a temporary database) and
// needs to be fixed or the database has a problem (example: incorrect version, missing extension)
if (diagnoseResult.drift.error.error_code === 'P3006') {
const failedMigrationError = diagnoseResult.drift
.error as UserFacingErrorWithMeta
throw new Error(
`The migration ${
failedMigrationError.meta.migration_name
} failed when applied to the shadow database.
${chalk.green(
`Fix the migration script and run ${getCommandWithExecutor(
'prisma migrate dev --preview-feature',
)} again.`,
)}
${failedMigrationError.error_code}
${failedMigrationError.message}`,
)
}
}
}
} else {
if (diagnoseResult.drift) {
if (diagnoseResult.drift?.diagnostic === 'migrationFailedToApply') {
// Migration has a problem (failed to cleanly apply to a temporary database) and
// needs to be fixed or the database has a problem (example: incorrect version, missing extension)
throw new Error(
`A migration failed when applied to the shadow database:
${
diagnoseResult.drift.error.error_code
? diagnoseResult.drift.error.error_code
: ''
}
${diagnoseResult.drift.error.message}`,
)
} else if (diagnoseResult.drift.diagnostic === 'driftDetected') {
// we could try to fix the drift in the future
console.info() // empty line
console.info(
'Drift detected: Your database schema is not in sync with your migration history.',
)
console.info() // empty line
isResetNeeded = true
}
}
if (diagnoseResult.history) {
if (diagnoseResult.history.diagnostic === 'databaseIsBehind') {
const { appliedMigrationNames } = await migrate.applyMigrations()
migrationIdsFromDatabaseIsBehind = appliedMigrationNames
// Inform user about applied migrations now
if (migrationIdsFromDatabaseIsBehind.length > 0) {
console.info(
`The following unapplied migration(s) have been applied:
- ${migrationIdsFromDatabaseIsBehind.join('\n- ')}\n`,
)
}
} else if (
diagnoseResult.history.diagnostic === 'migrationsDirectoryIsBehind'
) {
isResetNeeded = true
} else if (diagnoseResult.history.diagnostic === 'historiesDiverge') {
isResetNeeded = true
// migration(s) were removed from directory since they were applied to the db.
console.info(
`The following migration(s) are applied to the database but missing from the local migrations directory:
- ${diagnoseResult.history.unpersistedMigrationNames.join('\n- ')}\n`,
)
}
}
}
if (isResetNeeded && !isResetNeededAfterCreate) {
if (!args['--force']) {
// We use prompts.inject() for testing in our CI
if (isCi() && Boolean((prompt as any)._injected?.length) === false) {
throw new EnvNonInteractiveError()
}
const dbInfo = await getDbInfo(schemaPath)
const confirmedReset = await this.confirmReset(dbInfo)
console.info() // empty line
if (!confirmedReset) {
console.info('Reset cancelled.')
process.exit(0)
// For snapshot test, because exit() is mocked
return ``
}
}
await migrate.reset()
const { appliedMigrationNames } = await migrate.applyMigrations()
migrationIdsFromAfterReset = appliedMigrationNames
// Inform user about applied migrations now
if (migrationIdsFromAfterReset.length > 0) {
console.info(
`The following migration(s) have been applied after reset:\n\n${chalk(
printFilesFromMigrationIds(
'migrations',
migrationIdsFromAfterReset,
{
'migration.sql': '',
},
),
)}`,
)
}
}
const evaluateDataLossResult = await migrate.evaluateDataLoss()
debug({ evaluateDataLossResult })
// display unexecutableSteps
// throw error
handleUnexecutableSteps(evaluateDataLossResult.unexecutableSteps)
// log warnings and prompt user to continue if needed
const userCancelled = await handleWarnings(
evaluateDataLossResult.warnings,
args['--force'],
)
console.info() // empty line
if (userCancelled) {
migrate.stop()
return `Migration cancelled.`
}
let migrationName: undefined | string = undefined
if (
evaluateDataLossResult.migrationSteps.length > 0 ||
args['--create-only']
) {
const getMigrationNameResult = await getMigrationName(args['--name'])
console.info() // empty line
if (getMigrationNameResult.userCancelled) {
migrate.stop()
return getMigrationNameResult.userCancelled
} else {
migrationName = getMigrationNameResult.name
}
}
const createMigrationResult = await migrate.createMigration({
migrationsDirectoryPath: migrate.migrationsDirectoryPath,
migrationName: migrationName || '',
draft: args['--create-only'] ? true : false,
prismaSchema: migrate.getDatamodel(),
})
debug({ createMigrationResult })
if (args['--create-only']) {
migrate.stop()
console.info() // empty line
return `Prisma Migrate created the following migration without applying it ${printMigrationId(
createMigrationResult.generatedMigrationName!,
)}\n\nYou can now edit it and apply it by running ${chalk.greenBright(
getCommandWithExecutor('prisma migrate dev --preview-feature'),
)}.`
}
if (isResetNeededAfterCreate) {
console.info(
`The following migration was created from new schema changes:\n\n${chalk(
printFilesFromMigrationIds(
'migrations',
[createMigrationResult.generatedMigrationName!],
{
'migration.sql': '',
},
),
)}`,
)
console.info() // empty line
if (!args['--force']) {
// We use prompts.inject() for testing in our CI
if (isCi() && Boolean((prompt as any)._injected?.length) === false) {
throw new EnvNonInteractiveError()
}
console.info(
'Drift detected: Your database schema is not in sync with your migration history.',
)
console.info() // empty line
const dbInfo = await getDbInfo(schemaPath)
const confirmedReset = await this.confirmReset(dbInfo)
console.info() // empty line
if (!confirmedReset) {
console.info('Reset cancelled.')
process.exit(0)
// For snapshot test, because exit() is mocked
return ``
}
await migrate.reset()
}
}
const {
appliedMigrationNames: migrationIds,
} = await migrate.applyMigrations()
migrate.stop()
if (migrationIds.length === 0) {
if (
migrationIdsFromAfterReset.length > 0 ||
migrationIdsFromDatabaseIsBehind.length > 0
) {
// Run if not skipped
if (!process.env.MIGRATE_SKIP_GENERATE && !args['--skip-generate']) {
await migrate.tryToRunGenerate()
}
// During databaseIsBehind diagnostic migrations were applied and displayed
console.info() // empty line
return `${chalk.green('Everything is now in sync.')}`
} else {
console.info() // empty line
return `Already in sync, no schema change or unapplied migration was found.`
}
} else {
// For display only
if (
migrationIdsFromAfterReset.length > 0 ||
migrationIdsFromDatabaseIsBehind.length > 0
) {
console.info() // empty line
}
console.info(
`The following migration(s) have been created and applied from new schema changes:\n\n${chalk(
printFilesFromMigrationIds('migrations', migrationIds, {
'migration.sql': '',
}),
)}`,
)
// Run if not skipped
if (!process.env.MIGRATE_SKIP_GENERATE && !args['--skip-generate']) {
await migrate.tryToRunGenerate()
}
console.info() // empty line
return `${chalk.green('Everything is now in sync.')}`
}
}
private async confirmReset({
schemaWord,
dbType,
dbName,
dbLocation,
}): Promise<boolean> {
const mssqlMessage = `We need to reset the database. ${chalk.red(
'All data will be lost',
)}.\nDo you want to continue?`
const message = `We need to reset the ${dbType} ${schemaWord} "${dbName}" at "${dbLocation}". ${chalk.red(
'All data will be lost',
)}.\nDo you want to continue?`
const confirmation = await prompt({
type: 'confirm',
name: 'value',
message: dbType ? message : mssqlMessage,
})
return confirmation.value
}
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(
`\n${chalk.bold.red(`!`)} ${error}\n${MigrateDev.help}`,
)
}
return MigrateDev.help
}
}