forked from prisma/prisma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generate.ts
391 lines (336 loc) · 12.6 KB
/
Generate.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
import { enginesVersion } from '@prisma/engines'
import { SqlQueryOutput } from '@prisma/generator-helper'
import {
arg,
Command,
format,
Generator,
getCommandWithExecutor,
getConfig,
getGenerators,
getGeneratorSuccessMessage,
GetSchemaResult,
getSchemaWithPath,
getSchemaWithPathOptional,
HelpError,
isError,
link,
loadEnvFile,
logger,
missingGeneratorMessage,
parseEnvValue,
} from '@prisma/internals'
import { printSchemaLoadedMessage } from '@prisma/migrate'
import fs from 'fs'
import { blue, bold, dim, green, red, yellow } from 'kleur/colors'
import logUpdate from 'log-update'
import path from 'path'
import resolvePkg from 'resolve-pkg'
import { getHardcodedUrlWarning } from './generate/getHardcodedUrlWarning'
import { introspectSql, sqlDirPath } from './generate/introspectSql'
import { Watcher } from './generate/Watcher'
import { breakingChangesMessage } from './utils/breakingChanges'
import { getRandomPromotion } from './utils/handlePromotions'
import { simpleDebounce } from './utils/simpleDebounce'
const pkg = eval(`require('../package.json')`)
/**
* $ prisma generate
*/
export class Generate implements Command {
public static new(): Generate {
return new Generate()
}
private static help = format(`
Generate artifacts (e.g. Prisma Client)
${bold('Usage')}
${dim('$')} prisma generate [options]
${bold('Options')}
-h, --help Display this help message
--schema Custom path to your Prisma schema
--watch Watch the Prisma schema and rerun after a change
--generator Generator to use (may be provided multiple times)
--no-engine Generate a client for use with Accelerate only
--no-hints Hides the hint messages but still outputs errors and warnings
--allow-no-models Allow generating a client without models
--sql Generate typed sql module
${bold('Examples')}
With an existing Prisma schema
${dim('$')} prisma generate
Or specify a schema
${dim('$')} prisma generate --schema=./schema.prisma
Run the command with multiple specific generators
${dim('$')} prisma generate --generator client1 --generator client2
Watch Prisma schema file and rerun after each change
${dim('$')} prisma generate --watch
`)
private logText = ''
private hasGeneratorErrored = false
private runGenerate = simpleDebounce(async ({ generators }: { generators: Generator[] }) => {
const message: string[] = []
for (const generator of generators) {
const before = Math.round(performance.now())
try {
await generator.generate()
const after = Math.round(performance.now())
message.push(getGeneratorSuccessMessage(generator, after - before) + '\n')
generator.stop()
} catch (err) {
this.hasGeneratorErrored = true
generator.stop()
message.push(`${err.message}\n\n`)
}
}
this.logText += message.join('\n')
})
public async parse(argv: string[]): Promise<string | Error> {
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
'--watch': Boolean,
'--schema': String,
'--data-proxy': Boolean,
'--accelerate': Boolean,
'--no-engine': Boolean,
'--no-hints': Boolean,
'--generator': [String],
// Only used for checkpoint information
'--postinstall': String,
'--telemetry-information': String,
'--allow-no-models': Boolean,
'--sql': Boolean,
})
const postinstallCwd = process.env.PRISMA_GENERATE_IN_POSTINSTALL
let cwd = process.cwd()
if (postinstallCwd && postinstallCwd !== 'true') {
cwd = postinstallCwd
}
if (isError(args)) {
return this.help(args.message)
}
if (args['--help']) {
return this.help()
}
const watchMode = args['--watch'] || false
await loadEnvFile({ schemaPath: args['--schema'], printMessage: true })
const schemaResult = await getSchemaForGenerate(args['--schema'], cwd, Boolean(postinstallCwd))
const promotion = getRandomPromotion()
if (!schemaResult) return ''
const { schemas, schemaPath } = schemaResult
printSchemaLoadedMessage(schemaPath)
const config = await getConfig({ datamodel: schemas, ignoreEnvVarErrors: true })
// TODO Extract logic from here
let hasJsClient
let generators: Generator[] | undefined
let clientGeneratorVersion: string | null = null
let typedSql: SqlQueryOutput[] | undefined
if (args['--sql']) {
typedSql = await introspectSql(schemaPath)
}
try {
generators = await getGenerators({
schemaPath,
printDownloadProgress: !watchMode,
version: enginesVersion,
cliVersion: pkg.version,
generatorNames: args['--generator'],
postinstall: Boolean(args['--postinstall']),
typedSql,
noEngine:
Boolean(args['--no-engine']) ||
Boolean(args['--data-proxy']) || // legacy, keep for backwards compatibility
Boolean(args['--accelerate']) || // legacy, keep for backwards compatibility
Boolean(process.env.PRISMA_GENERATE_DATAPROXY) || // legacy, keep for backwards compatibility
Boolean(process.env.PRISMA_GENERATE_ACCELERATE) || // legacy, keep for backwards compatibility
Boolean(process.env.PRISMA_GENERATE_NO_ENGINE),
allowNoModels: Boolean(args['--allow-no-models']),
})
if (!generators || generators.length === 0) {
this.logText += `${missingGeneratorMessage}\n`
} else {
// Only used for CLI output, ie Go client doesn't want JS example output
const jsClient = generators.find(
(g) => g.options && parseEnvValue(g.options.generator.provider) === 'prisma-client-js',
)
clientGeneratorVersion = jsClient?.manifest?.version ?? null
hasJsClient = Boolean(jsClient)
try {
await this.runGenerate({ generators })
} catch (errRunGenerate) {
this.logText += `${errRunGenerate.message}\n\n`
}
}
} catch (errGetGenerators) {
if (postinstallCwd) {
console.error(`${blue('info')} The postinstall script automatically ran \`prisma generate\`, which failed.
The postinstall script still succeeds but won't generate the Prisma Client.
Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`)
return ''
}
if (watchMode) {
this.logText += `${errGetGenerators.message}\n\n`
} else {
throw errGetGenerators
}
}
let printBreakingChangesMessage = false
if (hasJsClient) {
try {
const clientVersionBeforeGenerate = getCurrentClientVersion()
if (clientVersionBeforeGenerate && typeof clientVersionBeforeGenerate === 'string') {
const [major, minor] = clientVersionBeforeGenerate.split('.')
if (parseInt(major) == 2 && parseInt(minor) < 12) {
printBreakingChangesMessage = true
}
}
} catch (e) {
//
}
}
if (postinstallCwd && printBreakingChangesMessage && logger.should.warn()) {
// skipping generate
return `There have been breaking changes in Prisma Client since you updated last time.
Please run \`prisma generate\` manually.`
}
const watchingText = `\n${green('Watching...')} ${dim(schemaPath)}\n`
if (!watchMode) {
const prismaClientJSGenerator = generators?.find(
({ options }) =>
options?.generator.provider && parseEnvValue(options?.generator.provider) === 'prisma-client-js',
)
let hint = ''
if (prismaClientJSGenerator) {
const generator = prismaClientJSGenerator.options?.generator
const isDeno = generator?.previewFeatures.includes('deno') && !!globalThis.Deno
if (isDeno && !generator?.isCustomOutput) {
throw new Error(`Can't find output dir for generator ${bold(generator!.name)} with provider ${bold(
generator!.provider.value!,
)}.
When using Deno, you need to define \`output\` in the client generator section of your schema.prisma file.`)
}
const breakingChangesStr = printBreakingChangesMessage
? `
${breakingChangesMessage}`
: ''
const hideHints = args['--no-hints'] ?? false
const versionsOutOfSync = clientGeneratorVersion && pkg.version !== clientGeneratorVersion
const versionsWarning =
versionsOutOfSync && logger.should.warn()
? `\n\n${yellow(bold('warn'))} Versions of ${bold(`prisma@${pkg.version}`)} and ${bold(
`@prisma/client@${clientGeneratorVersion}`,
)} don't match.
This might lead to unexpected behavior.
Please make sure they have the same version.`
: ''
if (hideHints) {
hint = `${getHardcodedUrlWarning(config)}${breakingChangesStr}${versionsWarning}`
} else {
hint = `
Start by importing your Prisma Client (See: http://pris.ly/d/importing-client)
${promotion.text} ${promotion.link}
${getHardcodedUrlWarning(config)}${breakingChangesStr}${versionsWarning}`
}
}
const message = '\n' + this.logText + (hasJsClient && !this.hasGeneratorErrored ? hint : '')
if (this.hasGeneratorErrored) {
if (postinstallCwd) {
logger.info(`The postinstall script automatically ran \`prisma generate\`, which failed.
The postinstall script still succeeds but won't generate the Prisma Client.
Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`)
return ''
}
throw new Error(message)
} else {
return message
}
} else {
logUpdate(watchingText + '\n' + this.logText)
const watcher = new Watcher(schemaPath)
if (args['--sql']) {
watcher.add(sqlDirPath(schemaPath))
}
for await (const changedPath of watcher) {
logUpdate(`Change in ${path.relative(process.cwd(), changedPath)}`)
let generatorsWatch: Generator[] | undefined
try {
if (args['--sql']) {
typedSql = await introspectSql(schemaPath)
}
generatorsWatch = await getGenerators({
schemaPath,
printDownloadProgress: !watchMode,
version: enginesVersion,
cliVersion: pkg.version,
generatorNames: args['--generator'],
typedSql,
})
if (!generatorsWatch || generatorsWatch.length === 0) {
this.logText += `${missingGeneratorMessage}\n`
} else {
logUpdate(`\n${green('Building...')}\n\n${this.logText}`)
try {
await this.runGenerate({
generators: generatorsWatch,
})
logUpdate(watchingText + '\n' + this.logText)
} catch (errRunGenerate) {
this.logText += `${errRunGenerate.message}\n\n`
logUpdate(watchingText + '\n' + this.logText)
}
}
} catch (errGetGenerators) {
this.logText += `${errGetGenerators.message}\n\n`
logUpdate(watchingText + '\n' + this.logText)
}
}
}
return ''
}
// help message
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(`\n${bold(red(`!`))} ${error}\n${Generate.help}`)
}
return Generate.help
}
}
function getCurrentClientVersion(): string | null {
try {
let pkgPath = resolvePkg('.prisma/client', { cwd: process.cwd() })
if (!pkgPath) {
const potentialPkgPath = path.join(process.cwd(), 'node_modules/.prisma/client')
if (fs.existsSync(potentialPkgPath)) {
pkgPath = potentialPkgPath
}
}
if (pkgPath) {
const indexPath = path.join(pkgPath, 'index.js')
if (fs.existsSync(indexPath)) {
const program = require(indexPath)
return program?.prismaVersion?.client ?? program?.Prisma?.prismaVersion?.client
}
}
} catch (e) {
return null
}
return null
}
async function getSchemaForGenerate(
schemaFromArgs: string | undefined,
cwd: string,
isPostinstall: boolean,
): Promise<GetSchemaResult | null> {
if (isPostinstall) {
const schema = await getSchemaWithPathOptional(schemaFromArgs, { cwd })
if (schema) {
return schema
}
logger.warn(`We could not find your Prisma schema in the default locations (see: ${link(
'https://pris.ly/d/prisma-schema-location',
)}).
If you have a Prisma schema file in a custom path, you will need to run
\`prisma generate --schema=./path/to/your/schema.prisma\` to generate Prisma Client.
If you do not have a Prisma schema file yet, you can ignore this message.`)
return null
}
return getSchemaWithPath(schemaFromArgs, { cwd })
}