forked from prisma/prisma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generate.ts
413 lines (353 loc) · 13.1 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import { enginesVersion } from '@prisma/engines'
import {
arg,
Command,
drawBox,
format,
Generator,
getCommandWithExecutor,
getConfig,
getGenerators,
getGeneratorSuccessMessage,
HelpError,
highlightTS,
isError,
link,
loadEnvFile,
logger,
missingGeneratorMessage,
parseEnvValue,
} from '@prisma/internals'
import { getSchemaPathAndPrint } from '@prisma/migrate'
import fs from 'fs'
import { blue, bold, dim, green, red, yellow } from 'kleur/colors'
import logUpdate from 'log-update'
import os from 'os'
import path from 'path'
import resolvePkg from 'resolve-pkg'
import { getHardcodedUrlWarning } from './generate/getHardcodedUrlWarning'
import { breakingChangesMessage } from './utils/breakingChanges'
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
${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,
'--generator': [String],
// Only used for checkpoint information
'--postinstall': String,
'--telemetry-information': String,
})
const isPostinstall = process.env.PRISMA_GENERATE_IN_POSTINSTALL
let cwd = process.cwd()
if (isPostinstall && isPostinstall !== 'true') {
cwd = isPostinstall
}
if (isError(args)) {
return this.help(args.message)
}
if (args['--help']) {
return this.help()
}
const watchMode = args['--watch'] || false
loadEnvFile({ schemaPath: args['--schema'], printMessage: true })
const schemaPath = await getSchemaPathAndPrint(args['--schema'], cwd)
if (!schemaPath) return ''
const datamodel = await fs.promises.readFile(schemaPath, 'utf-8')
const config = await getConfig({ datamodel, ignoreEnvVarErrors: true })
// TODO Extract logic from here
let hasJsClient
let generators: Generator[] | undefined
let clientGeneratorVersion: string | null = null
try {
generators = await getGenerators({
schemaPath,
printDownloadProgress: !watchMode,
version: enginesVersion,
cliVersion: pkg.version,
generatorNames: args['--generator'],
postinstall: Boolean(args['--postinstall']),
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),
})
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 (isPostinstall) {
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 (isPostinstall && 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(
(g) => g.options?.generator.provider && parseEnvValue(g.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 importPath = prismaClientJSGenerator.options?.generator?.isCustomOutput
? prefixRelativePathIfNecessary(
replacePathSeparatorsIfNecessary(
path.relative(process.cwd(), parseEnvValue(prismaClientJSGenerator.options.generator.output!)),
),
)
: '@prisma/client'
const breakingChangesStr = printBreakingChangesMessage
? `
${breakingChangesMessage}`
: ''
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.`
: ''
const tryAccelerateMessage = `Deploying your app to serverless or edge functions?
Try Prisma Accelerate for connection pooling and caching.
${link('https://pris.ly/cli/accelerate')}`
const boxedTryAccelerateMessage = drawBox({
height: tryAccelerateMessage.split('\n').length,
width: 0, // calculated automatically
str: tryAccelerateMessage,
horizontalPadding: 2,
})
hint = `
Start using Prisma Client in Node.js (See: ${link('https://pris.ly/d/client')})
${dim('```')}
${highlightTS(`\
import { PrismaClient } from '${importPath}'
const prisma = new PrismaClient()`)}
${dim('```')}
or start using Prisma Client at the edge (See: ${link('https://pris.ly/d/accelerate')})
${dim('```')}
${highlightTS(`\
import { PrismaClient } from '${importPath}/${isDeno ? 'deno/' : ''}edge${isDeno ? '.ts' : ''}'
const prisma = new PrismaClient()`)}
${dim('```')}
See other ways of importing Prisma Client: ${link('http://pris.ly/d/importing-client')}
${boxedTryAccelerateMessage}
${getHardcodedUrlWarning(config)}${breakingChangesStr}${versionsWarning}`
if (generator?.previewFeatures.includes('driverAdapters')) {
if (generator?.isCustomOutput && isDeno) {
hint = `
${bold('Start using Prisma Client')}
${dim('```')}
${highlightTS(`\
import { PrismaClient } from '${importPath}/${isDeno ? 'deno/' : ''}edge${isDeno ? '.ts' : ''}'
const prisma = new PrismaClient()`)}
${dim('```')}
More information: https://pris.ly/d/client`
} else {
hint = `
${bold('Start using Prisma Client')}
${dim('```')}
${highlightTS(`\
import { PrismaClient } from '${importPath}'
const prisma = new PrismaClient()`)}
${dim('```')}
More information: https://pris.ly/d/client`
}
hint = `${hint}
${boxedTryAccelerateMessage}
${getHardcodedUrlWarning(config)}${breakingChangesStr}${versionsWarning}`
}
}
const message = '\n' + this.logText + (hasJsClient && !this.hasGeneratorErrored ? hint : '')
if (this.hasGeneratorErrored) {
if (isPostinstall) {
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)
fs.watch(schemaPath, async (eventType) => {
if (eventType === 'change') {
let generatorsWatch: Generator[] | undefined
try {
generatorsWatch = await getGenerators({
schemaPath,
printDownloadProgress: !watchMode,
version: enginesVersion,
cliVersion: pkg.version,
generatorNames: args['--generator'],
})
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)
}
}
// logUpdate(watchingText + '\n' + this.logText)
} catch (errGetGenerators) {
this.logText += `${errGetGenerators.message}\n\n`
logUpdate(watchingText + '\n' + this.logText)
}
}
})
await new Promise((_) => null) // eslint-disable-line @typescript-eslint/no-unused-vars
}
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 prefixRelativePathIfNecessary(relativePath: string): string {
if (relativePath.startsWith('..')) {
return relativePath
}
return `./${relativePath}`
}
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
}
function replacePathSeparatorsIfNecessary(path: string): string {
const isWindows = os.platform() === 'win32'
if (isWindows) {
return path.replace(/\\/g, '/')
}
return path
}