-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
getDmmf.ts
211 lines (191 loc) · 6.66 KB
/
getDmmf.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
import Debug from '@prisma/debug'
import type { DataSource, DMMF, GeneratorConfig } from '@prisma/generator-helper'
import chalk from 'chalk'
import * as E from 'fp-ts/Either'
import { pipe } from 'fp-ts/lib/function'
import * as TE from 'fp-ts/TaskEither'
import fs from 'fs'
import { match } from 'ts-pattern'
import { ErrorArea, isWasmPanic, RustPanic, WasmPanic } from '../panic'
import { prismaFmt } from '../wasm'
import { addVersionDetailsToErrorMessage } from './errorHelpers'
import { createDebugErrorType, parseQueryEngineError, QueryEngineErrorInit } from './queryEngineCommons'
const debug = Debug('prisma:getDMMF')
export interface ConfigMetaFormat {
datasources: DataSource[]
generators: GeneratorConfig[]
warnings: string[]
}
export type GetDMMFOptions = {
datamodel?: string
cwd?: string
prismaPath?: string
datamodelPath?: string
retry?: number
previewFeatures?: string[]
}
export class GetDmmfError extends Error {
constructor(params: QueryEngineErrorInit) {
const constructedErrorMessage = match(params)
.with({ _tag: 'parsed' }, ({ errorCode, message, reason }) => {
const errorCodeMessage = errorCode ? `Error code: ${errorCode}` : ''
return `${reason}
${errorCodeMessage}
${message}`
})
.with({ _tag: 'unparsed' }, ({ message, reason }) => {
const detailsHeader = chalk.red.bold('Details:')
return `${reason}
${detailsHeader} ${message}`
})
.exhaustive()
const errorMessageWithContext = `${constructedErrorMessage}
[Context: getDmmf]`
super(addVersionDetailsToErrorMessage(errorMessageWithContext))
}
}
/**
* Wasm'd version of `getDMMF`.
*/
export async function getDMMF(options: GetDMMFOptions): Promise<DMMF.Document> {
// TODO: substitute this warning with `prismaFmt.lint()`.
// See https://github.com/prisma/prisma/issues/16538
warnOnDeprecatedFeatureFlag(options.previewFeatures)
const debugErrorType = createDebugErrorType(debug, 'getDmmfWasm')
debug(`Using getDmmf Wasm`)
const dmmfPipeline = pipe(
TE.tryCatch(
() => {
if (options.datamodel) {
debug('Using given datamodel')
return Promise.resolve(options.datamodel)
}
debug(`Reading datamodel from the given datamodel path ${options.datamodelPath!}`)
return fs.promises.readFile(options.datamodelPath!, { encoding: 'utf-8' })
},
(e) =>
({
type: 'read-datamodel-path' as const,
reason: 'Error while trying to read the datamodel path',
error: e as Error,
datamodelPath: options.datamodelPath,
} as const),
),
TE.chainW((datamodel) => {
return pipe(
E.tryCatch(
() => {
if (process.env.FORCE_PANIC_QUERY_ENGINE_GET_DMMF) {
debug('Triggering a Rust panic...')
prismaFmt.debug_panic()
}
const noColor = Boolean(process.env.NO_COLOR)
const params = JSON.stringify({
prismaSchema: datamodel,
noColor,
})
const data = prismaFmt.get_dmmf(params)
return data
},
(e) =>
({
type: 'wasm-error' as const,
reason: '(get-dmmf wasm)',
error: e as Error | WasmPanic,
} as const),
),
E.map((result) => ({ result })),
E.chainW(({ result }) =>
// NOTE: this should never fail, as we expect returned values to be valid JSON-serializable strings
E.tryCatch(
() => JSON.parse(result) as DMMF.Document,
(e) => ({
type: 'parse-json' as const,
reason: 'Unable to parse JSON',
error: e as Error,
}),
),
),
TE.fromEither,
)
}),
)
const dmmfEither = await dmmfPipeline()
if (E.isRight(dmmfEither)) {
debug('dmmf data retrieved without errors in getDmmf Wasm')
const { right: data } = dmmfEither
return Promise.resolve(data)
}
/**
* Check which error to throw.
*/
const error = match(dmmfEither.left)
.with({ type: 'read-datamodel-path' }, (e) => {
debugErrorType(e)
return new GetDmmfError({
_tag: 'unparsed',
message: `${e.error.message}\nDatamodel path: "${e.datamodelPath}"`,
reason: e.reason,
})
})
.with({ type: 'wasm-error' }, (e) => {
debugErrorType(e)
/**
* Capture and propagate possible Wasm panics.
*/
if (isWasmPanic(e.error)) {
const wasmError = e.error
const panic = new RustPanic(
/* message */ wasmError.message,
/* rustStack */ wasmError.stack || 'NO_BACKTRACE',
/* request */ '@prisma/prisma-fmt-wasm get_dmmf',
ErrorArea.FMT_CLI,
/* schemaPath */ options.prismaPath,
/* schema */ options.datamodel,
)
return panic
}
/*
* Extract the actual error by attempting to JSON-parse the error message.
*/
const errorOutput = e.error.message
return new GetDmmfError(parseQueryEngineError({ errorOutput, reason: e.reason }))
})
.with({ type: 'parse-json' }, (e) => {
debugErrorType(e)
return new GetDmmfError({ _tag: 'unparsed', message: e.error.message, reason: e.reason })
})
.exhaustive()
throw error
}
// See also removedFlags at
// https://github.com/prisma/prisma/blob/main/packages/engine-core/src/binary/BinaryEngine.ts#L174
function warnOnDeprecatedFeatureFlag(previewFeatures?: string[]) {
const getMessage = (flag: string) =>
`${chalk.blueBright(
'info',
)} The preview flag "${flag}" is not needed anymore, please remove it from your schema.prisma`
const removedFeatureFlagMap = {
insensitiveFilters: getMessage('insensitiveFilters'),
atomicNumberOperations: getMessage('atomicNumberOperations'),
connectOrCreate: getMessage('connectOrCreate'),
transaction: getMessage('transaction'),
nApi: getMessage('nApi'),
transactionApi: getMessage('transactionApi'),
uncheckedScalarInputs: getMessage('uncheckedScalarInputs'),
nativeTypes: getMessage('nativeTypes'),
createMany: getMessage('createMany'),
groupBy: getMessage('groupBy'),
referentialActions: getMessage('referentialActions'),
microsoftSqlServer: getMessage('microsoftSqlServer'),
selectRelationCount: getMessage('selectRelationCount'),
orderByRelation: getMessage('orderByRelation'),
orderByAggregateGroup: getMessage('orderByAggregateGroup'),
}
previewFeatures?.forEach((f) => {
const removedMessage = removedFeatureFlagMap[f]
if (removedMessage && !process.env.PRISMA_HIDE_PREVIEW_FLAG_WARNINGS) {
console.warn(removedMessage)
}
})
}