/
PrismaClient.ts
427 lines (387 loc) · 13.3 KB
/
PrismaClient.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import type { GeneratorConfig } from '@prisma/generator-helper'
import indent from 'indent-string'
import type { DMMFHelper } from '../../runtime/dmmf'
import { capitalize, lowerCase } from '../../runtime/utils/common'
import type { InternalDatasource } from '../../runtime/utils/printDatasources'
import { runtimeImport } from '../utils/runtimeImport'
import type { DatasourceOverwrite } from './../extractSqliteSources'
import { TAB_SIZE } from './constants'
import { Datasources } from './Datasources'
import type { Generatable } from './Generatable'
function batchingTransactionDefinition(this: PrismaClientClass) {
const args = ['arg: [...P]']
if (this.dmmf.hasEnumInNamespace('TransactionIsolationLevel', 'prisma')) {
args.push('options?: { isolationLevel?: Prisma.TransactionIsolationLevel }')
}
const argsString = args.join(', ')
return `
/**
* Allows the running of a sequence of read/write operations that are guaranteed to either succeed or fail as a whole.
* @example
* \`\`\`
* const [george, bob, alice] = await prisma.$transaction([
* prisma.user.create({ data: { name: 'George' } }),
* prisma.user.create({ data: { name: 'Bob' } }),
* prisma.user.create({ data: { name: 'Alice' } }),
* ])
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/concepts/components/prisma-client/transactions).
*/
$transaction<P extends PrismaPromise<any>[]>(${argsString}): Promise<UnwrapTuple<P>>;`
}
function interactiveTransactionDefinition(this: PrismaClientClass) {
if (!this.generator?.previewFeatures.includes('interactiveTransactions')) {
return ''
}
const txOptions = ['maxWait?: number', 'timeout?: number']
if (this.dmmf.hasEnumInNamespace('TransactionIsolationLevel', 'prisma')) {
txOptions.push('isolationLevel?: Prisma.TransactionIsolationLevel')
}
const optionsType = `{${txOptions.join(', ')}}`
return `
$transaction<R>(fn: (prisma: Prisma.TransactionClient) => Promise<R>, options?: ${optionsType}): Promise<R>;`
}
function queryRawDefinition(this: PrismaClientClass) {
// we do not generate `$queryRaw...` definitions if not supported
if (!this.dmmf.mappings.otherOperations.write.includes('queryRaw')) {
return '' // https://github.com/prisma/prisma/issues/8189
}
return `
/**
* Performs a prepared raw query and returns the \`SELECT\` data.
* @example
* \`\`\`
* const result = await prisma.$queryRaw\`SELECT * FROM User WHERE id = \${1} OR email = \${'user@email.com'};\`
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access).
*/
$queryRaw<T = unknown>(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): PrismaPromise<T>;
/**
* Performs a raw query and returns the \`SELECT\` data.
* Susceptible to SQL injections, see documentation.
* @example
* \`\`\`
* const result = await prisma.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com')
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access).
*/
$queryRawUnsafe<T = unknown>(query: string, ...values: any[]): PrismaPromise<T>;`
}
function executeRawDefinition(this: PrismaClientClass) {
// we do not generate `$executeRaw...` definitions if not supported
if (!this.dmmf.mappings.otherOperations.write.includes('executeRaw')) {
return '' // https://github.com/prisma/prisma/issues/8189
}
return `
/**
* Executes a prepared raw query and returns the number of affected rows.
* @example
* \`\`\`
* const result = await prisma.$executeRaw\`UPDATE User SET cool = \${true} WHERE email = \${'user@email.com'};\`
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access).
*/
$executeRaw<T = unknown>(query: TemplateStringsArray | Prisma.Sql, ...values: any[]): PrismaPromise<number>;
/**
* Executes a raw query and returns the number of affected rows.
* Susceptible to SQL injections, see documentation.
* @example
* \`\`\`
* const result = await prisma.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com')
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access).
*/
$executeRawUnsafe<T = unknown>(query: string, ...values: any[]): PrismaPromise<number>;`
}
function metricDefinition(this: PrismaClientClass) {
if (!this.generator?.previewFeatures.includes('metrics')) {
return ''
}
return `
/**
* Gives access to the client metrics in json or prometheus format.
*
* @example
* \`\`\`
* const metrics = await prisma.$metrics.json()
* // or
* const metrics = await prisma.$metrics.prometheus()
* \`\`\`
*/
readonly $metrics: runtime.${runtimeImport('MetricsClient')};
`
}
function runCommandRawDefinition(this: PrismaClientClass) {
// we do not generate `$runCommandRaw` definitions if not supported
if (!this.dmmf.mappings.otherOperations.write.includes('runCommandRaw')) {
return '' // https://github.com/prisma/prisma/issues/8189
}
return `
/**
* Executes a raw MongoDB command and returns the result of it.
* @example
* \`\`\`
* const user = await prisma.$runCommandRaw({
* aggregate: 'User',
* pipeline: [{ $match: { name: 'Bob' } }, { $project: { email: true, _id: false } }],
* explain: false,
* })
* \`\`\`
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access).
*/
$runCommandRaw(command: Prisma.InputJsonObject): PrismaPromise<Prisma.JsonObject>;`
}
export class PrismaClientClass implements Generatable {
constructor(
protected readonly dmmf: DMMFHelper,
protected readonly internalDatasources: InternalDatasource[],
protected readonly outputDir: string,
protected readonly browser?: boolean,
protected readonly generator?: GeneratorConfig,
protected readonly sqliteDatasourceOverrides?: DatasourceOverwrite[],
protected readonly cwd?: string,
) {}
private get jsDoc(): string {
const { dmmf } = this
const example = dmmf.mappings.modelOperations[0]
return `/**
* ## Prisma Client ʲˢ
*
* Type-safe database client for TypeScript & Node.js
* @example
* \`\`\`
* const prisma = new PrismaClient()
* // Fetch zero or more ${capitalize(example.plural)}
* const ${lowerCase(example.plural)} = await prisma.${lowerCase(example.model)}.findMany()
* \`\`\`
*
*
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client).
*/`
}
public toTSWithoutNamespace(): string {
const { dmmf } = this
return `${this.jsDoc}
export class PrismaClient<
T extends Prisma.PrismaClientOptions = Prisma.PrismaClientOptions,
U = 'log' extends keyof T ? T['log'] extends Array<Prisma.LogLevel | Prisma.LogDefinition> ? Prisma.GetEvents<T['log']> : never : never,
GlobalReject extends Prisma.RejectOnNotFound | Prisma.RejectPerOperation | false | undefined = 'rejectOnNotFound' extends keyof T
? T['rejectOnNotFound']
: false
> {
/**
* @private
*/
private fetcher;
/**
* @private
*/
private readonly dmmf;
/**
* @private
*/
private connectionPromise?;
/**
* @private
*/
private disconnectionPromise?;
/**
* @private
*/
private readonly engineConfig;
/**
* @private
*/
private readonly measurePerformance;
${indent(this.jsDoc, TAB_SIZE)}
constructor(optionsArg ?: Prisma.Subset<T, Prisma.PrismaClientOptions>);
$on<V extends (U | 'beforeExit')>(eventType: V, callback: (event: V extends 'query' ? Prisma.QueryEvent : V extends 'beforeExit' ? () => Promise<void> : Prisma.LogEvent) => void): void;
/**
* Connect with the database
*/
$connect(): Promise<void>;
/**
* Disconnect from the database
*/
$disconnect(): Promise<void>;
/**
* Add a middleware
*/
$use(cb: Prisma.Middleware): void
${[
executeRawDefinition.bind(this)(),
queryRawDefinition.bind(this)(),
batchingTransactionDefinition.bind(this)(),
interactiveTransactionDefinition.bind(this)(),
runCommandRawDefinition.bind(this)(),
metricDefinition.bind(this)(),
]
.join('\n')
.trim()}
${indent(
dmmf.mappings.modelOperations
.filter((m) => m.findMany)
.map((m) => {
const methodName = lowerCase(m.model)
return `\
/**
* \`prisma.${methodName}\`: Exposes CRUD operations for the **${m.model}** model.
* Example usage:
* \`\`\`ts
* // Fetch zero or more ${capitalize(m.plural)}
* const ${lowerCase(m.plural)} = await prisma.${methodName}.findMany()
* \`\`\`
*/
get ${methodName}(): Prisma.${m.model}Delegate<GlobalReject>;`
})
.join('\n\n'),
2,
)}
}`
}
public toTS(): string {
return `${new Datasources(this.internalDatasources).toTS()}
export type RejectOnNotFound = boolean | ((error: Error) => Error)
export type RejectPerModel = { [P in ModelName]?: RejectOnNotFound }
export type RejectPerOperation = { [P in "findUnique" | "findFirst"]?: RejectPerModel | RejectOnNotFound }
type IsReject<T> = T extends true ? True : T extends (err: Error) => Error ? True : False
export type HasReject<
GlobalRejectSettings extends Prisma.PrismaClientOptions['rejectOnNotFound'],
LocalRejectSettings,
Action extends PrismaAction,
Model extends ModelName
> = LocalRejectSettings extends RejectOnNotFound
? IsReject<LocalRejectSettings>
: GlobalRejectSettings extends RejectPerOperation
? Action extends keyof GlobalRejectSettings
? GlobalRejectSettings[Action] extends RejectOnNotFound
? IsReject<GlobalRejectSettings[Action]>
: GlobalRejectSettings[Action] extends RejectPerModel
? Model extends keyof GlobalRejectSettings[Action]
? IsReject<GlobalRejectSettings[Action][Model]>
: False
: False
: False
: IsReject<GlobalRejectSettings>
export type ErrorFormat = 'pretty' | 'colorless' | 'minimal'
export interface PrismaClientOptions {
/**
* Configure findUnique/findFirst to throw an error if the query returns null.
* @deprecated since 4.0.0. Use \`findUniqueOrThrow\`/\`findFirstOrThrow\` methods instead.
* @example
* \`\`\`
* // Reject on both findUnique/findFirst
* rejectOnNotFound: true
* // Reject only on findFirst with a custom error
* rejectOnNotFound: { findFirst: (err) => new Error("Custom Error")}
* // Reject on user.findUnique with a custom error
* rejectOnNotFound: { findUnique: {User: (err) => new Error("User not found")}}
* \`\`\`
*/
rejectOnNotFound?: RejectOnNotFound | RejectPerOperation
/**
* Overwrites the datasource url from your schema.prisma file
*/
datasources?: Datasources
/**
* @default "colorless"
*/
errorFormat?: ErrorFormat
/**
* @example
* \`\`\`
* // Defaults to stdout
* log: ['query', 'info', 'warn', 'error']
*
* // Emit as events
* log: [
* { emit: 'stdout', level: 'query' },
* { emit: 'stdout', level: 'info' },
* { emit: 'stdout', level: 'warn' }
* { emit: 'stdout', level: 'error' }
* ]
* \`\`\`
* Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/logging#the-log-option).
*/
log?: Array<LogLevel | LogDefinition>
}
export type Hooks = {
beforeRequest?: (options: { query: string, path: string[], rootField?: string, typeName?: string, document: any }) => any
}
/* Types for Logging */
export type LogLevel = 'info' | 'query' | 'warn' | 'error'
export type LogDefinition = {
level: LogLevel
emit: 'stdout' | 'event'
}
export type GetLogType<T extends LogLevel | LogDefinition> = T extends LogDefinition ? T['emit'] extends 'event' ? T['level'] : never : never
export type GetEvents<T extends any> = T extends Array<LogLevel | LogDefinition> ?
GetLogType<T[0]> | GetLogType<T[1]> | GetLogType<T[2]> | GetLogType<T[3]>
: never
export type QueryEvent = {
timestamp: Date
query: string
params: string
duration: number
target: string
}
export type LogEvent = {
timestamp: Date
message: string
target: string
}
/* End Types for Logging */
export type PrismaAction =
| 'findUnique'
| 'findMany'
| 'findFirst'
| 'create'
| 'createMany'
| 'update'
| 'updateMany'
| 'upsert'
| 'delete'
| 'deleteMany'
| 'executeRaw'
| 'queryRaw'
| 'aggregate'
| 'count'
| 'runCommandRaw'
| 'findRaw'
/**
* These options are being passed in to the middleware as "params"
*/
export type MiddlewareParams = {
model?: ModelName
action: PrismaAction
args: any
dataPath: string[]
runInTransaction: boolean
}
/**
* The \`T\` type makes sure, that the \`return proceed\` is not forgotten in the middleware implementation
*/
export type Middleware<T = any> = (
params: MiddlewareParams,
next: (params: MiddlewareParams) => Promise<T>,
) => Promise<T>
// tested in getLogLevel.test.ts
export function getLogLevel(log: Array<LogLevel | LogDefinition>): LogLevel | undefined;
${
this.generator?.previewFeatures.includes('interactiveTransactions')
? `
/**
* \`PrismaClient\` proxy available in interactive transactions.
*/
export type TransactionClient = Omit<PrismaClient, '$connect' | '$disconnect' | '$on' | '$transaction' | '$use'>
`
: ''
}`
}
}