import Debug from '@prisma/debug' ; import type { DatasourceOverwrite , Engine , EngineConfig , EngineEventType } from '@prisma/engine-core' ; import { LibraryEngine } from '@prisma/engine-core' ; import { BinaryEngine } from '@prisma/engine-core' ; import { DataProxyEngine } from '@prisma/engine-core' ; import type { DataSource , GeneratorConfig } from '@prisma/generator-helper' ; import { logger } from '@prisma/sdk' ; import { mapPreviewFeatures } from '@prisma/sdk' ; import { tryLoadEnvs } from '@prisma/sdk' ; import { ClientEngineType , getClientEngineType } from '@prisma/sdk' ; import { AsyncResource } from 'async_hooks' ; import fs from 'fs' ; import path from 'path' ; import * as sqlTemplateTag from 'sql-template-tag' ; import { DMMFClass } from './dmmf' ; import { DMMF } from './dmmf-types' ; import { getLogLevel } from './getLogLevel' ; import { mergeBy } from './mergeBy' ; import type { EngineMiddleware , Namespace , QueryMiddleware , QueryMiddlewareParams } from './MiddlewareHandler' ; import { Middlewares } from './MiddlewareHandler' ; import { PrismaClientFetcher } from './PrismaClientFetcher' ; import { makeDocument , transformDocument } from './query' ; import { clientVersion } from './utils/clientVersion' ; import { getOutputTypeName , lowerCase } from './utils/common' ; import { deepSet } from './utils/deep-set' ; import { mssqlPreparedStatement } from './utils/mssqlPreparedStatement' ; import { printJsonWithErrors } from './utils/printJsonErrors' ; import type { InstanceRejectOnNotFound , RejectOnNotFound } from './utils/rejectOnNotFound' ; import { getRejectOnNotFound } from './utils/rejectOnNotFound' ; import { serializeRawParameters } from './utils/serializeRawParameters' ; import { validatePrismaClientOptions } from './utils/validatePrismaClientOptions' ; import { RequestHandler } from './RequestHandler' ; import { PrismaClientValidationError } from '.' ; import type { LoadedEnv } from '@prisma/sdk/dist/utils/tryLoadEnvs' ; import type { InlineDatasources } from '../generation/utils/buildInlineDatasources' ; const debug = Debug ( 'prisma:client' ) ; const ALTER_RE = /^(\s*alter\s)/i ; declare global { var NOT_PRISMA_DATA_PROXY ; } ; ( globalThis = globalThis ) . NOT_PRISMA_DATA_PROXY = true ; function isReadonlyArray ( arg ) { return Array . isArray ( arg ) ; } function checkAlter ( query , values , invalidCall ) { if ( values . length > 0 && ALTER_RE . exec ( query ) ) { throw new Error ( `Running ALTER using ${ invalidCall } is not supported
Using the example below you can still execute your query with Prisma, but please note that it is vulnerable to SQL injection attacks and requires you to take care of input sanitization.

Example:
  await prisma.$executeRawUnsafe(\`ALTER USER prisma WITH PASSWORD '\${password}'\`)

More Information: https://pris.ly/d/execute-raw
` ) ; } } export type ErrorFormat = 'pretty' | 'colorless' | 'minimal' ; export type Datasource = { url ? : string ; } ; export type Datasources = { [ name in string ] : Datasource ; } ; export interface PrismaClientOptions { /**
     * Will throw an Error if findUnique returns null
     */ rejectOnNotFound ? : InstanceRejectOnNotFound ; /**
     * Overwrites the datasource url from your prisma.schema file
     */ datasources ? : Datasources ; default errorFormat ? : ErrorFormat ; example log ? : Array < LogLevel | LogDefinition > ; internal __internal ? : { debug ? : boolean ; hooks ? : Hooks ; useUds ? : boolean ; engine ? : { cwd ? : string ; binaryPath ? : string ; endpoint ? : string ; allowTriggerPanic ? : boolean ; } ; } ; } export type Unpacker = ( data : any ) => any ; export type HookParams = { query : string ; path : string [ ] ; rootField ? : string ; typeName ? : string ; document : any ; clientMethod : string ; args : any ; } ; export type Action = DMMF . ModelAction | 'executeRaw' | 'queryRaw' ; export type InternalRequestParams = { /**
     * The original client method being called.
     * Even though the rootField / operation can be changed,
     * this method stays as it is, as it's what the user's
     * code looks like
     */ clientMethod : string ; callsite ? : string ; headers ? : Record < string , string > ; transactionId ? : number ; unpacker ? : Unpacker ; } & QueryMiddlewareParams ; export type AllHookArgs = { params : HookParams ; fetch : ( params : HookParams ) => Promise < any > ; } ; export type Hooks = { beforeRequest ? : ( options : HookParams ) => any ; } ; 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 Array < LogLevel | LogDefinition > > = GetLogType < T [ 0 ] > | GetLogType < T [ 1 ] > | GetLogType < T [ 2 ] > ; export type QueryEvent = { timestamp : Date ; query : string ; params : string ; duration : number ; target : string ; } ; export type LogEvent = { timestamp : Date ; message : string ; target : string ; } ; /**
 * Config that is stored into the generated client. When the generated client is
 * loaded, this same config is passed to  getPrismaClient which creates a
 * closure with that config around a non-instantiated [[PrismaClient]].
  export interface GetPrismaClientConfig { document : DMMF . Document ; generator ? : GeneratorConfig ; sqliteDatasourceOverrides ? : DatasourceOverwrite [ ] ; relativeEnvPaths : { rootEnvPath ? : string | null ; schemaEnvPath ? : string | null ; } ; relativePath : string ; dirname : string ; filename ? : string ; clientVersion ? : string ; engineVersion ? : string ; datasourceNames : string [ ] ; activeProvider : string ; remarks inlineSchema ? : string ; remarks inlineEnv ? : LoadedEnv ; remarks inlineDatasources ? : InlineDatasources ; remarks inlineSchemaHash ? : string ; } const actionOperationMap = { findUnique : 'query' , findFirst : 'query' , findMany : 'query' , count : 'query' , create : 'mutation' , createMany : 'mutation' , update : 'mutation' , updateMany : 'mutation' , upsert : 'mutation' , delete : 'mutation' , deleteMany : 'mutation' , executeRaw : 'mutation' , queryRaw : 'mutation' , aggregate : 'query' , groupBy : 'query' , } ; const aggregateKeys = { _avg : true , _count : true , _sum : true , _min : true , _max : true , } ; export interface Client { _dmmf : DMMFClass ; _engine : Engine ; _fetcher : PrismaClientFetcher ; _connectionPromise ? : Promise < any > ; _disconnectionPromise ? : Promise < any > ; _engineConfig : EngineConfig ; _clientVersion : string ; _errorFormat : ErrorFormat ; $use < T > ( arg0 , arg1 ? ) ; $on ( eventType , callback ) ; $connect ( ) ; $disconnect ( ) ; _runDisconnect ( ) ; $executeRaw ( query , ... values ) ; $queryRaw ( query , ... values ) ; __internal_triggerPanic ( fatal ) ; $transaction ( input , options ? ) ; } export function getPrismaClient ( config ) { class PrismaClient implements Client { _dmmf : DMMFClass ; _engine : Engine ; _fetcher : PrismaClientFetcher ; _connectionPromise ? : Promise < any > ; _disconnectionPromise ? : Promise < any > ; _engineConfig : EngineConfig ; _clientVersion : string ; _errorFormat : ErrorFormat ; _clientEngineType : ClientEngineType ; private _hooks ? : Hooks ; private _getConfigPromise ? : Promise < { datasources : DataSource [ ] ; generators : GeneratorConfig [ ] ; } > ; private _middlewares : Middlewares = new Middlewares ( ) ; private _previewFeatures : string [ ] ; private _activeProvider : string ; private _transactionId = 1 ; private _rejectOnNotFound ? : InstanceRejectOnNotFound ; constructor ( optionsArg ? ) { if ( optionsArg ) { validatePrismaClientOptions ( optionsArg , config . datasourceNames ) ; } this . _rejectOnNotFound = optionsArg ?. rejectOnNotFound ; this . _clientVersion = config . clientVersion ?? clientVersion ; this . _activeProvider = config . activeProvider ; this . _clientEngineType = getClientEngineType ( config . generator ! ) ; const envPaths = { rootEnvPath : config . relativeEnvPaths . rootEnvPath && path . resolve ( config . dirname , config . relativeEnvPaths . rootEnvPath ) , schemaEnvPath : config . relativeEnvPaths . schemaEnvPath && path . resolve ( config . dirname , config . relativeEnvPaths . schemaEnvPath ) , } ; const loadedEnv = globalThis . NOT_PRISMA_DATA_PROXY && tryLoadEnvs ( envPaths , { conflictCheck : 'none' } ) ; try { const options = optionsArg ?? { } ; const internal = options . __internal ?? { } ; const useDebug = internal . debug === true ; if ( useDebug ) { Debug . enable ( 'prisma:client' ) ; } if ( internal . hooks ) { this . _hooks = internal . hooks ; } let cwd = path . resolve ( config . dirname , config . relativePath ) ; if ( ! fs . existsSync ( cwd ) ) { cwd = config . dirname ; } const thedatasources = options . datasources || { } ; const inputDatasources = Object . entries ( thedatasources ) . filter ( ( [ _ , source ] ) => { return source && source . url ; } ) . map ( ( [ name , { url } ] ) => ( { name , url , } ) ) ; const datasources = mergeBy ( [ ] , inputDatasources , ( source ) => source . name ) ; const engineConfig = internal . engine || { } ; if ( options . errorFormat ) { this . _errorFormat = options . errorFormat ; } else if ( process . env . NODE_ENV === 'production' ) { this . _errorFormat = 'minimal' ; } else if ( process . env . NO_COLOR ) { this . _errorFormat = 'colorless' ; } else { this . _errorFormat = 'colorless' ; } this . _dmmf = new DMMFClass ( config . document ) ; this . _previewFeatures = config . generator ?. previewFeatures ?? [ ] ; this . _engineConfig = { cwd , dirname : config . dirname , enableDebugLogs : useDebug , allowTriggerPanic : engineConfig . allowTriggerPanic , datamodelPath : path . join ( config . dirname , config . filename ?? 'schema.prisma' ) , prismaPath : engineConfig . binaryPath ?? undefined , engineEndpoint : engineConfig . endpoint , datasources , generator : config . generator , showColors : this . _errorFormat === 'pretty' , logLevel : options . log && ( getLogLevel ( options . log ) as any ) , logQueries : options . log && Boolean ( typeof options . log === 'string' ? options . log === 'query' : options . log . find ( ( o ) => ( typeof o === 'string' ? o === 'query' : o . level === 'query' ) ) ) , env : loadedEnv ? loadedEnv . parsed : config . inlineEnv ?. parsed ?? { } , flags : [ ] , clientVersion : config . clientVersion , previewFeatures : mapPreviewFeatures ( this . _previewFeatures ) , useUds : internal . useUds , activeProvider : config . activeProvider , inlineSchema : config . inlineSchema , inlineDatasources : config . inlineDatasources , inlineSchemaHash : config . inlineSchemaHash , } ; if ( config . activeProvider === 'mongodb' ) { const previewFeatures = this . _engineConfig . previewFeatures ? this . _engineConfig . previewFeatures . concat ( 'mongodb' ) : [ 'mongodb' ] ; this . _engineConfig . previewFeatures = previewFeatures ; } debug ( `clientVersion: ${ config . clientVersion }` ) ; debug ( `clientEngineType: ${ this . _clientEngineType }` ) ; this . _engine = this . getEngine ( ) ; void this . _getActiveProvider ( ) ; if ( ! this . _hasPreviewFlag ( 'interactiveTransactions' ) ) { this . _fetcher = new PrismaClientFetcher ( this , false , this . _hooks ) ; } else { this . _fetcher = new RequestHandler ( this , this . _hooks ) as any ; } if ( options . log ) { for ( const log of options . log ) { const level = typeof log === 'string' ? log : log . emit === 'stdout' ? log . level : null ; if ( level ) { this . $on ( level , ( event ) => { logger . log ( `${ logger . tags [ level ] ?? '' }` , event . message || event . query ) ; } ) ; } } } this . _bootstrapClient ( ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } get [ Symbol . toStringTag ] ( ) { return 'PrismaClient' ; } private getEngine ( ) { if ( this . _clientEngineType === ClientEngineType . Library ) { return ( globalThis . NOT_PRISMA_DATA_PROXY && new LibraryEngine ( this . _engineConfig ) ) ; } else if ( this . _clientEngineType === ClientEngineType . Binary ) { return ( globalThis . NOT_PRISMA_DATA_PROXY && new BinaryEngine ( this . _engineConfig ) ) ; } else { return new DataProxyEngine ( this . _engineConfig ) ; } } param middleware $use < T > ( middleware ) ; $use < T > ( namespace , cb ) ; $use < T > ( namespace , cb ) ; $use < T > ( arg0 , arg1 ? ) { if ( typeof arg0 === 'function' ) { this . _middlewares . query . use ( arg0 as QueryMiddleware ) ; } else if ( arg0 === 'all' ) { this . _middlewares . query . use ( arg1 as QueryMiddleware ) ; } else if ( arg0 === 'engine' ) { this . _middlewares . engine . use ( arg1 as EngineMiddleware ) ; } else { throw new Error ( `Invalid middleware ${ arg0 }` ) ; } } $on ( eventType , callback ) { if ( eventType === 'beforeExit' ) { this . _engine . on ( 'beforeExit' , callback ) ; } else { this . _engine . on ( eventType , ( event ) => { const fields = event . fields ; if ( eventType === 'query' ) { return callback ( { timestamp : event . timestamp , query : fields ?. query ?? event . query , params : fields ?. params ?? event . params , duration : fields ?. duration_ms ?? event . duration , target : event . target , } ) ; } else { return callback ( { timestamp : event . timestamp , message : fields ?. message ?? event . message , target : event . target , } ) ; } } ) ; } } $connect ( ) { try { return this . _engine . start ( ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } private async _runDisconnect ( ) { await this . _engine . stop ( ) ; delete this . _connectionPromise ; this . _engine = this . getEngine ( ) ; delete this . _disconnectionPromise ; delete this . _getConfigPromise ; } /**
         * Disconnect from the database
         */ $disconnect ( ) { try { return this . _engine . stop ( ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } private async _getActiveProvider ( ) { try { const configResult = await this . _engine . getConfig ( ) ; this . _activeProvider = configResult . datasources [ 0 ] . activeProvider ; } catch ( e ) { } } /**
         * Executes a raw query. Always returns a number
         */ private $executeRawInternal ( runInTransaction , transactionId , query , ... values ) { let queryString = '' ; let parameters = undefined ; if ( typeof query === 'string' ) { queryString = query ; parameters = { values : serializeRawParameters ( values || [ ] ) , __prismaRawParamaters__ : true , } ; checkAlter ( queryString , values , 'prisma.$executeRawUnsafe(<SQL>, [...values])' ) ; } else if ( isReadonlyArray ( query ) ) { switch ( this . _activeProvider ) { case 'sqlite' : case 'mysql' : { const queryInstance = sqlTemplateTag . sqltag ( query , ... values ) ; queryString = queryInstance . sql ; parameters = { values : serializeRawParameters ( queryInstance . values ) , __prismaRawParamaters__ : true , } ; break ; } case 'cockroachdb' : case 'postgresql' : { const queryInstance = sqlTemplateTag . sqltag ( query , ... values ) ; queryString = queryInstance . text ; checkAlter ( queryString , queryInstance . values , 'prisma.$executeRaw`<SQL>`' ) ; parameters = { values : serializeRawParameters ( queryInstance . values ) , __prismaRawParamaters__ : true , } ; break ; } case 'sqlserver' : { queryString = mssqlPreparedStatement ( query ) ; parameters = { values : serializeRawParameters ( values ) , __prismaRawParamaters__ : true , } ; break ; } default : { throw new Error ( `The ${ this . _activeProvider } provider does not support $executeRaw` ) ; } } } else { switch ( this . _activeProvider ) { case 'sqlite' : case 'mysql' : queryString = query . sql ; break ; case 'cockroachdb' : case 'postgresql' : queryString = query . text ; checkAlter ( queryString , query . values , 'prisma.$executeRaw(sql`<SQL>`)' ) ; break ; case 'sqlserver' : queryString = mssqlPreparedStatement ( query . strings ) ; break ; default : throw new Error ( `The ${ this . _activeProvider } provider does not support $executeRaw` ) ; } parameters = { values : serializeRawParameters ( query . values ) , __prismaRawParamaters__ : true , } ; } if ( parameters ?. values ) { debug ( `prisma.$executeRaw(${ queryString }, ${ parameters . values })` ) ; } else { debug ( `prisma.$executeRaw(${ queryString })` ) ; } const args = { query : queryString , parameters } ; debug ( `Prisma Client call:` ) ; return this . _request ( { args , clientMethod : 'executeRaw' , dataPath : [ ] , action : 'executeRaw' , callsite : this . _getCallsite ( ) , runInTransaction , transactionId : transactionId , } ) ; } /**
         * Executes a raw query and always returns a number
         */ private $executeRawRequest ( query , ... values ) { const request = ( transactionId ? , runInTransaction ? ) => { try { const promise = this . $executeRawInternal ( runInTransaction ?? false , transactionId , query , ... values ) ; ( promise as any ) . isExecuteRaw = true ; return promise ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } ; return createPrismaPromise ( request ) ; } see https param query param values returns $executeRaw ( query , ... values ) { return createPrismaPromise ( ( ) => { if ( ( query as TemplateStringsArray ) . raw || ( query as sqlTemplateTag . Sql ) . sql ) { return this . $executeRawRequest ( query , ... values ) ; } throw new PrismaClientValidationError ( `\`$executeRaw\` is a tag function, please use it like the following:
\`\`\`
const result = await prisma.$executeRaw\`UPDATE User SET cool = \${true} WHERE email = \${'user@email.com'};\`
\`\`\`

Or read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#executeraw
` ) ; } ) ; } see https param query param values returns $executeRawUnsafe ( query , ... values ) { return this . $executeRawRequest ( query , ... values ) ; } private _getCallsite ( ) { if ( this . _errorFormat !== 'minimal' ) { return new Error ( ) . stack ; } return undefined ; } /**
         * Executes a raw query and returns selected data
         */ private $queryRawInternal ( runInTransaction , transactionId , query , ... values ) { let queryString = '' ; let parameters = undefined ; if ( typeof query === 'string' ) { queryString = query ; parameters = { values : serializeRawParameters ( values || [ ] ) , __prismaRawParamaters__ : true , } ; } else if ( isReadonlyArray ( query ) ) { switch ( this . _activeProvider ) { case 'sqlite' : case 'mysql' : { const queryInstance = sqlTemplateTag . sqltag ( query , ... values ) ; queryString = queryInstance . sql ; parameters = { values : serializeRawParameters ( queryInstance . values ) , __prismaRawParamaters__ : true , } ; break ; } case 'cockroachdb' : case 'postgresql' : { const queryInstance = sqlTemplateTag . sqltag ( query as any , ... values ) ; queryString = queryInstance . text ; parameters = { values : serializeRawParameters ( queryInstance . values ) , __prismaRawParamaters__ : true , } ; break ; } case 'sqlserver' : { const queryInstance = sqlTemplateTag . sqltag ( query as any , ... values ) ; queryString = mssqlPreparedStatement ( queryInstance . strings ) ; parameters = { values : serializeRawParameters ( queryInstance . values ) , __prismaRawParamaters__ : true , } ; break ; } default : { throw new Error ( `The ${ this . _activeProvider } provider does not support $queryRaw` ) ; } } } else { switch ( this . _activeProvider ) { case 'sqlite' : case 'mysql' : queryString = query . sql ; break ; case 'cockroachdb' : case 'postgresql' : queryString = query . text ; break ; case 'sqlserver' : queryString = mssqlPreparedStatement ( query . strings ) ; break ; default : { throw new Error ( `The ${ this . _activeProvider } provider does not support $queryRaw` ) ; } } parameters = { values : serializeRawParameters ( query . values ) , __prismaRawParamaters__ : true , } ; } if ( parameters ?. values ) { debug ( `prisma.queryRaw(${ queryString }, ${ parameters . values })` ) ; } else { debug ( `prisma.queryRaw(${ queryString })` ) ; } const args = { query : queryString , parameters } ; debug ( `Prisma Client call:` ) ; return this . _request ( { args , clientMethod : 'queryRaw' , dataPath : [ ] , action : 'queryRaw' , callsite : this . _getCallsite ( ) , runInTransaction , transactionId : transactionId , } ) ; } /**
         * Executes a raw query and returns selected data
         */ private $queryRawRequest ( query , ... values ) { const request = ( transactionId ? , runInTransaction ? ) => { try { const promise = this . $queryRawInternal ( runInTransaction ?? false , transactionId , query , ... values ) ; ( promise as any ) . isQueryRaw = true ; return promise ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } ; return createPrismaPromise ( request ) ; } see https param query param values returns $queryRaw ( query , ... values ) { return createPrismaPromise ( ( ) => { if ( ( query as TemplateStringsArray ) . raw || ( query as sqlTemplateTag . Sql ) . sql ) { return this . $queryRawRequest ( query , ... values ) ; } throw new PrismaClientValidationError ( `\`$queryRaw\` is a tag function, please use it like the following:
\`\`\`
const result = await prisma.$queryRaw\`SELECT * FROM User WHERE id = \${1} OR email = \${'user@email.com'};\`
\`\`\`

Or read our docs at https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw
` ) ; } ) ; } see https param query param values returns $queryRawUnsafe ( query , ... values ) { return this . $queryRawRequest ( query , ... values ) ; } __internal_triggerPanic ( fatal ) { if ( ! this . _engineConfig . allowTriggerPanic ) { throw new Error ( `In order to use .__internal_triggerPanic(), please enable it like so:
new PrismaClient({
  __internal: {
    engine: {
      allowTriggerPanic: true
    }
  }
})` ) ; } const headers = fatal ? { 'X-DEBUG-FATAL' : '1' } : { 'X-DEBUG-NON-FATAL' : '1' } ; return this . _request ( { action : 'queryRaw' , args : { query : 'SELECT 1' , parameters : undefined , } , clientMethod : 'queryRaw' , dataPath : [ ] , runInTransaction : false , headers , callsite : this . _getCallsite ( ) , } ) ; } deprecated private ___getTransactionId ( ) { return this . _transactionId ++ ; } deprecated private async $___transactionInternal ( promises ) { for ( const p of promises ) { if ( ! p ) { throw new Error ( `All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function.` ) ; } if ( ( ! p . requestTransaction || typeof p . requestTransaction !== 'function' ) && ! p ?. isQueryRaw && ! p ?. isExecuteRaw ) { throw new Error ( `All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function.` ) ; } } const transactionId = this . ___getTransactionId ( ) ; const requests = await Promise . all ( promises . map ( ( p ) => { if ( p . requestTransaction ) { return p . requestTransaction ( transactionId ) ; } else { } return p ; } ) ) ; return Promise . all ( requests . map ( ( r ) => { if ( Object . prototype . toString . call ( r ) === '[object Promise]' ) { return r ; } if ( r && typeof r === 'function' ) { return r ( ) ; } return r ; } ) ) ; } deprecated private async $___transaction ( promises ) { try { return this . $___transactionInternal ( promises ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } param input param options returns $transaction ( input , options ? ) { if ( ! this . _hasPreviewFlag ( 'interactiveTransactions' ) ) { return this . $___transaction ( input ) ; } try { return this . _transaction ( input , options ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } param input param options returns private async _transaction ( input , options ? ) { if ( typeof input === 'function' ) { return this . _transactionWithCallback ( input , options ) ; } return this . _transactionWithRequests ( input , options ) ; } param callback param options returns private async _transactionWithCallback ( callback , options ? ) { const info = await this . _engine . transaction ( 'start' , options ) ; let result ; try { result = await callback ( transactionProxy ( this , info . id ) ) ; await this . _engine . transaction ( 'commit' , info ) ; } catch ( e ) { await this . _engine . transaction ( 'rollback' , info ) ; throw e ; } return result ; } param requests param options private async _transactionWithRequests ( requests , options ? ) { return this . _transactionWithCallback ( async ( prisma ) => { const transactionId = prisma [ TX_ID ] ; const _requests = requests . map ( ( request ) => { return new Promise ( ( resolve , reject ) => { ; ( request as any ) . then ( resolve , reject , transactionId ) ; } ) ; } ) ; return Promise . all ( _requests ) ; } , options ) ; } param internalParams param middlewareIndex returns private _request ( internalParams ) { try { const params = { args : internalParams . args , dataPath : internalParams . dataPath , runInTransaction : internalParams . runInTransaction , action : internalParams . action , model : internalParams . model , } ; let index = - 1 ; const consumer = ( changedParams ) => { const nextMiddleware = this . _middlewares . query . get ( ++ index ) ; if ( nextMiddleware ) { return nextMiddleware ( changedParams , consumer ) ; } const changedInternalParams = { ... internalParams , ... changedParams } ; if ( index > 0 && ! this . _hasPreviewFlag ( 'interactiveTransactions' ) ) { delete changedInternalParams [ 'transactionId' ] ; } return this . _executeRequest ( changedInternalParams ) ; } ; if ( globalThis . NOT_PRISMA_DATA_PROXY ) { const resource = new AsyncResource ( 'prisma-client-request' ) ; return resource . runInAsyncScope ( ( ) => consumer ( params ) ) ; } return consumer ( params ) ; } catch ( e ) { e . clientVersion = this . _clientVersion ; throw e ; } } private _executeRequest ( { args , clientMethod , dataPath , callsite , runInTransaction , action , model , headers , transactionId , unpacker , } ) { if ( action !== 'executeRaw' && action !== 'queryRaw' && ! model ) { throw new Error ( `Model missing for action ${ action }` ) ; } if ( ( action === 'executeRaw' || action === 'queryRaw' ) && model ) { throw new Error ( `executeRaw and queryRaw can't be executed on a model basis. The model ${ model } has been provided` ) ; } let rootField ; const operation = actionOperationMap [ action ] ; if ( action === 'executeRaw' || action === 'queryRaw' ) { rootField = action ; } let mapping ; if ( model ) { mapping = this . _dmmf . mappingsMap [ model ] ; if ( ! mapping ) { throw new Error ( `Could not find mapping for model ${ model }` ) ; } rootField = mapping [ action ] ; } if ( operation !== 'query' && operation !== 'mutation' ) { throw new Error ( `Invalid operation ${ operation } for action ${ action }` ) ; } const field = this . _dmmf . rootFieldMap [ rootField ! ] ; if ( ! field ) { throw new Error ( `Could not find rootField ${ rootField } for action ${ action } for model ${ model } on rootType ${ operation }` ) ; } const { isList } = field . outputType ; const typeName = getOutputTypeName ( field . outputType . type ) ; const rejectOnNotFound = getRejectOnNotFound ( action , typeName , args , this . _rejectOnNotFound ) ; let document = makeDocument ( { dmmf : this . _dmmf , rootField : rootField ! , rootTypeName : operation , select : args , } ) ; document . validate ( args , false , clientMethod , this . _errorFormat , callsite ) ; document = transformDocument ( document ) ; if ( Debug . enabled ( 'prisma:client' ) ) { const query = String ( document ) ; debug ( `Prisma Client call:` ) ; debug ( `prisma.${ clientMethod }(${ printJsonWithErrors ( { ast : args , keyPaths : [ ] , valuePaths : [ ] , missingItems : [ ] , } ) })` ) ; debug ( `Generated request:` ) ; debug ( query + '\n' ) ; } return this . _fetcher . request ( { document , clientMethod , typeName , dataPath , rejectOnNotFound , isList , rootField : rootField ! , callsite , showColors : this . _errorFormat === 'pretty' , args , engineHook : this . _middlewares . engine . get ( 0 ) , runInTransaction , headers , transactionId , unpacker , } ) ; } private _bootstrapClient ( ) { const modelClientBuilders = this . _dmmf . mappings . modelOperations . reduce ( ( modelClientBuilders , modelMapping ) => { const lowerCaseModel = lowerCase ( modelMapping . model ) ; const model = this . _dmmf . modelMap [ modelMapping . model ] ; if ( ! model ) { throw new Error ( `Invalid mapping ${ modelMapping . model }, can't find model` ) ; } const ModelClientBuilder = ( { operation , actionName , args , dataPath , modelName , unpacker , } ) => { let requestPromise ; const callsite = this . _getCallsite ( ) ; const request = ( transactionId ? , runInTransaction ? ) => { requestPromise = requestPromise ?? this . _request ( { args , model : modelName ?? model . name , action : actionName , clientMethod : `${ lowerCaseModel }.${ actionName }` , dataPath : dataPath , callsite : callsite , runInTransaction : runInTransaction ?? false , transactionId : transactionId , unpacker , } ) ; return requestPromise ; } ; const modelClient = createPrismaPromise ( request ) ; for ( const field of model . fields . filter ( ( f ) => f . kind === 'object' ) ) { modelClient [ field . name ] = ( fieldArgs ) => { const prefix = dataPath . includes ( 'select' ) ? 'select' : dataPath . includes ( 'include' ) ? 'include' : 'select' ; const newDataPath = [ ... dataPath , prefix , field . name ] ; const newArgs = deepSet ( args , newDataPath , fieldArgs || true ) ; return modelClientBuilders [ field . type as string ] ( { operation , actionName , args : newArgs , dataPath : newDataPath , isList : field . isList , modelName : modelName || model . name , } ) ; } ; } return modelClient ; } ; modelClientBuilders [ model . name ] = ModelClientBuilder ; return modelClientBuilders ; } , { } ) ; for ( const mapping of this . _dmmf . mappings . modelOperations ) { const lowerCaseModel = lowerCase ( mapping . model ) ; const filteredActionsList = { model : true , plural : true , aggregate : true , groupBy : true , } ; const delegate = Object . keys ( mapping ) . reduce ( ( acc , actionName ) => { if ( ! filteredActionsList [ actionName ] ) { const operation = getOperation ( actionName as any ) ; acc [ actionName ] = ( args ) => modelClientBuilders [ mapping . model ] ( { operation , actionName , dataPath : [ ] , args , } ) ; } return acc ; } , { } ) ; delegate . count = ( args ) => { let select ; let unpacker ; if ( args ?. select && typeof args ?. select === 'object' ) { select = { _count : { select : args . select } } ; } else { select = { _count : { select : { _all : true } } } ; unpacker = ( data ) => { data . _count = data . _count ?. _all ; return data ; } ; } return modelClientBuilders [ mapping . model ] ( { operation : 'query' , actionName : `aggregate` , args : { ... ( args ?? { } ) , select , } , dataPath : [ '_count' ] , unpacker , } ) ; } ; delegate . aggregate = ( args ) => { /**
                     * _avg, _count, _sum, _min, _max need to go into select
                     * For speed reasons we can go with "for in "
                     */ let unpacker = undefined ; const select = Object . entries ( args ) . reduce ( ( acc , [ key , value ] ) => { if ( aggregateKeys [ key ] ) { if ( ! acc . select ) { acc . select = { } ; } if ( key === '_count' || key === 'count' ) { if ( typeof value === 'object' && value ) { acc . select [ key ] = { select : value } ; } else { acc . select [ key ] = { select : { _all : value } } ; unpacker = ( data ) => { if ( data . _count ) { data . _count = data . _count ?. _all ; } else if ( data . count ) { data . count = data . count ?. _all ; } return data ; } ; } } else { acc . select [ key ] = { select : value } ; } } else { acc [ key ] = value ; } return acc ; } , { } as any ) ; return modelClientBuilders [ mapping . model ] ( { operation : 'query' , actionName : 'aggregate' , rootField : mapping . aggregate , args : select , dataPath : [ ] , unpacker , } ) ; } ; delegate . groupBy = ( args ) => { let unpacker = undefined ; /**
                     * _avg, _count, _sum, _min, _max need to go into select
                     * For speed reasons we can go with "for in "
                     */ const select = Object . entries ( args ) . reduce ( ( acc , [ key , value ] ) => { if ( aggregateKeys [ key ] ) { if ( ! acc . select ) { acc . select = { } ; } acc . select [ key ] = { select : value } ; } else { acc [ key ] = value ; } if ( key === '_count' ) { if ( typeof value === 'object' && value ) { acc . select [ key ] = { select : value } ; } else if ( typeof value === 'boolean' ) { acc . select [ key ] = { select : { _all : value } } ; unpacker = ( data ) => { if ( Array . isArray ( data ) ) { data = data . map ( ( row ) => { if ( row && typeof row . _count === 'object' && row . _count ?. _all ) { row . _count = row . _count ?. _all ; } return row ; } ) ; } return data ; } ; } } if ( key === 'by' && Array . isArray ( value ) && value . length > 0 ) { if ( ! acc . select ) { acc . select = { } ; } for ( const by of value ) { acc . select [ by ] = true ; } } return acc ; } , { } as any ) ; return modelClientBuilders [ mapping . model ] ( { operation : 'query' , actionName : 'groupBy' , rootField : mapping . groupBy , args : select , dataPath : [ ] , unpacker , } ) ; } ; this [ lowerCaseModel ] = delegate ; } } param feature returns private _hasPreviewFlag ( feature ) { return ! ! this . _engineConfig . previewFeatures ?. includes ( feature ) ; } } return PrismaClient as new ( optionsArg ? ) => Client ; } const TX_ID = Symbol . for ( 'prisma.client.transaction.id' ) ; const forbidden = [ '$connect' , '$disconnect' , '$on' , '$transaction' , '$use' ] ; param thing param transactionId returns function transactionProxy < T > ( thing , transactionId ) { if ( typeof thing !== 'object' ) return thing ; return new Proxy ( thing as any as object , { get : ( target , prop ) => { if ( forbidden . includes ( prop as string ) ) return undefined ; if ( prop === TX_ID ) return transactionId ; if ( typeof target [ prop ] === 'function' ) { return ( ... args ) => { if ( prop === 'then' ) { return target [ prop ] ( ... args , transactionId ) ; } return transactionProxy ( target [ prop ] ( ... args ) , transactionId ) ; } ; } return transactionProxy ( target [ prop ] , transactionId ) ; } , } ) as any as T ; } see interface PrismaPromise < A > extends Promise < A > { param onfulfilled param onrejected param transactionId then < R1 = A , R2 = never > ( onfulfilled ? , onrejected ? , transactionId ? ) : Promise < R1 | R2 > ; param id requestTransaction ? ( id ) : PromiseLike < unknown > ; } param callback see returns function createPrismaPromise ( callback ) { const _callback = ( transactionId ? , runInTransaction ? ) => { try { return callback ( transactionId , runInTransaction ) ; } catch ( error ) { return Promise . reject ( error ) as PrismaPromise < unknown > ; } } ; return { then ( onFulfilled , onRejected , transactionId ? ) { const promise = _callback ( transactionId , false ) ; return promise . then ( onFulfilled , onRejected , transactionId ) ; } , catch ( onRejected ) { return _callback ( ) . catch ( onRejected ) ; } , finally ( onFinally ) { return _callback ( ) . finally ( onFinally ) ; } , requestTransaction ( transactionId ) { const promise = _callback ( transactionId , true ) ; if ( promise . requestTransaction ) { return promise . requestTransaction ( transactionId ) ; } return promise ; } , [ Symbol . toStringTag ] : 'PrismaPromise' , } ; } export function getOperation ( action ) { if ( action === DMMF . ModelAction . findMany || action === DMMF . ModelAction . findUnique || action === DMMF . ModelAction . findFirst ) { return 'query' ; } return 'mutation' ; }