/
DbPush.ts
293 lines (252 loc) · 7.73 KB
/
DbPush.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
import {
arg,
Command,
format,
HelpError,
isError,
getSchemaPath,
logger,
isCi,
getCommandWithExecutor,
} from '@prisma/sdk'
import path from 'path'
import chalk from 'chalk'
import prompt from 'prompts'
import { Migrate } from '../Migrate'
import { ensureDatabaseExists, getDbInfo } from '../utils/ensureDatabaseExists'
import { formatms } from '../utils/formatms'
import {
DbPushIgnoreWarningsWithFlagError,
DbPushForceFlagRenamedError,
NoSchemaFoundError,
} from '../utils/errors'
import { printDatasource } from '../utils/printDatasource'
import { EngineResults } from '../types'
export class DbPush implements Command {
public static new(): DbPush {
return new DbPush()
}
private static help = format(`
${
process.platform === 'win32' ? '' : chalk.bold('🙌 ')
}Push the state from your Prisma schema to your database
${chalk.bold('Usage')}
${chalk.dim('$')} prisma db push [options]
${chalk.bold('Options')}
-h, --help Display this help message
--schema Custom path to your Prisma schema
--accept-data-loss Ignore data loss warnings
--force-reset Force a reset of the database before push
--skip-generate Skip triggering generators (e.g. Prisma Client)
${chalk.bold('Examples')}
Push the Prisma schema state to the database
${chalk.dim('$')} prisma db push
Specify a schema
${chalk.dim('$')} prisma db push --schema=./schema.prisma
Ignore data loss warnings
${chalk.dim('$')} prisma db push --accept-data-loss
`)
public async parse(argv: string[]): Promise<string | Error> {
const args = arg(
argv,
{
'--help': Boolean,
'-h': '--help',
'--preview-feature': Boolean,
'--accept-data-loss': Boolean,
'--force-reset': Boolean,
'--skip-generate': Boolean,
'--schema': String,
'--telemetry-information': String,
// Deprecated
// --force renamed to --accept-data-loss in 2.17.0
'--force': Boolean,
'-f': '--force',
},
false,
)
if (isError(args)) {
return this.help(args.message)
}
if (args['--help']) {
return this.help()
}
if (args['--preview-feature']) {
logger.warn(`Prisma "db push" was in Preview and is now Generally Available.
You can now remove the ${chalk.red('--preview-feature')} flag.`)
}
if (args['--force']) {
throw new DbPushForceFlagRenamedError()
}
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)
const dbInfo = await getDbInfo(schemaPath)
const migrate = new Migrate(schemaPath)
// Automatically create the database if it doesn't exist
const wasDbCreated = await ensureDatabaseExists('push', true, schemaPath)
if (wasDbCreated) {
console.info()
console.info(wasDbCreated)
}
let wasDatabaseReset = false
if (args['--force-reset']) {
console.info()
try {
await migrate.reset()
} catch (e) {
migrate.stop()
throw e
}
if (dbInfo.dbName && dbInfo.dbLocation) {
console.info(
`The ${dbInfo.dbType} ${dbInfo.schemaWord} "${dbInfo.dbName}" from "${dbInfo.dbLocation}" was successfully reset.`,
)
} else {
console.info(
`The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`,
)
}
wasDatabaseReset = true
}
const before = Date.now()
let migration: EngineResults.SchemaPush
try {
migration = await migrate.push({
force: args['--accept-data-loss'],
})
} catch (e) {
migrate.stop()
throw e
}
if (migration.unexecutable && migration.unexecutable.length > 0) {
const messages: string[] = []
messages.push(
`${chalk.bold.red('\n⚠️ We found changes that cannot be executed:\n')}`,
)
for (const item of migration.unexecutable) {
messages.push(`${chalk(` • ${item}`)}`)
}
console.info() // empty line
// We use prompts.inject() for testing in our CI
if (isCi() && Boolean((prompt as any)._injected?.length) === false) {
migrate.stop()
throw new Error(`${messages.join('\n')}\n
Use the --force-reset flag to drop the database before push like ${chalk.bold.greenBright(
getCommandWithExecutor('prisma db push --force-reset'),
)}
${chalk.bold.redBright('All data will be lost.')}
`)
} else {
console.info(`${messages.join('\n')}\n`)
}
console.info() // empty line
const confirmation = await prompt({
type: 'confirm',
name: 'value',
message: `To apply this change we need to reset the database, do you want to continue? ${chalk.red(
'All data will be lost',
)}.`,
})
if (!confirmation.value) {
console.info('Reset cancelled.')
migrate.stop()
process.exit(0)
// For snapshot test, because exit() is mocked
return ``
}
try {
// Reset first to remove all structure and data
await migrate.reset()
if (dbInfo.dbName && dbInfo.dbLocation) {
console.info(
`The ${dbInfo.dbType} ${dbInfo.schemaWord} "${dbInfo.dbName}" from "${dbInfo.dbLocation}" was successfully reset.`,
)
} else {
console.info(
`The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`,
)
}
wasDatabaseReset = true
// And now we can db push
await migrate.push({})
} catch (e) {
migrate.stop()
throw e
}
}
if (migration.warnings && migration.warnings.length > 0) {
console.info(
chalk.bold.yellow(
`\n⚠️ There might be data loss when applying the changes:\n`,
),
)
for (const warning of migration.warnings) {
console.info(chalk(` • ${warning}`))
}
console.info() // empty line
if (!args['--accept-data-loss']) {
// We use prompts.inject() for testing in our CI
if (isCi() && Boolean((prompt as any)._injected?.length) === false) {
migrate.stop()
throw new DbPushIgnoreWarningsWithFlagError()
}
console.info() // empty line
const confirmation = await prompt({
type: 'confirm',
name: 'value',
message: `Do you want to ignore the warning(s)?`,
})
if (!confirmation.value) {
console.info('Push cancelled.')
migrate.stop()
process.exit(0)
// For snapshot test, because exit() is mocked
return ``
}
try {
await migrate.push({
force: true,
})
} catch (e) {
migrate.stop()
throw e
}
}
}
migrate.stop()
if (
!wasDatabaseReset &&
migration.warnings.length === 0 &&
migration.executedSteps === 0
) {
console.info(`\nThe database is already in sync with the Prisma schema.`)
} else {
console.info(
`\n${
process.platform === 'win32' ? '' : '🚀 '
}Your database is now in sync with your schema. Done in ${formatms(
Date.now() - before,
)}`,
)
}
// Run if not skipped
if (!process.env.PRISMA_MIGRATE_SKIP_GENERATE && !args['--skip-generate']) {
await migrate.tryToRunGenerate()
}
return ``
}
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${DbPush.help}`)
}
return DbPush.help
}
}