-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
MigrateReset.ts
189 lines (155 loc) · 4.91 KB
/
MigrateReset.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
import {
arg,
Command,
format,
getSchemaPath,
HelpError,
isError,
isCi,
link,
} from '@prisma/sdk'
import chalk from 'chalk'
import path from 'path'
import prompt from 'prompts'
import { Migrate } from '../Migrate'
import {
ExperimentalFlagWithNewMigrateError,
EarlyAccessFeatureFlagWithNewMigrateError,
} from '../utils/flagErrors'
import {
NoSchemaFoundError,
MigrateResetEnvNonInteractiveError,
} from '../utils/errors'
import { printFilesFromMigrationIds } from '../utils/printFiles'
import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate'
import { ensureDatabaseExists } from '../utils/ensureDatabaseExists'
import { printDatasource } from '../utils/printDatasource'
import { tryToRunSeed, detectSeedFiles } from '../utils/seed'
export class MigrateReset implements Command {
public static new(): MigrateReset {
return new MigrateReset()
}
private static help = format(`
Reset your database and apply all migrations, all data will be lost
${chalk.bold('Usage')}
${chalk.dim('$')} prisma migrate reset [options]
${chalk.bold('Options')}
-h, --help Display this help message
--schema Custom path to your Prisma schema
--skip-generate Skip triggering generators (e.g. Prisma Client)
--skip-seed Skip triggering seed
-f, --force Skip the confirmation prompt
${chalk.bold('Examples')}
Reset your database and apply all migrations, all data will be lost
${chalk.dim('$')} prisma migrate reset
Specify a schema
${chalk.dim('$')} prisma migrate reset --schema=./schema.prisma
Use --force to skip the confirmation prompt
${chalk.dim('$')} prisma migrate reset --force
`)
public async parse(argv: string[]): Promise<string | Error> {
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
'--force': Boolean,
'-f': '--force',
'--skip-generate': Boolean,
'--skip-seed': Boolean,
'--experimental': Boolean,
'--early-access-feature': Boolean,
'--schema': String,
'--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()
}
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)
}
if (!args['--force']) {
// We use prompts.inject() for testing in our CI
if (isCi() && Boolean((prompt as any)._injected?.length) === false) {
throw new MigrateResetEnvNonInteractiveError()
}
console.info() // empty line
const confirmation = await prompt({
type: 'confirm',
name: 'value',
message: `Are you sure you want to reset your database? ${chalk.red(
'All data will be lost',
)}.`,
})
if (!confirmation.value) {
console.info('Reset cancelled.')
process.exit(0)
// For snapshot test, because exit() is mocked
return ``
}
}
const migrate = new Migrate(schemaPath)
let migrationIds: string[]
try {
await migrate.reset()
const { appliedMigrationNames } = await migrate.applyMigrations()
migrationIds = appliedMigrationNames
} finally {
migrate.stop()
}
if (migrationIds.length === 0) {
console.info(`${chalk.green('Database reset successful')}`)
} else {
console.info(
`${chalk.green('Database reset successful')}
The following migration(s) have been applied:\n\n${chalk(
printFilesFromMigrationIds('migrations', migrationIds, {
'migration.sql': '',
}),
)}`,
)
}
// Run if not skipped
if (!process.env.PRISMA_MIGRATE_SKIP_GENERATE && !args['--skip-generate']) {
await migrate.tryToRunGenerate()
}
// Run if not skipped
if (!process.env.PRISMA_MIGRATE_SKIP_SEED && !args['--skip-seed']) {
// Run seed if 1 or more seed files are present
const detected = detectSeedFiles(schemaPath)
if (detected.numberOfSeedFiles > 0) {
await tryToRunSeed(schemaPath)
}
}
return ``
}
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(
`\n${chalk.bold.red(`!`)} ${error}\n${MigrateReset.help}`,
)
}
return MigrateReset.help
}
}