diff --git a/.prettierrc.yml b/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/.prettierrc.yml +++ b/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/cli/.prettierrc.yml b/packages/cli/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/cli/.prettierrc.yml +++ b/packages/cli/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/cli/helpers/build.ts b/packages/cli/helpers/build.ts index bf2fdfcbda82..396587459b94 100644 --- a/packages/cli/helpers/build.ts +++ b/packages/cli/helpers/build.ts @@ -47,29 +47,19 @@ const cliLifecyclePlugin: esbuild.Plugin = { build.onEnd(async () => { // we copy the contents from @prisma/studio to build - copySync( - path.join(require.resolve('@prisma/studio/package.json'), '../dist'), - './build/public', - { - recursive: true, - overwrite: true, - }, - ) + copySync(path.join(require.resolve('@prisma/studio/package.json'), '../dist'), './build/public', { + recursive: true, + overwrite: true, + }) // we copy the contents from checkpoint-client to build await copyFile( - path.join( - require.resolve('checkpoint-client/package.json'), - '../dist/child.js', - ), + path.join(require.resolve('checkpoint-client/package.json'), '../dist/child.js'), './build/child.js', ) // we copy the contents from xdg-open to build - await copyFile( - path.join(require.resolve('open/package.json'), '../xdg-open'), - './build/xdg-open', - ) + await copyFile(path.join(require.resolve('open/package.json'), '../xdg-open'), './build/xdg-open') await replaceFirstLine('./build/index.js', '#!/usr/bin/env node\n') diff --git a/packages/cli/helpers/copy-prisma-client.ts b/packages/cli/helpers/copy-prisma-client.ts index 5f261036755d..6f223d7718e1 100644 --- a/packages/cli/helpers/copy-prisma-client.ts +++ b/packages/cli/helpers/copy-prisma-client.ts @@ -9,9 +9,7 @@ const clientPath = path.dirname(require.resolve('@prisma/client')) const clientPkg = require('@prisma/client/package.json') // we compute the paths of the files that would get npm published -const clientFiles = (clientPkg.files ?? []).map((file: string) => - path.join(clientPath, file), -) +const clientFiles = (clientPkg.files ?? []).map((file: string) => path.join(clientPath, file)) // we copy each file that we found in pkg to a new destination for (const file of clientFiles) { diff --git a/packages/cli/src/CLI.ts b/packages/cli/src/CLI.ts index 4c4ea62fada3..30bb44ac937d 100644 --- a/packages/cli/src/CLI.ts +++ b/packages/cli/src/CLI.ts @@ -1,13 +1,6 @@ import chalk from 'chalk' import type { Command, Commands } from '@prisma/sdk' -import { - arg, - isError, - format, - HelpError, - unknownCommand, - logger, -} from '@prisma/sdk' +import { arg, isError, format, HelpError, unknownCommand, logger } from '@prisma/sdk' import { Version } from './Version' import { link } from '@prisma/sdk' import { ensureBinariesExist } from '@prisma/engines' @@ -19,10 +12,7 @@ export class CLI implements Command { static new(cmds: Commands, ensureBinaries: string[]): CLI { return new CLI(cmds, ensureBinaries) } - private constructor( - private readonly cmds: Commands, - private readonly ensureBinaries: string[], - ) {} + private constructor(private readonly cmds: Commands, private readonly ensureBinaries: string[]) {} async parse(argv: string[]): Promise { const args = arg(argv, { @@ -55,20 +45,14 @@ export class CLI implements Command { const cmdName = args._[0] // Throw if "lift" if (cmdName === 'lift') { - throw new Error( - `${chalk.red('prisma lift')} has been renamed to ${chalk.green( - 'prisma migrate', - )}`, - ) + throw new Error(`${chalk.red('prisma lift')} has been renamed to ${chalk.green('prisma migrate')}`) } // warn if "introspect" else if (cmdName === 'introspect') { logger.warn('') logger.warn( `${chalk.bold( - `The ${chalk.underline( - 'prisma introspect', - )} command is deprecated. Please use ${chalk.green( + `The ${chalk.underline('prisma introspect')} command is deprecated. Please use ${chalk.green( 'prisma db pull', )} instead.`, )}`, @@ -85,20 +69,11 @@ export class CLI implements Command { let argsForCmd: string[] if (args['--experimental']) { - argsForCmd = [ - ...args._.slice(1), - `--experimental=${args['--experimental']}`, - ] + argsForCmd = [...args._.slice(1), `--experimental=${args['--experimental']}`] } else if (args['--preview-feature']) { - argsForCmd = argsForCmd = [ - ...args._.slice(1), - `--preview-feature=${args['--preview-feature']}`, - ] + argsForCmd = argsForCmd = [...args._.slice(1), `--preview-feature=${args['--preview-feature']}`] } else if (args['--early-access-feature']) { - argsForCmd = argsForCmd = [ - ...args._.slice(1), - `--early-access-feature=${args['--early-access-feature']}`, - ] + argsForCmd = argsForCmd = [...args._.slice(1), `--early-access-feature=${args['--early-access-feature']}`] } else { argsForCmd = args._.slice(1) } @@ -119,9 +94,7 @@ export class CLI implements Command { private static help = format(` ${ process.platform === 'win32' ? '' : chalk.bold.green('ā—­ ') - }Prisma is a modern DB toolkit to query, migrate and model your database (${link( - 'https://prisma.io', - )}) + }Prisma is a modern DB toolkit to query, migrate and model your database (${link('https://prisma.io')}) ${chalk.bold('Usage')} diff --git a/packages/cli/src/Dev.ts b/packages/cli/src/Dev.ts index 3bdad1451e20..64313dc57f46 100644 --- a/packages/cli/src/Dev.ts +++ b/packages/cli/src/Dev.ts @@ -10,18 +10,14 @@ export class Dev implements Command { // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars async parse(argv: string[]): Promise { return format(` - ${chalk.redBright( - 'Prisma CLI does not include a `dev` command any more right now.', - )} + ${chalk.redBright('Prisma CLI does not include a `dev` command any more right now.')} If you want to run Prisma Studio, use ${chalk.green('prisma studio')}. - If you want to generate the Prisma Client, use ${chalk.green( - 'prisma generate', - )} (or ${chalk.green('prisma generate --watch')}) + If you want to generate the Prisma Client, use ${chalk.green('prisma generate')} (or ${chalk.green( + 'prisma generate --watch', + )}) If you want to update your schema, use ${chalk.green('prisma db pull')}. - If you want to migrate your database, use ${chalk.green( - 'prisma migrate', - )}. + If you want to migrate your database, use ${chalk.green('prisma migrate')}. `) } } diff --git a/packages/cli/src/Doctor.ts b/packages/cli/src/Doctor.ts index f939d5cbf2bf..0bfb45f0168d 100644 --- a/packages/cli/src/Doctor.ts +++ b/packages/cli/src/Doctor.ts @@ -81,11 +81,7 @@ ${chalk.bold('Examples')} ) } - console.log( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.log(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) const schema = await readFile(schemaPath, 'utf-8') const localDmmf = await getDMMF({ datamodel: schema }) @@ -94,10 +90,7 @@ ${chalk.bold('Examples')} console.error(`šŸ‘©ā€āš•ļøšŸ„ Prisma Doctor checking the database...`) const connectionString = config.datasources[0].url - const canConnect = await canConnectToDatabase( - connectionString.value, - path.dirname(schemaPath), - ) + const canConnect = await canConnectToDatabase(connectionString.value, path.dirname(schemaPath)) if (typeof canConnect !== 'boolean') { throw new Error(`${canConnect.code}: ${canConnect.message}`) } @@ -116,18 +109,14 @@ ${chalk.bold('Examples')} const remoteDmmf = await getDMMF({ datamodel }) - const remoteModels = keyBy( - remoteDmmf.datamodel.models, - (m) => m.dbName ?? m.name, - ) + const remoteModels = keyBy(remoteDmmf.datamodel.models, (m) => m.dbName ?? m.name) const modelPairs = localDmmf.datamodel.models.map((localModel) => ({ localModel, remoteModel: remoteModels[localModel.dbName ?? localModel.name], })) - const getFieldName = (f: DMMF.Field) => - f.dbNames && f.dbNames.length > 0 ? f.dbNames[0] : f.name + const getFieldName = (f: DMMF.Field) => (f.dbNames && f.dbNames.length > 0 ? f.dbNames[0] : f.name) const messages: string[] = [] @@ -145,12 +134,7 @@ ${chalk.bold('Examples')} const remoteField = remoteFields[getFieldName(localField)] if (!remoteField) { missingFields.push(localField) - } else if ( - !equal( - pick(localField, ['type', 'isList']), - pick(remoteField, ['type', 'isList']), - ) - ) { + } else if (!equal(pick(localField, ['type', 'isList']), pick(remoteField, ['type', 'isList']))) { incorrectFieldType.push({ localField, remoteField }) } } @@ -194,11 +178,7 @@ function printModelMessage({ missingFields: DMMF.Field[] incorrectFieldType: IncorrectFieldTypes }) { - if ( - !missingModel && - missingFields.length === 0 && - incorrectFieldType.length === 0 - ) { + if (!missingModel && missingFields.length === 0 && incorrectFieldType.length === 0) { return null } let msg = `${chalk.bold.underline(model.name)}\n` diff --git a/packages/cli/src/Format.ts b/packages/cli/src/Format.ts index c63d71912e6b..3ff9bab2d5dd 100644 --- a/packages/cli/src/Format.ts +++ b/packages/cli/src/Format.ts @@ -1,12 +1,5 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - formatSchema, - getDMMF, - getSchemaPath, - HelpError, -} from '@prisma/sdk' +import { arg, format, formatSchema, getDMMF, getSchemaPath, HelpError } from '@prisma/sdk' import chalk from 'chalk' import fs from 'fs' import os from 'os' @@ -74,11 +67,7 @@ Or specify a Prisma schema path ) } - console.log( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.log(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) let output = await formatSchema({ schemaPath, @@ -93,9 +82,7 @@ Or specify a Prisma schema path fs.writeFileSync(schemaPath, output) const after = Date.now() - return `Formatted ${chalk.underline(schemaPath)} in ${formatms( - after - before, - )} šŸš€` + return `Formatted ${chalk.underline(schemaPath)} in ${formatms(after - before)} šŸš€` } public help(error?: string): string | HelpError { diff --git a/packages/cli/src/Generate.ts b/packages/cli/src/Generate.ts index 23098ef0f701..a8f80d217bfa 100644 --- a/packages/cli/src/Generate.ts +++ b/packages/cli/src/Generate.ts @@ -62,50 +62,41 @@ ${chalk.bold('Examples')} private logText = '' private hasGeneratorErrored = false - private runGenerate = simpleDebounce( - async ({ generators }: { generators: Generator[] }) => { - const message: string[] = [] - - for (const generator of generators) { - const toStr = generator.options!.generator.output! - ? chalk.dim( - ` to .${path.sep}${path.relative( - process.cwd(), - parseEnvValue(generator.options!.generator.output!), - )}`, - ) - : '' - const name = generator.manifest - ? generator.manifest.prettyName - : generator.options!.generator.provider - const before = Date.now() - try { - await generator.generate() - const after = Date.now() - const version = generator.manifest?.version + private runGenerate = simpleDebounce(async ({ generators }: { generators: Generator[] }) => { + const message: string[] = [] + + for (const generator of generators) { + const toStr = generator.options!.generator.output! + ? chalk.dim( + ` to .${path.sep}${path.relative(process.cwd(), parseEnvValue(generator.options!.generator.output!))}`, + ) + : '' + const name = generator.manifest ? generator.manifest.prettyName : generator.options!.generator.provider + const before = Date.now() + try { + await generator.generate() + const after = Date.now() + const version = generator.manifest?.version + message.push( + `āœ” Generated ${chalk.bold(name!)}${version ? ` (${version})` : ''}${toStr} in ${formatms(after - before)}\n`, + ) + generator.stop() + } catch (err) { + this.hasGeneratorErrored = true + generator.stop() + // This is an error received when the the client < 2.20 and the cli >= 2.20, This was caused by a breaking change in the generators + if (err.message.includes('outputDir.endsWith is not a function')) { message.push( - `āœ” Generated ${chalk.bold(name!)}${ - version ? ` (${version})` : '' - }${toStr} in ${formatms(after - before)}\n`, + `This combination of Prisma CLI (>= 2.20) and Prisma Client (< 2.20) is not supported. Please update \`@prisma/client\` to ${pkg.version} \n\n`, ) - generator.stop() - } catch (err) { - this.hasGeneratorErrored = true - generator.stop() - // This is an error received when the the client < 2.20 and the cli >= 2.20, This was caused by a breaking change in the generators - if (err.message.includes('outputDir.endsWith is not a function')) { - message.push( - `This combination of Prisma CLI (>= 2.20) and Prisma Client (< 2.20) is not supported. Please update \`@prisma/client\` to ${pkg.version} \n\n`, - ) - } else { - message.push(`${err.message}\n\n`) - } + } else { + message.push(`${err.message}\n\n`) } } + } - this.logText += message.join('\n') - }, - ) + this.logText += message.join('\n') + }) public async parse(argv: string[]): Promise { const args = arg(argv, { @@ -153,11 +144,7 @@ If you do not have a Prisma schema file yet, you can ignore this message.`) ) } - logger.log( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + logger.log(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) let hasJsClient let generators: Generator[] | undefined @@ -175,9 +162,7 @@ If you do not have a Prisma schema file yet, you can ignore this message.`) } 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', + (g) => g.options && parseEnvValue(g.options.generator.provider) === 'prisma-client-js', ) clientGeneratorVersion = jsClient?.manifest?.version ?? null @@ -211,10 +196,7 @@ Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`) try { const clientVersionBeforeGenerate = getCurrentClientVersion() - if ( - clientVersionBeforeGenerate && - typeof clientVersionBeforeGenerate === 'string' - ) { + if (clientVersionBeforeGenerate && typeof clientVersionBeforeGenerate === 'string') { const [major, minor] = clientVersionBeforeGenerate.split('.') if (parseInt(major) == 2 && parseInt(minor) < 12) { @@ -232,27 +214,17 @@ Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`) Please run \`prisma generate\` manually.` } - const watchingText = `\n${chalk.green('Watching...')} ${chalk.dim( - schemaPath, - )}\n` + const watchingText = `\n${chalk.green('Watching...')} ${chalk.dim(schemaPath)}\n` if (!watchMode) { const prismaClientJSGenerator = generators?.find( - (g) => - g.options?.generator.provider && - parseEnvValue(g.options?.generator.provider) === 'prisma-client-js', + (g) => g.options?.generator.provider && parseEnvValue(g.options?.generator.provider) === 'prisma-client-js', ) let hint = '' if (prismaClientJSGenerator) { - const importPath = prismaClientJSGenerator.options?.generator - ?.isCustomOutput + const importPath = prismaClientJSGenerator.options?.generator?.isCustomOutput ? prefixRelativePathIfNecessary( - path.relative( - process.cwd(), - parseEnvValue( - prismaClientJSGenerator.options.generator.output!, - ), - ), + path.relative(process.cwd(), parseEnvValue(prismaClientJSGenerator.options.generator.output!)), ) : '@prisma/client' const breakingChangesStr = printBreakingChangesMessage @@ -261,32 +233,24 @@ Please run \`prisma generate\` manually.` ${breakingChangesMessage}` : '' - const versionsOutOfSync = - clientGeneratorVersion && pkg.version !== clientGeneratorVersion + const versionsOutOfSync = clientGeneratorVersion && pkg.version !== clientGeneratorVersion const versionsWarning = versionsOutOfSync && logger.should.warn - ? `\n\n${chalk.yellow.bold('warn')} Versions of ${chalk.bold( - `prisma@${pkg.version}`, - )} and ${chalk.bold( + ? `\n\n${chalk.yellow.bold('warn')} Versions of ${chalk.bold(`prisma@${pkg.version}`)} and ${chalk.bold( `@prisma/client@${clientGeneratorVersion}`, )} don't match. This might lead to unexpected behavior. Please make sure they have the same version.` : '' - hint = `You can now start using Prisma Client in your code. Reference: ${link( - 'https://pris.ly/d/client', - )} + hint = `You can now start using Prisma Client in your code. Reference: ${link('https://pris.ly/d/client')} ${chalk.dim('```')} ${highlightTS(`\ import { PrismaClient } from '${importPath}' const prisma = new PrismaClient()`)} ${chalk.dim('```')}${breakingChangesStr}${versionsWarning}` } - const message = - '\n' + - this.logText + - (hasJsClient && !this.hasGeneratorErrored ? hint : '') + const message = '\n' + this.logText + (hasJsClient && !this.hasGeneratorErrored ? hint : '') if (this.hasGeneratorErrored) { if (isPostinstall) { @@ -343,9 +307,7 @@ Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`) // help message public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${Generate.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${Generate.help}`) } return Generate.help } @@ -363,10 +325,7 @@ 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', - ) + const potentialPkgPath = path.join(process.cwd(), 'node_modules/.prisma/client') if (fs.existsSync(potentialPkgPath)) { pkgPath = potentialPkgPath } @@ -375,10 +334,7 @@ function getCurrentClientVersion(): string | null { const indexPath = path.join(pkgPath, 'index.js') if (fs.existsSync(indexPath)) { const program = require(indexPath) - return ( - program?.prismaVersion?.client ?? - program?.Prisma?.prismaVersion?.client - ) + return program?.prismaVersion?.client ?? program?.Prisma?.prismaVersion?.client } } } catch (e) { diff --git a/packages/cli/src/Init.ts b/packages/cli/src/Init.ts index 69f9b88fe491..b3efe2b3b3bc 100644 --- a/packages/cli/src/Init.ts +++ b/packages/cli/src/Init.ts @@ -1,13 +1,5 @@ import type { Command } from '@prisma/sdk' -import { - arg, - canConnectToDatabase, - format, - getCommandWithExecutor, - HelpError, - link, - logger, -} from '@prisma/sdk' +import { arg, canConnectToDatabase, format, getCommandWithExecutor, HelpError, link, logger } from '@prisma/sdk' import { protocolToConnectorType } from '@prisma/sdk/dist/convertCredentials' import type { ConnectorType } from '@prisma/generator-helper' import chalk from 'chalk' @@ -79,11 +71,7 @@ export const defaultPort = (provider: ConnectorType) => { return undefined } -export const defaultURL = ( - provider: ConnectorType, - port = defaultPort(provider), - schema = 'public', -) => { +export const defaultURL = (provider: ConnectorType, port = defaultPort(provider), schema = 'public') => { switch (provider) { case 'postgresql': return `postgresql://johndoe:randompassword@localhost:${port}/mydb?schema=${schema}` @@ -131,9 +119,7 @@ export class Init implements Command { ${chalk.dim('$')} prisma init --datasource-provider mysql Setup a new Prisma project and specify the url that will be used - ${chalk.dim( - '$', - )} prisma init --url mysql://user:password@localhost:3306/mydb + ${chalk.dim('$')} prisma init --url mysql://user:password@localhost:3306/mydb `) // eslint-disable-next-line @typescript-eslint/require-await @@ -163,9 +149,7 @@ export class Init implements Command { if (fs.existsSync(path.join(outputDir, 'schema.prisma'))) { console.log( - printError(`File ${chalk.bold( - 'schema.prisma', - )} already exists in your project. + printError(`File ${chalk.bold('schema.prisma')} already exists in your project. Please try again in a project that is not yet using Prisma. `), ) @@ -174,9 +158,7 @@ export class Init implements Command { if (fs.existsSync(prismaFolder)) { console.log( - printError(`A folder called ${chalk.bold( - 'prisma', - )} already exists in your project. + printError(`A folder called ${chalk.bold('prisma')} already exists in your project. Please try again in a project that is not yet using Prisma. `), ) @@ -185,9 +167,7 @@ export class Init implements Command { if (fs.existsSync(path.join(prismaFolder, 'schema.prisma'))) { console.log( - printError(`File ${chalk.bold( - 'prisma/schema.prisma', - )} already exists in your project. + printError(`File ${chalk.bold('prisma/schema.prisma')} already exists in your project. Please try again in a project that is not yet using Prisma. `), ) @@ -216,11 +196,7 @@ export class Init implements Command { url = args['--url'] } else if (args['--datasource-provider']) { const providerLowercase = args['--datasource-provider'].toLowerCase() - if ( - !['postgresql', 'mysql', 'sqlserver', 'sqlite', 'mongodb'].includes( - providerLowercase, - ) - ) { + if (!['postgresql', 'mysql', 'sqlserver', 'sqlite', 'mongodb'].includes(providerLowercase)) { throw new Error( `Provider "${args['--datasource-provider']}" is invalid or not supported. Try again with "postgresql", "mysql", "sqlite", "sqlserver" or "mongodb".`, ) @@ -244,10 +220,7 @@ export class Init implements Command { fs.mkdirSync(prismaFolder) } - fs.writeFileSync( - path.join(prismaFolder, 'schema.prisma'), - defaultSchema(provider), - ) + fs.writeFileSync(path.join(prismaFolder, 'schema.prisma'), defaultSchema(provider)) const warnings: string[] = [] const envPath = path.join(outputDir, '.env') @@ -258,17 +231,12 @@ export class Init implements Command { const config = dotenv.parse(envFile) // will return an object if (Object.keys(config).includes('DATABASE_URL')) { warnings.push( - `${chalk.yellow( - 'warn', - )} Prisma would have added DATABASE_URL but it already exists in ${chalk.bold( + `${chalk.yellow('warn')} Prisma would have added DATABASE_URL but it already exists in ${chalk.bold( path.relative(outputDir, envPath), )}`, ) } else { - fs.appendFileSync( - envPath, - `\n\n` + '# This was inserted by `prisma init`:\n' + defaultEnv(url), - ) + fs.appendFileSync(envPath, `\n\n` + '# This was inserted by `prisma init`:\n' + defaultEnv(url)) } } @@ -308,15 +276,11 @@ export class Init implements Command { if (!url || args['--datasource-provider']) { if (!args['--datasource-provider']) { steps.unshift( - `Set the ${chalk.green('provider')} of the ${chalk.green( - 'datasource', - )} block in ${chalk.green( + `Set the ${chalk.green('provider')} of the ${chalk.green('datasource')} block in ${chalk.green( 'schema.prisma', - )} to match your database: ${chalk.green( - 'postgresql', - )}, ${chalk.green('mysql')}, ${chalk.green('sqlite')}, ${chalk.green( - 'sqlserver', - )} or ${chalk.green('mongodb')} (Preview).`, + )} to match your database: ${chalk.green('postgresql')}, ${chalk.green('mysql')}, ${chalk.green( + 'sqlite', + )}, ${chalk.green('sqlserver')} or ${chalk.green('mongodb')} (Preview).`, ) } diff --git a/packages/cli/src/Studio.ts b/packages/cli/src/Studio.ts index 0d738cfc3c22..b8f850b796f5 100644 --- a/packages/cli/src/Studio.ts +++ b/packages/cli/src/Studio.ts @@ -92,15 +92,10 @@ ${chalk.bold('Examples')} ) } - console.log( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.log(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) const hostname = args['--hostname'] - const port = - args['--port'] || (await getPort({ port: getPort.makeRange(5555, 5600) })) + const port = args['--port'] || (await getPort({ port: getPort.makeRange(5555, 5600) })) const browser = args['--browser'] || process.env.BROWSER const staticAssetDir = path.resolve(__dirname, '../build/public') @@ -112,10 +107,7 @@ ${chalk.bold('Examples')} staticAssetDir, prismaClient: { resolve: { - '@prisma/client': path.resolve( - __dirname, - '../prisma-client/index.js', - ), + '@prisma/client': path.resolve(__dirname, '../prisma-client/index.js'), '@prisma/engines': require.resolve('@prisma/engines'), }, }, diff --git a/packages/cli/src/Validate.ts b/packages/cli/src/Validate.ts index 9ba0af1f3169..e925672d26b4 100644 --- a/packages/cli/src/Validate.ts +++ b/packages/cli/src/Validate.ts @@ -1,12 +1,5 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getConfig, - getDMMF, - getSchemaPath, - HelpError, -} from '@prisma/sdk' +import { arg, format, getConfig, getDMMF, getSchemaPath, HelpError } from '@prisma/sdk' import chalk from 'chalk' import fs from 'fs' import path from 'path' @@ -71,11 +64,7 @@ ${chalk.bold('Examples')} ) } - console.log( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.log(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) const schema = fs.readFileSync(schemaPath, 'utf-8') @@ -93,9 +82,7 @@ ${chalk.bold('Examples')} // help message public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${Validate.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${Validate.help}`) } return Validate.help } diff --git a/packages/cli/src/Version.ts b/packages/cli/src/Version.ts index 231a24bd9e11..306784b065e4 100644 --- a/packages/cli/src/Version.ts +++ b/packages/cli/src/Version.ts @@ -68,9 +68,7 @@ export class Version implements Command { const platform = await getPlatform() const cliQueryEngineBinaryType = getCliQueryEngineBinaryType() - const introspectionEngine = await this.resolveEngine( - BinaryType.introspectionEngine, - ) + const introspectionEngine = await this.resolveEngine(BinaryType.introspectionEngine) const migrationEngine = await this.resolveEngine(BinaryType.migrationEngine) // TODO This conditional does not really belong here, CLI should be able to tell you which engine it is _actually_ using const queryEngine = await this.resolveEngine(cliQueryEngineBinaryType) @@ -83,20 +81,13 @@ export class Version implements Command { ['@prisma/client', prismaClientVersion ?? 'Not found'], ['Current platform', platform], [ - `Query Engine${ - cliQueryEngineBinaryType === BinaryType.libqueryEngine - ? ' (Node-API)' - : ' (Binary)' - }`, + `Query Engine${cliQueryEngineBinaryType === BinaryType.libqueryEngine ? ' (Node-API)' : ' (Binary)'}`, this.printBinaryInfo(queryEngine), ], ['Migration Engine', this.printBinaryInfo(migrationEngine)], ['Introspection Engine', this.printBinaryInfo(introspectionEngine)], ['Format Binary', this.printBinaryInfo(fmtBinary)], - [ - 'Default Engines Hash', - packageJson.dependencies['@prisma/engines'].split('.').pop(), - ], + ['Default Engines Hash', packageJson.dependencies['@prisma/engines'].split('.').pop()], ['Studio', packageJson.devDependencies['@prisma/studio-server']], ] @@ -120,9 +111,7 @@ export class Version implements Command { const config = await getConfig({ datamodel, }) - const generator = config.generators.find( - (g) => g.previewFeatures.length > 0, - ) + const generator = config.generators.find((g) => g.previewFeatures.length > 0) if (generator) { return generator.previewFeatures } @@ -132,16 +121,9 @@ export class Version implements Command { return [] } - private printBinaryInfo({ - path: absolutePath, - version, - fromEnvVar, - }: BinaryInfo): string { + private printBinaryInfo({ path: absolutePath, version, fromEnvVar }: BinaryInfo): string { const resolved = fromEnvVar ? `, resolved by ${fromEnvVar}` : '' - return `${version} (at ${path.relative( - process.cwd(), - absolutePath, - )}${resolved})` + return `${version} (at ${path.relative(process.cwd(), absolutePath)}${resolved})` } private async resolveEngine(binaryName: BinaryType): Promise { @@ -166,9 +148,7 @@ export class Version implements Command { return JSON.stringify(result, null, 2) } const maxPad = rows.reduce((acc, curr) => Math.max(acc, curr[0].length), 0) - return rows - .map(([left, right]) => `${left.padEnd(maxPad)} : ${right}`) - .join('\n') + return rows.map(([left, right]) => `${left.padEnd(maxPad)} : ${right}`).join('\n') } public help(error?: string): string | HelpError { diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 122ec984b26d..7596ff94e2e0 100755 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -34,9 +34,7 @@ process.on('unhandledRejection', (e) => { if (process.argv.length > 1 && process.argv[1].endsWith('prisma2')) { console.log( chalk.yellow('deprecated') + - ` The ${chalk.redBright( - 'prisma2', - )} command is deprecated and has been renamed to ${chalk.greenBright( + ` The ${chalk.redBright('prisma2')} command is deprecated and has been renamed to ${chalk.greenBright( 'prisma', )}.\nPlease execute ${chalk.bold.greenBright( 'prisma' + (commandArray.length ? ' ' + commandArray.join(' ') : ''), @@ -199,18 +197,14 @@ async function main(): Promise { // restrict the search to previewFeatures of `provider = 'prisma-client-js'` // (this was not scoped to `prisma-client-js` before Prisma 3.0) const generator = config.generators.find( - (generator) => - parseEnvValue(generator.provider) === 'prisma-client-js' && - generator.previewFeatures.length > 0, + (generator) => parseEnvValue(generator.provider) === 'prisma-client-js' && generator.previewFeatures.length > 0, ) if (generator) { schemaPreviewFeatures = generator.previewFeatures } // Example 'prisma-client-js' - schemaGeneratorsProviders = config.generators.map((generator) => - parseEnvValue(generator.provider), - ) + schemaGeneratorsProviders = config.generators.map((generator) => parseEnvValue(generator.provider)) } catch (e) { debug('Error from cli/src/bin.ts') debug(e) @@ -228,17 +222,11 @@ async function main(): Promise { cli_path: process.argv[1], cli_install_type: isPrismaInstalledGlobally ? 'global' : 'local', command: commandArray.join(' '), - information: - args['--telemetry-information'] || - process.env.PRISMA_TELEMETRY_INFORMATION, + information: args['--telemetry-information'] || process.env.PRISMA_TELEMETRY_INFORMATION, }) // if the result is cached and we're outdated, show this prompt const shouldHide = process.env.PRISMA_HIDE_UPDATE_MESSAGE - if ( - checkResult.status === 'ok' && - checkResult.data.outdated && - !shouldHide - ) { + if (checkResult.status === 'ok' && checkResult.data.outdated && !shouldHide) { printUpdateMessage(checkResult) } } catch (e) { @@ -276,12 +264,7 @@ if (eval('require.main === module')) { function handleIndividualError(error): void { if (error.rustStack) { - handlePanic( - error, - packageJson.version, - enginesVersion, - commandArray.join(' '), - ) + handlePanic(error, packageJson.version, enginesVersion, commandArray.join(' ')) .catch((e) => { if (Debug.enabled('prisma')) { console.error(chalk.redBright.bold('Error: ') + e.stack) diff --git a/packages/cli/src/utils/breakingChanges.ts b/packages/cli/src/utils/breakingChanges.ts index 7156272de1d9..934882b4a5c2 100644 --- a/packages/cli/src/utils/breakingChanges.ts +++ b/packages/cli/src/utils/breakingChanges.ts @@ -1,9 +1,7 @@ import { link } from '@prisma/sdk' import chalk from 'chalk' -export const breakingChangesMessage = `${chalk.yellow.bold( - 'warn', -)} Prisma 2.12.0 has breaking changes. +export const breakingChangesMessage = `${chalk.yellow.bold('warn')} Prisma 2.12.0 has breaking changes. You can update your code with ${chalk.bold('`npx @prisma/codemods update-2.12 ./`')} Read more at ${link('https://pris.ly/2.12')}` diff --git a/packages/cli/src/utils/getClientVersion.ts b/packages/cli/src/utils/getClientVersion.ts index 272509e6d7b9..51a9384e5041 100644 --- a/packages/cli/src/utils/getClientVersion.ts +++ b/packages/cli/src/utils/getClientVersion.ts @@ -8,21 +8,14 @@ const readFileAsync = promisify(fs.readFile) /** * Try reading the installed Prisma Client version */ -export async function getInstalledPrismaClientVersion( - cwd: string = process.cwd(), -): Promise { - return ( - (await getPrismaClientVersionFromNodeModules(cwd)) ?? - (await getPrismaClientVersionFromLocalPackageJson(cwd)) - ) +export async function getInstalledPrismaClientVersion(cwd: string = process.cwd()): Promise { + return (await getPrismaClientVersionFromNodeModules(cwd)) ?? (await getPrismaClientVersionFromLocalPackageJson(cwd)) } /** * Try reading the Prisma Client version from its package.json */ -async function getPrismaClientVersionFromNodeModules( - cwd: string = process.cwd(), -): Promise { +async function getPrismaClientVersionFromNodeModules(cwd: string = process.cwd()): Promise { try { const pkgJsonPath = requireResolveFrom('@prisma/client/package.json', cwd) @@ -46,9 +39,7 @@ async function getPrismaClientVersionFromNodeModules( /** * Try reading the Prisma Client version from the local package.json */ -async function getPrismaClientVersionFromLocalPackageJson( - cwd: string = process.cwd(), -): Promise { +async function getPrismaClientVersionFromLocalPackageJson(cwd: string = process.cwd()): Promise { try { const pkgJsonPath = await pkgUp({ cwd }) @@ -58,9 +49,7 @@ async function getPrismaClientVersionFromLocalPackageJson( const pkgJsonString = await readFileAsync(pkgJsonPath, 'utf-8') const pkgJson = JSON.parse(pkgJsonString) - const clientVersion = - pkgJson.dependencies?.['@prisma/client'] ?? - pkgJson.devDependencies?.['@prisma/client'] + const clientVersion = pkgJson.dependencies?.['@prisma/client'] ?? pkgJson.devDependencies?.['@prisma/client'] if (!clientVersion) { return null diff --git a/packages/cli/src/utils/printUpdateMessage.ts b/packages/cli/src/utils/printUpdateMessage.ts index dd73cfe6f493..5c80b3f04e6b 100644 --- a/packages/cli/src/utils/printUpdateMessage.ts +++ b/packages/cli/src/utils/printUpdateMessage.ts @@ -4,28 +4,18 @@ import type { Check } from 'checkpoint-client' const isPrismaInstalledGlobally = isCurrentBinInstalledGlobally() -export function printUpdateMessage(checkResult: { - status: 'ok' - data: Check.Response -}): void { +export function printUpdateMessage(checkResult: { status: 'ok'; data: Check.Response }): void { let boxHeight = 4 let majorText = '' const currentVersionInstalled = checkResult.data.previous_version const latestVersionAvailable = checkResult.data.current_version - const prismaCLICommand = makeInstallCommand( - checkResult.data.package, - checkResult.data.release_tag, - ) - const prismaClientCommand = makeInstallCommand( - '@prisma/client', - checkResult.data.release_tag, - { - canBeGlobal: false, - canBeDev: false, - }, - ) + const prismaCLICommand = makeInstallCommand(checkResult.data.package, checkResult.data.release_tag) + const prismaClientCommand = makeInstallCommand('@prisma/client', checkResult.data.release_tag, { + canBeGlobal: false, + canBeDev: false, + }) try { const [majorInstalled] = currentVersionInstalled.split('.') diff --git a/packages/cli/src/utils/prompt/utils/deepExtend.ts b/packages/cli/src/utils/prompt/utils/deepExtend.ts index c779a6c8cdb6..5b9636bb5e72 100644 --- a/packages/cli/src/utils/prompt/utils/deepExtend.ts +++ b/packages/cli/src/utils/prompt/utils/deepExtend.ts @@ -28,9 +28,7 @@ */ function isSpecificValue(val): boolean { - return val instanceof Buffer || val instanceof Date || val instanceof RegExp - ? true - : false + return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false } function cloneSpecificValue(val): RegExp | Buffer | Date { @@ -125,11 +123,7 @@ export const deepExtend = function (target, ...args): any { continue // overwrite by new value if source isn't object or array - } else if ( - typeof src !== 'object' || - src === null || - Array.isArray(src) - ) { + } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { target[key] = deepExtend({}, val) continue diff --git a/packages/cli/src/utils/prompt/utils/templates/sortModels.ts b/packages/cli/src/utils/prompt/utils/templates/sortModels.ts index 325232c4cc75..91bd83ea11ce 100644 --- a/packages/cli/src/utils/prompt/utils/templates/sortModels.ts +++ b/packages/cli/src/utils/prompt/utils/templates/sortModels.ts @@ -1,15 +1,6 @@ import type { DMMF } from '@prisma/generator-helper' -const modelOrder = [ - 'User', - 'Player', - 'Customer', - 'Product', - 'Order', - 'Article', - 'Post', - 'Message', -] +const modelOrder = ['User', 'Player', 'Customer', 'Product', 'Order', 'Article', 'Post', 'Message'] export function sortModels(models: DMMF.Model[]): DMMF.Model[] { return models.sort((a, b) => { diff --git a/packages/cli/src/utils/test-handlePanic.ts b/packages/cli/src/utils/test-handlePanic.ts index 98a2e678d816..099fbd4667e7 100644 --- a/packages/cli/src/utils/test-handlePanic.ts +++ b/packages/cli/src/utils/test-handlePanic.ts @@ -9,14 +9,7 @@ async function main() { const command = 'something-test' try { - const dirPath = path.join( - __dirname, - '..', - '__tests__', - 'fixtures', - 'introspection', - 'postgresql', - ) + const dirPath = path.join(__dirname, '..', '__tests__', 'fixtures', 'introspection', 'postgresql') process.chdir(dirPath) diff --git a/packages/client/.prettierrc.yml b/packages/client/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/client/.prettierrc.yml +++ b/packages/client/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/client/fixtures/generate.ts b/packages/client/fixtures/generate.ts index b33a378a6063..dcb8d4667b3b 100644 --- a/packages/client/fixtures/generate.ts +++ b/packages/client/fixtures/generate.ts @@ -13,9 +13,7 @@ async function main() { const projectDir = args._[0] if (!projectDir) { - throw new Error( - `Project dir missing. Usage: ts-node examples/generate.ts examples/accounts`, - ) + throw new Error(`Project dir missing. Usage: ts-node examples/generate.ts examples/accounts`) } if (!fs.existsSync(projectDir)) { @@ -25,9 +23,7 @@ async function main() { const useLocalRuntime = args['--skip-transpile'] if (args['--built-runtime'] && !args['--skip-transpile']) { - throw new Error( - `Please either provide --skip-transpile or --skip-transpile and --built-runtime`, - ) + throw new Error(`Please either provide --skip-transpile or --skip-transpile and --built-runtime`) } const time = await generateInFolder({ @@ -38,9 +34,9 @@ async function main() { }) console.log( - `Generated Prisma Client ${chalk.underline( - useLocalRuntime ? 'with' : 'without', - )} local runtime in ${time.toFixed(3)}ms`, + `Generated Prisma Client ${chalk.underline(useLocalRuntime ? 'with' : 'without')} local runtime in ${time.toFixed( + 3, + )}ms`, ) } diff --git a/packages/client/helpers/build.ts b/packages/client/helpers/build.ts index 8e36a6ca0ffc..3814c968775e 100644 --- a/packages/client/helpers/build.ts +++ b/packages/client/helpers/build.ts @@ -111,18 +111,10 @@ function bundleTypeDefinitions(filename: string, outfile: string) { } } -void build([ - generatorBuildConfig, - runtimeBuildConfig, - browserBuildConfig, - proxyBuildConfig, -]).then(() => { +void build([generatorBuildConfig, runtimeBuildConfig, browserBuildConfig, proxyBuildConfig]).then(() => { if (process.env.DEV !== 'true') { bundleTypeDefinitions('declaration/runtime/index', 'runtime/index') bundleTypeDefinitions('declaration/runtime/index', 'runtime/proxy') - bundleTypeDefinitions( - 'declaration/runtime/index-browser', - 'runtime/index-browser', - ) + bundleTypeDefinitions('declaration/runtime/index-browser', 'runtime/index-browser') } }) diff --git a/packages/client/scripts/default-index.d.ts b/packages/client/scripts/default-index.d.ts index 10b768639ce6..0fa19bbef8c8 100644 --- a/packages/client/scripts/default-index.d.ts +++ b/packages/client/scripts/default-index.d.ts @@ -35,12 +35,9 @@ export declare type dmmf = any /** * Get the type of the value, that the Promise holds. */ -export declare type PromiseType> = - T extends PromiseLike ? U : T +export declare type PromiseType> = T extends PromiseLike ? U : T /** * Get the return type of a function which returns a Promise. */ -export declare type PromiseReturnType< - T extends (...args: any) => Promise, -> = PromiseType> +export declare type PromiseReturnType Promise> = PromiseType> diff --git a/packages/client/src/__tests__/aggregate.test.ts b/packages/client/src/__tests__/aggregate.test.ts index 0bdc251e504d..a9fc49c071bb 100644 --- a/packages/client/src/__tests__/aggregate.test.ts +++ b/packages/client/src/__tests__/aggregate.test.ts @@ -134,9 +134,7 @@ describe('aggregate', () => { rootTypeName: 'query', rootField: 'aggregateUser', }) - expect(() => - document.validate(select, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('unhappy path - incorrect field', () => { @@ -155,8 +153,6 @@ describe('aggregate', () => { rootTypeName: 'query', rootField: 'aggregateUser', }) - expect(() => - document.validate(select, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) }) diff --git a/packages/client/src/__tests__/batching.test.ts b/packages/client/src/__tests__/batching.test.ts index 8a3a88e24104..e5578324290c 100644 --- a/packages/client/src/__tests__/batching.test.ts +++ b/packages/client/src/__tests__/batching.test.ts @@ -14,9 +14,7 @@ describe('batching', () => { _engine: { requestBatch: (batch) => { batches.push(batch) - return Promise.resolve( - batch.map(() => ({ data: { data: null }, elapsed: 0.2 })), - ) + return Promise.resolve(batch.map(() => ({ data: { data: null }, elapsed: 0.2 }))) }, request: (request) => { requests.push(request) @@ -129,9 +127,7 @@ describe('batching', () => { _engine: { requestBatch: (batch) => { batches.push(batch) - return Promise.resolve( - batch.map(() => ({ data: { data: null }, elapsed: 0.2 })), - ) + return Promise.resolve(batch.map(() => ({ data: { data: null }, elapsed: 0.2 }))) }, request: (request) => { requests.push(request) @@ -233,9 +229,7 @@ describe('batching', () => { _engine: { requestBatch: (batch) => { batches.push(batch) - return Promise.resolve( - batch.map(() => ({ data: { data: null }, elapsed: 0.2 })), - ) + return Promise.resolve(batch.map(() => ({ data: { data: null }, elapsed: 0.2 }))) }, request: (request) => { requests.push(request) diff --git a/packages/client/src/__tests__/binaryEngine.test.ts b/packages/client/src/__tests__/binaryEngine.test.ts index 53309ff1aeb4..d63f51ea51b1 100644 --- a/packages/client/src/__tests__/binaryEngine.test.ts +++ b/packages/client/src/__tests__/binaryEngine.test.ts @@ -1,9 +1,6 @@ import { BinaryEngine } from '@prisma/engine-core' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../runtime/utils/getClientEngineType' describe('BinaryEngine', () => { test('should error correctly with invalid flags', async () => { @@ -16,16 +13,11 @@ describe('BinaryEngine', () => { try { const engine = new BinaryEngine({ flags: ['--flag-that-does-not-exist'], - datamodelPath: path.join( - __dirname, - './runtime-tests/blog/schema.prisma', - ), + datamodelPath: path.join(__dirname, './runtime-tests/blog/schema.prisma'), }) await engine.start() } catch (e) { - expect(e.message).toMatch( - ` Found argument '--flag-that-does-not-exist' which wasn't expected`, - ) + expect(e.message).toMatch(` Found argument '--flag-that-does-not-exist' which wasn't expected`) } }) }) diff --git a/packages/client/src/__tests__/dmmf.test.ts b/packages/client/src/__tests__/dmmf.test.ts index f31cb875cfac..6ca06580b270 100644 --- a/packages/client/src/__tests__/dmmf.test.ts +++ b/packages/client/src/__tests__/dmmf.test.ts @@ -22,11 +22,8 @@ describe('dmmf', () => { }` const dmmf = await getDMMF({ datamodel }) - expect( - dmmf.schema.inputObjectTypes.prisma.find( - (i) => i.name === 'NestedEnumPostKindFilter', - ), - ).toMatchInlineSnapshot(` + expect(dmmf.schema.inputObjectTypes.prisma.find((i) => i.name === 'NestedEnumPostKindFilter')) + .toMatchInlineSnapshot(` Object { constraints: Object { maxNumFields: null, @@ -95,11 +92,7 @@ describe('dmmf', () => { name: NestedEnumPostKindFilter, } `) - expect( - dmmf.schema.inputObjectTypes.prisma.find( - (i) => i.name === 'EnumPostKindFilter', - ), - ).toMatchInlineSnapshot(` + expect(dmmf.schema.inputObjectTypes.prisma.find((i) => i.name === 'EnumPostKindFilter')).toMatchInlineSnapshot(` Object { constraints: Object { maxNumFields: null, @@ -190,11 +183,8 @@ describe('dmmf', () => { }` const dmmf = await getDMMF({ datamodel }) - expect( - dmmf.schema.inputObjectTypes.prisma.find( - (i) => i.name === 'NestedEnumPostKindFilter', - ), - ).toMatchInlineSnapshot(` + expect(dmmf.schema.inputObjectTypes.prisma.find((i) => i.name === 'NestedEnumPostKindFilter')) + .toMatchInlineSnapshot(` Object { constraints: Object { maxNumFields: null, @@ -263,11 +253,7 @@ describe('dmmf', () => { name: NestedEnumPostKindFilter, } `) - expect( - dmmf.schema.inputObjectTypes.prisma.find( - (i) => i.name === 'EnumPostKindFilter', - ), - ).toMatchInlineSnapshot(` + expect(dmmf.schema.inputObjectTypes.prisma.find((i) => i.name === 'EnumPostKindFilter')).toMatchInlineSnapshot(` Object { constraints: Object { maxNumFields: null, diff --git a/packages/client/src/__tests__/dmmfTypes.test.ts b/packages/client/src/__tests__/dmmfTypes.test.ts index c2cf429e664c..841c8b8eeae7 100644 --- a/packages/client/src/__tests__/dmmfTypes.test.ts +++ b/packages/client/src/__tests__/dmmfTypes.test.ts @@ -26,11 +26,7 @@ test('dmmf types', async () => { const dmmf = await getDMMF({ datamodel: blog }) const file = `import { DMMF } from '@prisma/generator-helper' -const dmmf: DMMF.Document = ${JSON.stringify( - sortKeys(dmmf, { deep: true }), - null, - 2, - )} +const dmmf: DMMF.Document = ${JSON.stringify(sortKeys(dmmf, { deep: true }), null, 2)} ` const target = path.join(__dirname, '__helpers__/dmmf-types.ts') fs.writeFileSync(target, file) diff --git a/packages/client/src/__tests__/generation/generator.test.ts b/packages/client/src/__tests__/generation/generator.test.ts index bc9009a15d70..cc762afba2c6 100644 --- a/packages/client/src/__tests__/generation/generator.test.ts +++ b/packages/client/src/__tests__/generation/generator.test.ts @@ -5,20 +5,14 @@ import rimraf from 'rimraf' import stripAnsi from 'strip-ansi' import { promisify } from 'util' import { omit } from '../../omit' -import { - ClientEngineType, - getClientEngineType, -} from '../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../runtime/utils/getClientEngineType' const del = promisify(rimraf) jest.setTimeout(30000) describe('generator', () => { test('minimal', async () => { - const prismaClientTarget = path.join( - __dirname, - './node_modules/@prisma/client', - ) + const prismaClientTarget = path.join(__dirname, './node_modules/@prisma/client') // Make sure, that nothing is cached. try { await del(prismaClientTarget) @@ -41,9 +35,7 @@ describe('generator', () => { const manifest = omit(generator.manifest, ['version']) as any if (manifest.requiresEngineVersion.length !== 40) { - throw new Error( - `Generator manifest should have "requiresEngineVersion" with length 40`, - ) + throw new Error(`Generator manifest should have "requiresEngineVersion" with length 40`) } manifest.requiresEngineVersion = 'ENGINE_VERSION_TEST' @@ -71,8 +63,7 @@ describe('generator', () => { `) } - expect(omit(generator.options!.generator, ['output'])) - .toMatchInlineSnapshot(` + expect(omit(generator.options!.generator, ['output'])).toMatchInlineSnapshot(` Object { binaryTargets: Array [], config: Object {}, @@ -85,12 +76,9 @@ describe('generator', () => { } `) - expect( - path.relative( - __dirname, - parseEnvValue(generator.options!.generator.output!), - ), - ).toMatchInlineSnapshot(`node_modules/@prisma/client`) + expect(path.relative(__dirname, parseEnvValue(generator.options!.generator.output!))).toMatchInlineSnapshot( + `node_modules/@prisma/client`, + ) await generator.generate() const photonDir = path.join(__dirname, 'node_modules/@prisma/client') @@ -103,10 +91,7 @@ describe('generator', () => { }) test('denylist from engine validation', async () => { - const prismaClientTarget = path.join( - __dirname, - './node_modules/@prisma/client', - ) + const prismaClientTarget = path.join(__dirname, './node_modules/@prisma/client') // Make sure, that nothing is cached. try { await del(prismaClientTarget) @@ -152,10 +137,7 @@ describe('generator', () => { }) test('schema path does not exist', async () => { - const prismaClientTarget = path.join( - __dirname, - './node_modules/@prisma/client', - ) + const prismaClientTarget = path.join(__dirname, './node_modules/@prisma/client') // Make sure, that nothing is cached. try { await del(prismaClientTarget) @@ -179,17 +161,14 @@ describe('generator', () => { } catch (e) { doesnNotExistError = e } finally { - expect( - stripAnsi(doesnNotExistError.message).split('generation/')[1], - ).toMatchInlineSnapshot(`doesnotexist.prisma does not exist`) + expect(stripAnsi(doesnNotExistError.message).split('generation/')[1]).toMatchInlineSnapshot( + `doesnotexist.prisma does not exist`, + ) } }) test('mongo', async () => { - const prismaClientTarget = path.join( - __dirname, - './node_modules/@prisma/client', - ) + const prismaClientTarget = path.join(__dirname, './node_modules/@prisma/client') // Make sure, that nothing is cached. try { await del(prismaClientTarget) @@ -212,9 +191,7 @@ describe('generator', () => { const manifest = omit(generator.manifest, ['version']) as any if (manifest.requiresEngineVersion.length !== 40) { - throw new Error( - `Generator manifest should have "requiresEngineVersion" with length 40`, - ) + throw new Error(`Generator manifest should have "requiresEngineVersion" with length 40`) } manifest.requiresEngineVersion = 'ENGINE_VERSION_TEST' @@ -242,8 +219,7 @@ describe('generator', () => { `) } - expect(omit(generator.options!.generator, ['output'])) - .toMatchInlineSnapshot(` + expect(omit(generator.options!.generator, ['output'])).toMatchInlineSnapshot(` Object { binaryTargets: Array [], config: Object {}, @@ -258,12 +234,9 @@ describe('generator', () => { } `) - expect( - path.relative( - __dirname, - parseEnvValue(generator.options!.generator.output!), - ), - ).toMatchInlineSnapshot(`node_modules/@prisma/client`) + expect(path.relative(__dirname, parseEnvValue(generator.options!.generator.output!))).toMatchInlineSnapshot( + `node_modules/@prisma/client`, + ) await generator.generate() const photonDir = path.join(__dirname, 'node_modules/@prisma/client') diff --git a/packages/client/src/__tests__/integration/__helpers__/migrateDb.ts b/packages/client/src/__tests__/integration/__helpers__/migrateDb.ts index 15c51e5fea96..c41a4bc09d65 100644 --- a/packages/client/src/__tests__/integration/__helpers__/migrateDb.ts +++ b/packages/client/src/__tests__/integration/__helpers__/migrateDb.ts @@ -6,10 +6,7 @@ export type MigrateOptions = { schemaPath: string } -export async function migrateDb({ - connectionString, - schemaPath, -}: MigrateOptions) { +export async function migrateDb({ connectionString, schemaPath }: MigrateOptions) { await createDatabase(connectionString) const migrate = new Migrate(schemaPath) diff --git a/packages/client/src/__tests__/integration/errors/connection-limit-mysql/test.ts b/packages/client/src/__tests__/integration/errors/connection-limit-mysql/test.ts index 85700473a85c..1dcce9f96711 100644 --- a/packages/client/src/__tests__/integration/errors/connection-limit-mysql/test.ts +++ b/packages/client/src/__tests__/integration/errors/connection-limit-mysql/test.ts @@ -11,9 +11,7 @@ describe.skip('connection-limit-mysql', () => { test('the client cannot query the db with 152 connections already open', async () => { const PrismaClient = await getTestClient() - const connectionString = - process.env.TEST_MYSQL_ISOLATED_URI || - 'mysql://root:root@mysql:3306/tests' + const connectionString = process.env.TEST_MYSQL_ISOLATED_URI || 'mysql://root:root@mysql:3306/tests' for (let i = 0; i <= 155; i++) { const client = new PrismaClient({ diff --git a/packages/client/src/__tests__/integration/errors/connection-limit-postgres/test.ts b/packages/client/src/__tests__/integration/errors/connection-limit-postgres/test.ts index 4ee7c9b9be29..51a10425fd12 100644 --- a/packages/client/src/__tests__/integration/errors/connection-limit-postgres/test.ts +++ b/packages/client/src/__tests__/integration/errors/connection-limit-postgres/test.ts @@ -10,9 +10,7 @@ describe.skip('connection-limit-postgres', () => { test('the client cannot query the db with 100 connections already open', async () => { const PrismaClient = await getTestClient() - const connectionString = - process.env.TEST_POSTGRES_ISOLATED_URI || - 'postgres://prisma:prisma@localhost:5435/tests' + const connectionString = process.env.TEST_POSTGRES_ISOLATED_URI || 'postgres://prisma:prisma@localhost:5435/tests' for (let i = 0; i <= 100; i++) { const client = new PrismaClient({ @@ -28,9 +26,7 @@ describe.skip('connection-limit-postgres', () => { await client.$connect() } } catch (e) { - expect(e.message).toMatch( - 'Error querying the database: db error: FATAL: sorry, too many clients already', - ) + expect(e.message).toMatch('Error querying the database: db error: FATAL: sorry, too many clients already') } }, 100_000) }) diff --git a/packages/client/src/__tests__/integration/errors/corruption/test.ts b/packages/client/src/__tests__/integration/errors/corruption/test.ts index 4817471ff427..883fe3eb0f82 100644 --- a/packages/client/src/__tests__/integration/errors/corruption/test.ts +++ b/packages/client/src/__tests__/integration/errors/corruption/test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('corruption of query engine binary', async () => { @@ -16,9 +13,7 @@ test('corruption of query engine binary', async () => { const binaryPath = path.join( __dirname, 'node_modules/.prisma/client', - getClientEngineType() === ClientEngineType.Library - ? getNodeAPIName(platform, 'fs') - : `query-engine-${platform}`, + getClientEngineType() === ClientEngineType.Library ? getNodeAPIName(platform, 'fs') : `query-engine-${platform}`, ) fs.writeFileSync(binaryPath, 'hello world') diff --git a/packages/client/src/__tests__/integration/errors/error-link/test.ts b/packages/client/src/__tests__/integration/errors/error-link/test.ts index ab9c36c31771..323a068b21e1 100644 --- a/packages/client/src/__tests__/integration/errors/error-link/test.ts +++ b/packages/client/src/__tests__/integration/errors/error-link/test.ts @@ -1,7 +1,4 @@ -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { getTestClient } from '../../../../utils/getTestClient' test('error-link', async () => { @@ -22,8 +19,7 @@ test('error-link', async () => { errorFormat: 'minimal', }) - await expect(db.__internal_triggerPanic(true)).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(db.__internal_triggerPanic(true)).rejects.toThrowErrorMatchingInlineSnapshot(` Query engine debug fatal error, shutting down. This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic. diff --git a/packages/client/src/__tests__/integration/errors/executeRaw-alter-postgres/test.ts b/packages/client/src/__tests__/integration/errors/executeRaw-alter-postgres/test.ts index 7cb7d1a5f83f..d449d0fec32c 100644 --- a/packages/client/src/__tests__/integration/errors/executeRaw-alter-postgres/test.ts +++ b/packages/client/src/__tests__/integration/errors/executeRaw-alter-postgres/test.ts @@ -40,10 +40,7 @@ test('executeRaw-alter-postgres', async () => { `) } try { - await prisma.$executeRawUnsafe( - `ALTER USER prisma WITH PASSWORD $1`, - password, - ) + await prisma.$executeRawUnsafe(`ALTER USER prisma WITH PASSWORD $1`, password) } catch (err) { // String expect(err).toMatchInlineSnapshot(` @@ -74,8 +71,6 @@ test('executeRaw-alter-postgres', async () => { } // Should Work - const result = await prisma.$executeRawUnsafe( - `ALTER USER prisma WITH PASSWORD '${password}'`, - ) + const result = await prisma.$executeRawUnsafe(`ALTER USER prisma WITH PASSWORD '${password}'`) expect(result).toMatchInlineSnapshot(`0`) }) diff --git a/packages/client/src/__tests__/integration/errors/incorrect-column-type/test.ts b/packages/client/src/__tests__/integration/errors/incorrect-column-type/test.ts index d8e077ae7a96..0bc9bf61ceb3 100644 --- a/packages/client/src/__tests__/integration/errors/incorrect-column-type/test.ts +++ b/packages/client/src/__tests__/integration/errors/incorrect-column-type/test.ts @@ -12,8 +12,7 @@ test('incorrect-column-type', async () => { ], }) - await expect(prisma.user.findMany()).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(prisma.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot(` Invalid \`expect(prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/incorrect-column-type/test.ts:0:0 @@ -21,7 +20,7 @@ test('incorrect-column-type', async () => { 12 ], 13 }) 14 - ā†’ 15 await expect(prisma.user.findMany()).reject + ā†’ 15 await expect(prisma.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot( Attempted to serialize scalar '123' with incompatible type 'String' for field name. `) await prisma.$disconnect() diff --git a/packages/client/src/__tests__/integration/errors/int-errors/test.ts b/packages/client/src/__tests__/integration/errors/int-errors/test.ts index 21a39e1270b3..e6e64acd60b4 100644 --- a/packages/client/src/__tests__/integration/errors/int-errors/test.ts +++ b/packages/client/src/__tests__/integration/errors/int-errors/test.ts @@ -9,8 +9,7 @@ describe('int-errors', () => { beforeAll(async () => { await generateTestClient() const { PrismaClient } = require('@prisma/client') - let originalConnectionString = - process.env.TEST_MYSQL_URI || 'mysql://root:root@localhost:3306/tests' + let originalConnectionString = process.env.TEST_MYSQL_URI || 'mysql://root:root@localhost:3306/tests' originalConnectionString += '-signed-int' diff --git a/packages/client/src/__tests__/integration/errors/missing-column/test.ts b/packages/client/src/__tests__/integration/errors/missing-column/test.ts index fa102cbe2f89..4c7c851448a6 100644 --- a/packages/client/src/__tests__/integration/errors/missing-column/test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-column/test.ts @@ -3,8 +3,7 @@ import { getTestClient } from '../../../../utils/getTestClient' test('missing-column', async () => { const PrismaClient = await getTestClient() const client = new PrismaClient() - await expect(client.user.findMany()).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(client.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot(` Invalid \`expect(client.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-column/test.ts:0:0 @@ -12,7 +11,7 @@ test('missing-column', async () => { 3 test('missing-column', async () => { 4 const PrismaClient = await getTestClient() 5 const client = new PrismaClient() - ā†’ 6 await expect(client.user.findMany()).reject + ā†’ 6 await expect(client.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot( The column \`main.User.name\` does not exist in the current database. `) client.$disconnect() diff --git a/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/binary.test.ts b/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/binary.test.ts index 793bad82666c..67ed50a6e724 100644 --- a/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/binary.test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/binary.test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('missing-engine-native-binaryTarget: binary', async () => { @@ -20,16 +17,8 @@ test('missing-engine-native-binaryTarget: binary', async () => { const platform = await getPlatform() const binaryPath = getClientEngineType() === ClientEngineType.Library - ? path.join( - __dirname, - 'node_modules/.prisma/client', - getNodeAPIName(platform, 'fs'), - ) - : path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + ? path.join(__dirname, 'node_modules/.prisma/client', getNodeAPIName(platform, 'fs')) + : path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) fs.unlinkSync(binaryPath) const prisma = new PrismaClient({ log: [ @@ -47,10 +36,10 @@ test('missing-engine-native-binaryTarget: binary', async () => { Invalid \`prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/binary.test.ts:0:0 - 41 }) - 42 - 43 await expect(async () => { - ā†’ 44 await prisma.user.findMany( + 30 }) + 31 + 32 await expect(async () => { + ā†’ 33 await prisma.user.findMany( Query engine binary for current platform "TEST_PLATFORM" could not be found. This probably happens, because you built Prisma Client on a different platform. (Prisma Client looked in "/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/node_modules/@prisma/client/runtime/query-engine-TEST_PLATFORM") diff --git a/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/library.test.ts b/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/library.test.ts index d1737f4cbd67..c62c21b26d3e 100644 --- a/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/library.test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/library.test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('missing-engine-native-binaryTarget: library', async () => { @@ -20,16 +17,8 @@ test('missing-engine-native-binaryTarget: library', async () => { const platform = await getPlatform() const binaryPath = getClientEngineType() === ClientEngineType.Library - ? path.join( - __dirname, - 'node_modules/.prisma/client', - getNodeAPIName(platform, 'fs'), - ) - : path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + ? path.join(__dirname, 'node_modules/.prisma/client', getNodeAPIName(platform, 'fs')) + : path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) fs.unlinkSync(binaryPath) const prisma = new PrismaClient({ log: [ @@ -47,10 +36,10 @@ test('missing-engine-native-binaryTarget: library', async () => { Invalid \`prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-engine-native-binaryTarget/library.test.ts:0:0 - 41 }) - 42 - 43 await expect(async () => { - ā†’ 44 await prisma.user.findMany( + 30 }) + 31 + 32 await expect(async () => { + ā†’ 33 await prisma.user.findMany( Query engine library for current platform "TEST_PLATFORM" could not be found. You incorrectly pinned it to TEST_PLATFORM diff --git a/packages/client/src/__tests__/integration/errors/missing-engine/binary.test.ts b/packages/client/src/__tests__/integration/errors/missing-engine/binary.test.ts index 7bb14aeaf9d4..1c575329a00a 100644 --- a/packages/client/src/__tests__/integration/errors/missing-engine/binary.test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-engine/binary.test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('missing-engine: binary', async () => { @@ -20,16 +17,8 @@ test('missing-engine: binary', async () => { const platform = await getPlatform() const binaryPath = getClientEngineType() === ClientEngineType.Library - ? path.join( - __dirname, - 'node_modules/.prisma/client', - getNodeAPIName(platform, 'fs'), - ) - : path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + ? path.join(__dirname, 'node_modules/.prisma/client', getNodeAPIName(platform, 'fs')) + : path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) fs.unlinkSync(binaryPath) const prisma = new PrismaClient({ log: [ @@ -47,10 +36,10 @@ test('missing-engine: binary', async () => { Invalid \`prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-engine/binary.test.ts:0:0 - 41 }) - 42 - 43 await expect(async () => { - ā†’ 44 await prisma.user.findMany( + 30 }) + 31 + 32 await expect(async () => { + ā†’ 33 await prisma.user.findMany( Query engine binary for current platform "TEST_PLATFORM" could not be found. This probably happens, because you built Prisma Client on a different platform. (Prisma Client looked in "/client/src/__tests__/integration/errors/missing-engine/node_modules/@prisma/client/runtime/query-engine-TEST_PLATFORM") diff --git a/packages/client/src/__tests__/integration/errors/missing-engine/library.test.ts b/packages/client/src/__tests__/integration/errors/missing-engine/library.test.ts index b759e3729200..7c41de32ce61 100644 --- a/packages/client/src/__tests__/integration/errors/missing-engine/library.test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-engine/library.test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('missing-engine: library', async () => { @@ -20,16 +17,8 @@ test('missing-engine: library', async () => { const platform = await getPlatform() const binaryPath = getClientEngineType() === ClientEngineType.Library - ? path.join( - __dirname, - 'node_modules/.prisma/client', - getNodeAPIName(platform, 'fs'), - ) - : path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + ? path.join(__dirname, 'node_modules/.prisma/client', getNodeAPIName(platform, 'fs')) + : path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) fs.unlinkSync(binaryPath) const prisma = new PrismaClient({ log: [ @@ -47,10 +36,10 @@ test('missing-engine: library', async () => { Invalid \`prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-engine/library.test.ts:0:0 - 41 }) - 42 - 43 await expect(async () => { - ā†’ 44 await prisma.user.findMany( + 30 }) + 31 + 32 await expect(async () => { + ā†’ 33 await prisma.user.findMany( Query engine library for current platform "TEST_PLATFORM" could not be found. You incorrectly pinned it to TEST_PLATFORM diff --git a/packages/client/src/__tests__/integration/errors/missing-table/test.ts b/packages/client/src/__tests__/integration/errors/missing-table/test.ts index 7719ec3547e0..00e22df7bf97 100644 --- a/packages/client/src/__tests__/integration/errors/missing-table/test.ts +++ b/packages/client/src/__tests__/integration/errors/missing-table/test.ts @@ -5,8 +5,7 @@ test('missing-table', async () => { const PrismaClient = await getTestClient() const prisma = new PrismaClient() - await expect(prisma.user.findMany()).rejects - .toThrowErrorMatchingInlineSnapshot(` + await expect(prisma.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot(` Invalid \`expect(prisma.user.findMany()\` invocation in /client/src/__tests__/integration/errors/missing-table/test.ts:0:0 @@ -14,7 +13,7 @@ test('missing-table', async () => { 5 const PrismaClient = await getTestClient() 6 const prisma = new PrismaClient() 7 - ā†’ 8 await expect(prisma.user.findMany()).reject + ā†’ 8 await expect(prisma.user.findMany()).rejects.toThrowErrorMatchingInlineSnapshot( The table \`main.User\` does not exist in the current database. `) diff --git a/packages/client/src/__tests__/integration/errors/object-transaction/test.ts b/packages/client/src/__tests__/integration/errors/object-transaction/test.ts index 1bfc36892ac7..61325eb3207b 100644 --- a/packages/client/src/__tests__/integration/errors/object-transaction/test.ts +++ b/packages/client/src/__tests__/integration/errors/object-transaction/test.ts @@ -3,9 +3,7 @@ import { getTestClient } from '../../../../utils/getTestClient' test('object-transaction undefined', async () => { const PrismaClient = await getTestClient() const prisma = new PrismaClient() - await expect(async () => - prisma.$transaction([await Promise.resolve()]), - ).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(async () => prisma.$transaction([await Promise.resolve()])).rejects.toThrowErrorMatchingInlineSnapshot( `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.`, ) @@ -15,9 +13,7 @@ test('object-transaction undefined', async () => { test('object-transaction object', async () => { const PrismaClient = await getTestClient() const prisma = new PrismaClient() - await expect(async () => - prisma.$transaction([await Promise.resolve({})]), - ).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(async () => prisma.$transaction([await Promise.resolve({})])).rejects.toThrowErrorMatchingInlineSnapshot( `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.`, ) diff --git a/packages/client/src/__tests__/integration/happy/atomic-operations/test.ts b/packages/client/src/__tests__/integration/happy/atomic-operations/test.ts index b120df7cce51..af2617013b76 100644 --- a/packages/client/src/__tests__/integration/happy/atomic-operations/test.ts +++ b/packages/client/src/__tests__/integration/happy/atomic-operations/test.ts @@ -6,10 +6,7 @@ const copyFile = promisify(fs.copyFile) test('atomic-operations', async () => { // start with a fresh db - await copyFile( - path.join(__dirname, 'dev.db'), - path.join(__dirname, 'dev-tmp.db'), - ) + await copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db')) const PrismaClient = await getTestClient() const prisma = new PrismaClient() diff --git a/packages/client/src/__tests__/integration/happy/batch-findUnique/test.ts b/packages/client/src/__tests__/integration/happy/batch-findUnique/test.ts index e54725c55246..e591df4be63d 100644 --- a/packages/client/src/__tests__/integration/happy/batch-findUnique/test.ts +++ b/packages/client/src/__tests__/integration/happy/batch-findUnique/test.ts @@ -26,9 +26,7 @@ test('batch findUnique', async () => { prisma.$on('query', (q) => { queries.push(q) }) - users = await Promise.all( - users.map((u) => prisma.user.findUnique({ where: { id: u.id } })), - ) + users = await Promise.all(users.map((u) => prisma.user.findUnique({ where: { id: u.id } }))) expect(users).toMatchInlineSnapshot(` Array [ Object { diff --git a/packages/client/src/__tests__/integration/happy/binary/test.ts b/packages/client/src/__tests__/integration/happy/binary/test.ts index 06182a17a35d..4c543159b4ac 100644 --- a/packages/client/src/__tests__/integration/happy/binary/test.ts +++ b/packages/client/src/__tests__/integration/happy/binary/test.ts @@ -1,10 +1,7 @@ import { getNodeAPIName, getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' test('binary', async () => { @@ -14,15 +11,7 @@ test('binary', async () => { const platform = await getPlatform() const binaryPath = getClientEngineType() === ClientEngineType.Library - ? path.join( - __dirname, - 'node_modules/.prisma/client', - getNodeAPIName(platform, 'fs'), - ) - : path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + ? path.join(__dirname, 'node_modules/.prisma/client', getNodeAPIName(platform, 'fs')) + : path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) expect(fs.existsSync(binaryPath)).toBe(true) }) diff --git a/packages/client/src/__tests__/integration/happy/blog-env-mssql/test.ts b/packages/client/src/__tests__/integration/happy/blog-env-mssql/test.ts index 499326eaa8fb..b2678b598982 100644 --- a/packages/client/src/__tests__/integration/happy/blog-env-mssql/test.ts +++ b/packages/client/src/__tests__/integration/happy/blog-env-mssql/test.ts @@ -9,9 +9,7 @@ describe('blog-env-mssql', () => { const requests: any[] = [] beforeAll(async () => { - const connectionString = - process.env.TEST_MSSQL_URI || - 'mssql://SA:Pr1sm4_Pr1sm4@localhost:1433/master' + const connectionString = process.env.TEST_MSSQL_URI || 'mssql://SA:Pr1sm4_Pr1sm4@localhost:1433/master' const setupParams: SetupParams = { connectionString, dirname: __dirname, @@ -186,9 +184,7 @@ describe('blog-env-mssql', () => { test('$queryRaw(sql``) with params', async () => { await prisma.user.create({ data: { email: 'd@a.de', name: 'D' } }) - const users = await prisma.$queryRaw( - sql`SELECT * FROM [dbo].[User] WHERE name = ${'D'}`, - ) + const users = await prisma.$queryRaw(sql`SELECT * FROM [dbo].[User] WHERE name = ${'D'}`) expect(users).not.toHaveLength(0) }) @@ -199,17 +195,17 @@ describe('blog-env-mssql', () => { }) test('$queryRaw`` with join', async () => { - const users = - await prisma.$queryRaw`SELECT * FROM [dbo].[User] WHERE id IN (${PrismaHelpers.join( - ['42', '333', '2048'], - )})` + const users = await prisma.$queryRaw`SELECT * FROM [dbo].[User] WHERE id IN (${PrismaHelpers.join([ + '42', + '333', + '2048', + ])})` expect(users).toHaveLength(0) }) test('$queryRaw`` with params', async () => { await prisma.user.create({ data: { email: 'f@a.de', name: 'F' } }) - const users = - await prisma.$queryRaw`SELECT * FROM [dbo].[User] WHERE name = ${'F'}` + const users = await prisma.$queryRaw`SELECT * FROM [dbo].[User] WHERE name = ${'F'}` expect(users[0].name).toBe('F') }) @@ -229,10 +225,7 @@ describe('blog-env-mssql', () => { test('$queryRawUnsafe(string) with params', async () => { await prisma.user.create({ data: { email: 'b@a.de', name: 'B' } }) - const users = await prisma.$queryRawUnsafe( - 'SELECT * FROM [dbo].[User] WHERE name = @P1', - 'B', - ) + const users = await prisma.$queryRawUnsafe('SELECT * FROM [dbo].[User] WHERE name = @P1', 'B') expect(users).not.toHaveLength(0) }) }) @@ -246,9 +239,7 @@ describe('blog-env-mssql', () => { test('$executeRaw(sql``) with params', async () => { await prisma.user.create({ data: { email: 'd@b.de', name: 'D' } }) - const users = await prisma.$executeRaw( - sql`SELECT * FROM [dbo].[User] WHERE name = ${'D'}`, - ) + const users = await prisma.$executeRaw(sql`SELECT * FROM [dbo].[User] WHERE name = ${'D'}`) expect(users).not.toBe(0) }) @@ -260,8 +251,7 @@ describe('blog-env-mssql', () => { test('$executeRaw`` with params', async () => { await prisma.user.create({ data: { email: 'f@b.de', name: 'F' } }) - const users = - await prisma.$executeRaw`SELECT * FROM [dbo].[User] WHERE name = ${'F'}` + const users = await prisma.$executeRaw`SELECT * FROM [dbo].[User] WHERE name = ${'F'}` expect(users).not.toBe(0) }) @@ -281,10 +271,7 @@ describe('blog-env-mssql', () => { test('$executeRawUnsafe(string) with params', async () => { await prisma.user.create({ data: { email: 'b@b.de', name: 'B' } }) - const users = await prisma.$executeRawUnsafe( - 'SELECT * FROM [dbo].[User] WHERE name = @P1', - 'B', - ) + const users = await prisma.$executeRawUnsafe('SELECT * FROM [dbo].[User] WHERE name = @P1', 'B') expect(users).not.toBe(0) }) }) diff --git a/packages/client/src/__tests__/integration/happy/blog-env-postgresql/test.ts b/packages/client/src/__tests__/integration/happy/blog-env-postgresql/test.ts index 3ea9b8c5b999..0c83d97ec1d6 100644 --- a/packages/client/src/__tests__/integration/happy/blog-env-postgresql/test.ts +++ b/packages/client/src/__tests__/integration/happy/blog-env-postgresql/test.ts @@ -1,9 +1,6 @@ import { generateTestClient } from '../../../../utils/getTestClient' import type { SetupParams } from '../../../../utils/setupPostgres' -import { - setupPostgres, - tearDownPostgres, -} from '../../../../utils/setupPostgres' +import { setupPostgres, tearDownPostgres } from '../../../../utils/setupPostgres' test('Blog fixture: Postgres', async () => { await generateTestClient() @@ -12,9 +9,7 @@ test('Blog fixture: Postgres', async () => { const { PrismaClientValidationError, prismaVersion } = Prisma - let originalConnectionString = - process.env.TEST_POSTGRES_URI || - 'postgres://prisma:prisma@localhost:5432/tests' + let originalConnectionString = process.env.TEST_POSTGRES_URI || 'postgres://prisma:prisma@localhost:5432/tests' originalConnectionString += '-blog-env-postgresql' const SetupParams: SetupParams = { @@ -64,8 +59,7 @@ test('Blog fixture: Postgres', async () => { expect(rawQueryTemplate[0]['?column?']).toBe(1) // Test queryRaw`` with ${param} - const rawQueryTemplateWithParams = - await prisma.$queryRaw`SELECT * FROM "public"."User" WHERE name = ${'Alice'}` + const rawQueryTemplateWithParams = await prisma.$queryRaw`SELECT * FROM "public"."User" WHERE name = ${'Alice'}` expect(rawQueryTemplateWithParams[0].name).toBe('Alice') // Test executeRaw(string) @@ -77,8 +71,7 @@ test('Blog fixture: Postgres', async () => { expect(rawexecuteTemplate).toBe(1) // Test executeRaw`` with ${param} - const rawexecuteTemplateWithParams = - await prisma.$executeRaw`SELECT * FROM "public"."User" WHERE name = ${'Alice'}` + const rawexecuteTemplateWithParams = await prisma.$executeRaw`SELECT * FROM "public"."User" WHERE name = ${'Alice'}` expect(rawexecuteTemplateWithParams).toBe(1) // Test validation errors @@ -92,10 +85,7 @@ test('Blog fixture: Postgres', async () => { errorLogs.push(validationError) } - if ( - !validationError || - !(validationError instanceof PrismaClientValidationError) - ) { + if (!validationError || !(validationError instanceof PrismaClientValidationError)) { throw new Error(`Validation error is incorrect`) } @@ -242,9 +232,7 @@ test('Blog fixture: Postgres', async () => { jsonData: new Date(), }, }) - expect(resultJsonUpdateWithoutSetDateTime.title).toBe( - 'json array updated date', - ) + expect(resultJsonUpdateWithoutSetDateTime.title).toBe('json array updated date') await prisma.post.delete({ where: { id: resultJsonArray.id }, diff --git a/packages/client/src/__tests__/integration/happy/blog-update/test.ts b/packages/client/src/__tests__/integration/happy/blog-update/test.ts index 000a988a8e09..89f6a501672c 100644 --- a/packages/client/src/__tests__/integration/happy/blog-update/test.ts +++ b/packages/client/src/__tests__/integration/happy/blog-update/test.ts @@ -5,10 +5,7 @@ import { getTestClient } from '../../../../utils/getTestClient' const copyFile = promisify(fs.copyFile) test('blog-update', async () => { - await copyFile( - path.join(__dirname, 'dev.db'), - path.join(__dirname, 'dev-tmp.db'), - ) + await copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db')) const PrismaClient = await getTestClient() const prisma = new PrismaClient() diff --git a/packages/client/src/__tests__/integration/happy/blog/test.ts b/packages/client/src/__tests__/integration/happy/blog/test.ts index c50d5689e163..9f45ae1a8403 100644 --- a/packages/client/src/__tests__/integration/happy/blog/test.ts +++ b/packages/client/src/__tests__/integration/happy/blog/test.ts @@ -5,15 +5,7 @@ test('blog', async () => { const { PrismaClient, Prisma } = require('./node_modules/@prisma/client') - const { - prismaVersion, - sql, - raw, - join, - empty, - PrismaClientValidationError, - PrismaClientKnownRequestError, - } = Prisma + const { prismaVersion, sql, raw, join, empty, PrismaClientValidationError, PrismaClientKnownRequestError } = Prisma const requests: any[] = [] const db = new PrismaClient({ @@ -79,11 +71,7 @@ test('blog', async () => { expect(rawQuery[0]['1']).toBe(1) // Test queryRaw(string, values) - const rawQueryWithValues = await db.$queryRawUnsafe( - 'SELECT $1 AS name, $2 AS id', - 'Alice', - 42, - ) + const rawQueryWithValues = await db.$queryRawUnsafe('SELECT $1 AS name, $2 AS id', 'Alice', 42) expect(rawQueryWithValues[0]).toEqual({ name: 'Alice', @@ -95,8 +83,7 @@ test('blog', async () => { expect(rawQueryTemplate[0]['1']).toBe(1) // Test queryRaw`` with ${param} - const rawQueryTemplateWithParams = - await db.$queryRaw`SELECT * FROM User WHERE name = ${'Alice'}` + const rawQueryTemplateWithParams = await db.$queryRaw`SELECT * FROM User WHERE name = ${'Alice'}` expect(rawQueryTemplateWithParams[0].name).toBe('Alice') // Test queryRaw`` with prisma.sql`` @@ -115,24 +102,15 @@ test('blog', async () => { */ // Test .$executeRaw((string) - const executeRaw = await db.$executeRawUnsafe( - 'UPDATE User SET name = $1 WHERE id = $2', - 'name', - 'id', - ) + const executeRaw = await db.$executeRawUnsafe('UPDATE User SET name = $1 WHERE id = $2', 'name', 'id') expect(executeRaw).toBe(0) // Test .$executeRaw((string, values) - const executeRawWithValues = await db.$executeRawUnsafe( - 'UPDATE User SET name = $1 WHERE id = $2', - 'Alice', - 'id', - ) + const executeRawWithValues = await db.$executeRawUnsafe('UPDATE User SET name = $1 WHERE id = $2', 'Alice', 'id') expect(executeRawWithValues).toBe(0) // Test $executeRaw - const $executeRawTemplate = - await db.$executeRaw`UPDATE User SET name = ${'name'} WHERE id = ${'id'}` + const $executeRawTemplate = await db.$executeRaw`UPDATE User SET name = ${'name'} WHERE id = ${'id'}` expect($executeRawTemplate).toBe(0) // Test validation errors @@ -144,10 +122,7 @@ test('blog', async () => { } catch (e) { validationError = e } - if ( - !validationError || - !(validationError instanceof PrismaClientValidationError) - ) { + if (!validationError || !(validationError instanceof PrismaClientValidationError)) { throw new Error(`Validation error is incorrect`) } @@ -163,10 +138,7 @@ test('blog', async () => { } catch (e) { knownRequestError = e } - if ( - !knownRequestError || - !(knownRequestError instanceof PrismaClientKnownRequestError) - ) { + if (!knownRequestError || !(knownRequestError instanceof PrismaClientKnownRequestError)) { throw new Error(`Known request error is incorrect`) } else { if (!knownRequestError.message.includes('.user.create()')) { diff --git a/packages/client/src/__tests__/integration/happy/chmod/test.ts b/packages/client/src/__tests__/integration/happy/chmod/test.ts index d13d3781e414..1d550e32bbc6 100644 --- a/packages/client/src/__tests__/integration/happy/chmod/test.ts +++ b/packages/client/src/__tests__/integration/happy/chmod/test.ts @@ -1,10 +1,7 @@ import { getPlatform } from '@prisma/get-platform' import fs from 'fs' import path from 'path' -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' // Tests that no error is being thrown when the binary is manually set to chmod 644 because Client fixes that itself @@ -12,11 +9,7 @@ test('chmod', async () => { await generateTestClient() const platform = await getPlatform() if (getClientEngineType() !== ClientEngineType.Library) { - const binaryPath = path.join( - __dirname, - 'node_modules/.prisma/client', - `query-engine-${platform}`, - ) + const binaryPath = path.join(__dirname, 'node_modules/.prisma/client', `query-engine-${platform}`) fs.chmodSync(binaryPath, '644') } const { PrismaClient } = require('./node_modules/@prisma/client') diff --git a/packages/client/src/__tests__/integration/happy/client-engine/test.ts b/packages/client/src/__tests__/integration/happy/client-engine/test.ts index 6c72f5a95329..4fa381bf76cd 100644 --- a/packages/client/src/__tests__/integration/happy/client-engine/test.ts +++ b/packages/client/src/__tests__/integration/happy/client-engine/test.ts @@ -1,10 +1,7 @@ import fs from 'fs' import os from 'os' import path from 'path' -import { - ClientEngineType, - DEFAULT_CLIENT_ENGINE_TYPE, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, DEFAULT_CLIENT_ENGINE_TYPE } from '../../../../runtime/utils/getClientEngineType' import { generateTestClient } from '../../../../utils/getTestClient' const buildSchema = (engineType?: string) => ` @@ -57,32 +54,21 @@ function getExpectedEngine(engineType, envVar, envVarValue) { return DEFAULT_CLIENT_ENGINE_TYPE } function buildTests() { - const engineTypes = [ - ClientEngineType.Binary, - ClientEngineType.Library, - undefined, - ] + const engineTypes = [ClientEngineType.Binary, ClientEngineType.Library, undefined] const envVars = { PRISMA_CLIENT_ENGINE_TYPE: engineTypes, } for (const engineType of engineTypes) { for (const envVar in envVars) { for (const value of envVars[envVar]) { - const expectedClientEngine = getExpectedEngine( - engineType, - envVar, - value, - ) + const expectedClientEngine = getExpectedEngine(engineType, envVar, value) test(`expects(${expectedClientEngine}) | ${envVar}=${value} | engineType=${engineType}`, async () => { expect.assertions(2) const schema = buildSchema(engineType) // Setup Project in tmp dir const projectDir = fs.mkdtempSync(`${os.tmpdir()}${path.sep}`) - fs.copyFileSync( - path.join(__dirname, './dev.db'), - path.join(projectDir, 'dev.db'), - ) + fs.copyFileSync(path.join(__dirname, './dev.db'), path.join(projectDir, 'dev.db')) fs.writeFileSync(path.join(projectDir, 'schema.prisma'), schema) // Set ENV VAR @@ -92,10 +78,7 @@ function buildTests() { await generateTestClient(projectDir) // Run Tests - const { PrismaClient } = require(path.join( - projectDir, - 'node_modules/@prisma/client', - )) + const { PrismaClient } = require(path.join(projectDir, 'node_modules/@prisma/client')) const prisma = new PrismaClient() const users = await prisma.user.findMany() expect(users).toMatchInlineSnapshot(` diff --git a/packages/client/src/__tests__/integration/happy/createMany-mysql/test.ts b/packages/client/src/__tests__/integration/happy/createMany-mysql/test.ts index 26dcf22b736c..4c727618065e 100644 --- a/packages/client/src/__tests__/integration/happy/createMany-mysql/test.ts +++ b/packages/client/src/__tests__/integration/happy/createMany-mysql/test.ts @@ -80,12 +80,7 @@ describe('createMany(mysql)', () => { email: 'test@2.com', posts: { createMany: { - data: [ - { title: '1' }, - { title: '2' }, - { title: '3' }, - { title: '4' }, - ], + data: [{ title: '1' }, { title: '2' }, { title: '3' }, { title: '4' }], }, }, }, diff --git a/packages/client/src/__tests__/integration/happy/createMany-postgresql/test.ts b/packages/client/src/__tests__/integration/happy/createMany-postgresql/test.ts index 777140ae253d..695c60278464 100644 --- a/packages/client/src/__tests__/integration/happy/createMany-postgresql/test.ts +++ b/packages/client/src/__tests__/integration/happy/createMany-postgresql/test.ts @@ -84,12 +84,7 @@ describe('createMany(postgres)', () => { email: 'test@2.com', posts: { createMany: { - data: [ - { title: '1' }, - { title: '2' }, - { title: '3' }, - { title: '4' }, - ], + data: [{ title: '1' }, { title: '2' }, { title: '3' }, { title: '4' }], }, }, }, diff --git a/packages/client/src/__tests__/integration/happy/exhaustive-schema/dmmf-types.test.ts b/packages/client/src/__tests__/integration/happy/exhaustive-schema/dmmf-types.test.ts index 01b5d1df671c..22da2e8ccb1b 100644 --- a/packages/client/src/__tests__/integration/happy/exhaustive-schema/dmmf-types.test.ts +++ b/packages/client/src/__tests__/integration/happy/exhaustive-schema/dmmf-types.test.ts @@ -7,10 +7,7 @@ import { compileFile } from '../../../../utils/compileFile' * Makes sure, that the actual dmmf value and types are in match */ test('dmmf-types', async () => { - const datamodel = fs.readFileSync( - path.join(__dirname, 'schema.prisma'), - 'utf-8', - ) + const datamodel = fs.readFileSync(path.join(__dirname, 'schema.prisma'), 'utf-8') const dmmf = await getDMMF({ datamodel, }) diff --git a/packages/client/src/__tests__/integration/happy/exhaustive-schema/test.ts b/packages/client/src/__tests__/integration/happy/exhaustive-schema/test.ts index 4e7f74ad2ee5..16f4ebf3c070 100644 --- a/packages/client/src/__tests__/integration/happy/exhaustive-schema/test.ts +++ b/packages/client/src/__tests__/integration/happy/exhaustive-schema/test.ts @@ -5,10 +5,7 @@ import path from 'path' test('exhaustive-schema', async () => { await generateTestClient() - const generatedTypeScript = fs.readFileSync( - path.join(__dirname, './node_modules/.prisma/client/index.d.ts'), - 'utf-8', - ) + const generatedTypeScript = fs.readFileSync(path.join(__dirname, './node_modules/.prisma/client/index.d.ts'), 'utf-8') const generatedBrowserJS = fs.readFileSync( path.join(__dirname, './node_modules/.prisma/client/index-browser.js'), 'utf-8', diff --git a/packages/client/src/__tests__/integration/happy/insensitive-postgresql-feature-flag/test.ts b/packages/client/src/__tests__/integration/happy/insensitive-postgresql-feature-flag/test.ts index 792b53fb7682..d715405f7acb 100644 --- a/packages/client/src/__tests__/integration/happy/insensitive-postgresql-feature-flag/test.ts +++ b/packages/client/src/__tests__/integration/happy/insensitive-postgresql-feature-flag/test.ts @@ -1,15 +1,10 @@ import { getTestClient } from '../../../../utils/getTestClient' import type { SetupParams } from '../../../../utils/setupPostgres' -import { - setupPostgres, - tearDownPostgres, -} from '../../../../utils/setupPostgres' +import { setupPostgres, tearDownPostgres } from '../../../../utils/setupPostgres' test('insensitive-postgresql', async () => { const PrismaClient = await getTestClient() - let originalConnectionString = - process.env.TEST_POSTGRES_URI || - 'postgres://prisma:prisma@localhost:5432/tests' + let originalConnectionString = process.env.TEST_POSTGRES_URI || 'postgres://prisma:prisma@localhost:5432/tests' originalConnectionString += '-insensitive-postgresql-feature-flag' diff --git a/packages/client/src/__tests__/integration/happy/insensitive-postgresql/test.ts b/packages/client/src/__tests__/integration/happy/insensitive-postgresql/test.ts index cf08d0a939c9..46348ef0f53d 100644 --- a/packages/client/src/__tests__/integration/happy/insensitive-postgresql/test.ts +++ b/packages/client/src/__tests__/integration/happy/insensitive-postgresql/test.ts @@ -1,15 +1,10 @@ import { getTestClient } from '../../../../utils/getTestClient' import type { SetupParams } from '../../../../utils/setupPostgres' -import { - setupPostgres, - tearDownPostgres, -} from '../../../../utils/setupPostgres' +import { setupPostgres, tearDownPostgres } from '../../../../utils/setupPostgres' test('insensitive-postgresql', async () => { const PrismaClient = await getTestClient() - let originalConnectionString = - process.env.TEST_POSTGRES_URI || - 'postgres://prisma:prisma@localhost:5432/tests' + let originalConnectionString = process.env.TEST_POSTGRES_URI || 'postgres://prisma:prisma@localhost:5432/tests' originalConnectionString += '-insensitive-postgresql' diff --git a/packages/client/src/__tests__/integration/happy/interactive-transactions/test.ts b/packages/client/src/__tests__/integration/happy/interactive-transactions/test.ts index 0e8c248ea521..9fc371ae146b 100644 --- a/packages/client/src/__tests__/integration/happy/interactive-transactions/test.ts +++ b/packages/client/src/__tests__/integration/happy/interactive-transactions/test.ts @@ -44,15 +44,15 @@ describe('interactive transaction', () => { await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.user.findMany()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - - 39 - 40 await new Promise((res) => setTimeout(res, 6000)) - 41 -ā†’ 42 return prisma.user.findMany( - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. -`) + Invalid \`prisma.user.findMany()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + + 39 + 40 await new Promise((res) => setTimeout(res, 6000)) + 41 + ā†’ 42 return prisma.user.findMany( + Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. + `) }) /** @@ -79,15 +79,15 @@ Invalid \`prisma.user.findMany()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.user.findMany()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + Invalid \`prisma.user.findMany()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - 69 - 70 await new Promise((res) => setTimeout(res, 600)) - 71 -ā†’ 72 return prisma.user.findMany( - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. -`) + 69 + 70 await new Promise((res) => setTimeout(res, 600)) + 71 + ā†’ 72 return prisma.user.findMany( + Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. + `) }) /** @@ -112,12 +112,12 @@ Invalid \`prisma.user.findMany()\` invocation in ) await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` - - Invalid \`prisma.user.findMany()\` invocation: - - - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. - `) + + Invalid \`prisma.user.findMany()\` invocation: + + + Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. + `) }) /** @@ -134,9 +134,7 @@ Invalid \`prisma.user.findMany()\` invocation in throw new Error('you better rollback now') }) - await expect(result).rejects.toThrowErrorMatchingInlineSnapshot( - `you better rollback now`, - ) + await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(`you better rollback now`) const users = await prisma.user.findMany() @@ -173,11 +171,11 @@ Invalid \`prisma.user.findMany()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` - Invalid \`prisma.user.findMany()\` invocation: + Invalid \`prisma.user.findMany()\` invocation: - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. - `) + Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'. + `) const users = await prisma.user.findMany() @@ -218,15 +216,15 @@ Invalid \`prisma.user.findMany()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.user.create()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + Invalid \`prisma.user.create()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - 209 }, - 210 }) - 211 -ā†’ 212 await prisma.user.create( - Unique constraint failed on the fields: (\`email\`) -`) + 207 }, + 208 }) + 209 + ā†’ 210 await prisma.user.create( + Unique constraint failed on the fields: (\`email\`) + `) const users = await prisma.user.findMany() @@ -252,15 +250,15 @@ Invalid \`prisma.user.create()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`transactionBoundPrisma.user.create()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + Invalid \`transactionBoundPrisma.user.create()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - 243 }) - 244 - 245 const result = prisma.$transaction(async () => { -ā†’ 246 await transactionBoundPrisma.user.create( - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Committed'. -`) + 241 }) + 242 + 243 const result = prisma.$transaction(async () => { + ā†’ 244 await transactionBoundPrisma.user.create( + Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Committed'. + `) const users = await prisma.user.findMany() @@ -308,15 +306,15 @@ Invalid \`transactionBoundPrisma.user.create()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.user.create()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + Invalid \`prisma.user.create()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - 294 */ - 295 test('batching rollback', async () => { - 296 const result = prisma.$transaction([ -ā†’ 297 prisma.user.create( - Unique constraint failed on the fields: (\`email\`) -`) + 292 */ + 293 test('batching rollback', async () => { + 294 const result = prisma.$transaction([ + ā†’ 295 prisma.user.create( + Unique constraint failed on the fields: (\`email\`) + `) const users = await prisma.user.findMany() @@ -342,11 +340,11 @@ Invalid \`prisma.user.create()\` invocation in await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.executeRaw()\` invocation: + Invalid \`prisma.executeRaw()\` invocation: - Raw query failed. Code: \`2067\`. Message: \`UNIQUE constraint failed: User.email\` -`) + Raw query failed. Code: \`2067\`. Message: \`UNIQUE constraint failed: User.email\` + `) const users = await prisma.user.findMany() @@ -406,15 +404,15 @@ Invalid \`prisma.executeRaw()\` invocation: await expect(result).rejects.toThrowErrorMatchingInlineSnapshot(` -Invalid \`prisma.user.create()\` invocation in -/client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 + Invalid \`prisma.user.create()\` invocation in + /client/src/__tests__/integration/happy/interactive-transactions/test.ts:0:0 - 392 }) - 393 - 394 const result = prisma.$transaction([ -ā†’ 395 prisma.user.create( - Unique constraint failed on the fields: (\`email\`) -`) + 390 }) + 391 + 392 const result = prisma.$transaction([ + ā†’ 393 prisma.user.create( + Unique constraint failed on the fields: (\`email\`) + `) const users = await prisma.user.findMany() diff --git a/packages/client/src/__tests__/integration/happy/namedConstraints/test.ts b/packages/client/src/__tests__/integration/happy/namedConstraints/test.ts index 5fc8c73eb979..87aabeec1f52 100644 --- a/packages/client/src/__tests__/integration/happy/namedConstraints/test.ts +++ b/packages/client/src/__tests__/integration/happy/namedConstraints/test.ts @@ -32,15 +32,14 @@ describe('namedConstraints(sqlite) - with preview flag', () => { key2: 2, }, }) - const result: { key1: string; key2: number } | null = - await prisma.atAtId.findUnique({ - where: { - key1_key2: { - key1: 'data', - key2: 2, - }, + const result: { key1: string; key2: number } | null = await prisma.atAtId.findUnique({ + where: { + key1_key2: { + key1: 'data', + key2: 2, }, - }) + }, + }) expect(result).toEqual({ key1: 'data', key2: 2, @@ -54,15 +53,14 @@ describe('namedConstraints(sqlite) - with preview flag', () => { key2: 2, }, }) - const result: { key1: string; key2: number } | null = - await prisma.atAtIdNamed.findUnique({ - where: { - namedConstraintId: { - key1: 'data', - key2: 2, - }, + const result: { key1: string; key2: number } | null = await prisma.atAtIdNamed.findUnique({ + where: { + namedConstraintId: { + key1: 'data', + key2: 2, }, - }) + }, + }) expect(result).toEqual({ key1: 'data', key2: 2, @@ -76,15 +74,14 @@ describe('namedConstraints(sqlite) - with preview flag', () => { key2: 2, }, }) - const result: { key1: string; key2: number } | null = - await prisma.atAtUnique.findUnique({ - where: { - key1_key2: { - key1: 'data', - key2: 2, - }, + const result: { key1: string; key2: number } | null = await prisma.atAtUnique.findUnique({ + where: { + key1_key2: { + key1: 'data', + key2: 2, }, - }) + }, + }) expect(result).toEqual({ key1: 'data', key2: 2, @@ -98,15 +95,14 @@ describe('namedConstraints(sqlite) - with preview flag', () => { key2: 2, }, }) - const result: { key1: string; key2: number } | null = - await prisma.atAtUniqueNamed.findUnique({ - where: { - namedConstraintUnique: { - key1: 'data', - key2: 2, - }, + const result: { key1: string; key2: number } | null = await prisma.atAtUniqueNamed.findUnique({ + where: { + namedConstraintUnique: { + key1: 'data', + key2: 2, }, - }) + }, + }) expect(result).toEqual({ key1: 'data', key2: 2, diff --git a/packages/client/src/__tests__/integration/happy/prisma-promises/test.ts b/packages/client/src/__tests__/integration/happy/prisma-promises/test.ts index dd79d73f2b50..e28f1745b073 100644 --- a/packages/client/src/__tests__/integration/happy/prisma-promises/test.ts +++ b/packages/client/src/__tests__/integration/happy/prisma-promises/test.ts @@ -10,9 +10,7 @@ describe('prisma promises', () => { const remove = await prisma.user.deleteMany().catch(handler) const queryRaw = await prisma.$queryRawUnsafe('SELECT 1').catch(handler) - const executeRaw = await prisma - .$executeRawUnsafe('DELETE FROM User') - .catch(handler) + const executeRaw = await prisma.$executeRawUnsafe('DELETE FROM User').catch(handler) const findMany = await prisma.user.findMany().catch(handler) expect(remove).toMatchInlineSnapshot(` @@ -43,9 +41,7 @@ describe('prisma promises', () => { const remove = await prisma.user.deleteMany().finally(handler) const queryRaw = await prisma.$queryRawUnsafe('SELECT 1').finally(handler) - const executeRaw = await prisma - .$executeRawUnsafe('DELETE FROM User') - .finally(handler) + const executeRaw = await prisma.$executeRawUnsafe('DELETE FROM User').finally(handler) const findMany = await prisma.user.findMany().finally(handler) expect(remove).toMatchInlineSnapshot(` diff --git a/packages/client/src/__tests__/integration/happy/raw-transactions/test.ts b/packages/client/src/__tests__/integration/happy/raw-transactions/test.ts index dfedcb008b3f..ad16eeb46f47 100644 --- a/packages/client/src/__tests__/integration/happy/raw-transactions/test.ts +++ b/packages/client/src/__tests__/integration/happy/raw-transactions/test.ts @@ -289,10 +289,7 @@ describe('transaction', () => { }) const res = await Promise.all([ - prisma.$transaction([ - prisma.$queryRaw`SELECT * FROM "User"`, - prisma.$queryRaw`SELECT * FROM "Post"`, - ]), + prisma.$transaction([prisma.$queryRaw`SELECT * FROM "User"`, prisma.$queryRaw`SELECT * FROM "Post"`]), prisma.$transaction([prisma.user.findFirst(), prisma.post.findFirst()]), ]) await prisma.$disconnect() diff --git a/packages/client/src/__tests__/integration/happy/restart/test.ts b/packages/client/src/__tests__/integration/happy/restart/test.ts index e75b64f867ae..899b05db592b 100644 --- a/packages/client/src/__tests__/integration/happy/restart/test.ts +++ b/packages/client/src/__tests__/integration/happy/restart/test.ts @@ -1,7 +1,4 @@ -import { - ClientEngineType, - getClientEngineType, -} from '../../../../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../../../../runtime/utils/getClientEngineType' import { getTestClient } from '../../../../utils/getTestClient' // Does Prisma Client restart the QE when it is killed for some reason? diff --git a/packages/client/src/__tests__/integration/happy/transaction/test.ts b/packages/client/src/__tests__/integration/happy/transaction/test.ts index 8ee252fe4743..f9f3afae5240 100644 --- a/packages/client/src/__tests__/integration/happy/transaction/test.ts +++ b/packages/client/src/__tests__/integration/happy/transaction/test.ts @@ -19,10 +19,7 @@ function clean(array: any[]) { } beforeAll(() => { - fs.copyFileSync( - path.join(__dirname, 'dev.db'), - path.join(__dirname, 'dev2.db'), - ) + fs.copyFileSync(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev2.db')) }) test('transaction', async () => { diff --git a/packages/client/src/__tests__/integration/happy/uds/test.ts b/packages/client/src/__tests__/integration/happy/uds/test.ts index bc45a46ba8be..33755c2e671e 100644 --- a/packages/client/src/__tests__/integration/happy/uds/test.ts +++ b/packages/client/src/__tests__/integration/happy/uds/test.ts @@ -5,15 +5,7 @@ test('blog', async () => { const { PrismaClient, Prisma } = require('./node_modules/@prisma/client') - const { - prismaVersion, - sql, - raw, - join, - empty, - PrismaClientValidationError, - PrismaClientKnownRequestError, - } = Prisma + const { prismaVersion, sql, raw, join, empty, PrismaClientValidationError, PrismaClientKnownRequestError } = Prisma const requests: any[] = [] const db = new PrismaClient({ @@ -79,11 +71,7 @@ test('blog', async () => { expect(rawQuery[0]['1']).toBe(1) // Test queryRaw(string, values) - const rawQueryWithValues = await db.$queryRawUnsafe( - 'SELECT $1 AS name, $2 AS id', - 'Alice', - 42, - ) + const rawQueryWithValues = await db.$queryRawUnsafe('SELECT $1 AS name, $2 AS id', 'Alice', 42) expect(rawQueryWithValues[0]).toEqual({ name: 'Alice', @@ -95,8 +83,7 @@ test('blog', async () => { expect(rawQueryTemplate[0]['1']).toBe(1) // Test queryRaw`` with ${param} - const rawQueryTemplateWithParams = - await db.$queryRaw`SELECT * FROM User WHERE name = ${'Alice'}` + const rawQueryTemplateWithParams = await db.$queryRaw`SELECT * FROM User WHERE name = ${'Alice'}` expect(rawQueryTemplateWithParams[0].name).toBe('Alice') // Test queryRaw`` with prisma.sql`` @@ -115,24 +102,15 @@ test('blog', async () => { */ // Test .$executeRaw((string) - const executeRaw = await db.$executeRawUnsafe( - 'UPDATE User SET name = $1 WHERE id = $2', - 'name', - 'id', - ) + const executeRaw = await db.$executeRawUnsafe('UPDATE User SET name = $1 WHERE id = $2', 'name', 'id') expect(executeRaw).toBe(0) // Test .$executeRaw((string, values) - const executeRawWithValues = await db.$executeRawUnsafe( - 'UPDATE User SET name = $1 WHERE id = $2', - 'Alice', - 'id', - ) + const executeRawWithValues = await db.$executeRawUnsafe('UPDATE User SET name = $1 WHERE id = $2', 'Alice', 'id') expect(executeRawWithValues).toBe(0) // Test $executeRaw - const $executeRawTemplate = - await db.$executeRaw`UPDATE User SET name = ${'name'} WHERE id = ${'id'}` + const $executeRawTemplate = await db.$executeRaw`UPDATE User SET name = ${'name'} WHERE id = ${'id'}` expect($executeRawTemplate).toBe(0) // Test validation errors @@ -144,10 +122,7 @@ test('blog', async () => { } catch (e) { validationError = e } - if ( - !validationError || - !(validationError instanceof PrismaClientValidationError) - ) { + if (!validationError || !(validationError instanceof PrismaClientValidationError)) { throw new Error(`Validation error is incorrect`) } @@ -163,10 +138,7 @@ test('blog', async () => { } catch (e) { knownRequestError = e } - if ( - !knownRequestError || - !(knownRequestError instanceof PrismaClientKnownRequestError) - ) { + if (!knownRequestError || !(knownRequestError instanceof PrismaClientKnownRequestError)) { throw new Error(`Known request error is incorrect`) } else { if (!knownRequestError.message.includes('.user.create()')) { diff --git a/packages/client/src/__tests__/integration/happy/uncheckedScalarInputs/test.ts b/packages/client/src/__tests__/integration/happy/uncheckedScalarInputs/test.ts index 9e2db60b16b1..f8c5c337d688 100644 --- a/packages/client/src/__tests__/integration/happy/uncheckedScalarInputs/test.ts +++ b/packages/client/src/__tests__/integration/happy/uncheckedScalarInputs/test.ts @@ -5,10 +5,7 @@ import { getTestClient } from '../../../../utils/getTestClient' const copyFile = promisify(fs.copyFile) test('uncheckedScalarInputs', async () => { - await copyFile( - path.join(__dirname, 'dev.db'), - path.join(__dirname, 'dev-tmp.db'), - ) + await copyFile(path.join(__dirname, 'dev.db'), path.join(__dirname, 'dev-tmp.db')) const PrismaClient = await getTestClient() const prisma = new PrismaClient() await prisma.user.deleteMany() diff --git a/packages/client/src/__tests__/json.test.ts b/packages/client/src/__tests__/json.test.ts index 0ad134c77aef..6c99dcb83bb0 100644 --- a/packages/client/src/__tests__/json.test.ts +++ b/packages/client/src/__tests__/json.test.ts @@ -121,9 +121,7 @@ describe('json', () => { rootTypeName: 'query', rootField: 'findManyUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('should be able to update json', () => { diff --git a/packages/client/src/__tests__/noArgs.test.ts b/packages/client/src/__tests__/noArgs.test.ts index 17728ff422ab..67ef544356ad 100644 --- a/packages/client/src/__tests__/noArgs.test.ts +++ b/packages/client/src/__tests__/noArgs.test.ts @@ -15,9 +15,7 @@ describe('no args', () => { rootTypeName: 'query', rootField: 'findUniqueUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('findMany', () => { @@ -51,9 +49,7 @@ describe('no args', () => { rootTypeName: 'query', rootField: 'findManyUser', }) - expect(() => - document.validate(select, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() expect(String(document)).toMatchInlineSnapshot(` query { findManyUser(where: { @@ -74,9 +70,7 @@ describe('no args', () => { rootTypeName: 'mutation', rootField: 'createOneUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('deleteMany', () => { const document = makeDocument({ @@ -101,9 +95,7 @@ describe('no args', () => { rootTypeName: 'mutation', rootField: 'deleteOneUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('updateMany', () => { const document = makeDocument({ @@ -112,9 +104,7 @@ describe('no args', () => { rootTypeName: 'mutation', rootField: 'updateManyUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('upsertOne', () => { const document = makeDocument({ @@ -123,9 +113,7 @@ describe('no args', () => { rootTypeName: 'mutation', rootField: 'upsertOneUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) test('nested create', () => { const document = makeDocument({ @@ -149,8 +137,6 @@ describe('no args', () => { rootTypeName: 'mutation', rootField: 'createOneUser', }) - expect(() => - document.validate(undefined, false, 'user', 'colorless'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(undefined, false, 'user', 'colorless')).toThrowErrorMatchingSnapshot() }) }) diff --git a/packages/client/src/__tests__/relationWhereTransformation.test.ts b/packages/client/src/__tests__/relationWhereTransformation.test.ts index 699855dfc895..1af636535c54 100644 --- a/packages/client/src/__tests__/relationWhereTransformation.test.ts +++ b/packages/client/src/__tests__/relationWhereTransformation.test.ts @@ -45,9 +45,7 @@ describe('relation where transformation', () => { rootField: 'findManyArtist', }) - expect(() => - document.validate(select, false, 'users'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'users')).toThrowErrorMatchingSnapshot() }) test('throw correctly for incorrect deep scalar', () => { @@ -84,9 +82,7 @@ describe('relation where transformation', () => { rootTypeName: 'query', rootField: 'findManyArtist', }) - expect(() => - document.validate(select, false, 'users'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'users')).toThrowErrorMatchingSnapshot() }) test('throw correctly for deep at least one error', () => { const select = { @@ -120,8 +116,6 @@ describe('relation where transformation', () => { rootTypeName: 'query', rootField: 'findManyArtist', }) - expect(() => - document.validate(select, false, 'artists'), - ).toThrowErrorMatchingSnapshot() + expect(() => document.validate(select, false, 'artists')).toThrowErrorMatchingSnapshot() }) }) diff --git a/packages/client/src/__tests__/resolveDatasources.test.ts b/packages/client/src/__tests__/resolveDatasources.test.ts index 5d14682e70a8..42f00b6a85d1 100644 --- a/packages/client/src/__tests__/resolveDatasources.test.ts +++ b/packages/client/src/__tests__/resolveDatasources.test.ts @@ -1,46 +1,31 @@ import type { DataSource } from '@prisma/generator-helper' -import { - datasourceToDatasourceOverwrite, - serializeDatasources, -} from '../generation/serializeDatasources' +import { datasourceToDatasourceOverwrite, serializeDatasources } from '../generation/serializeDatasources' import { absolutizeRelativePath } from '../utils/resolveDatasources' const cwd = '/Users/tim/project/prisma' const outputDir = '/Users/tim/project/node_modules/@prisma/client/runtime' test('absolutizeRelativePath', () => { - expect( - absolutizeRelativePath('file:db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../prisma/db.db`) - expect( - absolutizeRelativePath('file:/db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../../../../db.db`) - expect( - absolutizeRelativePath('file:../db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../db.db`) - expect( - absolutizeRelativePath('file:./db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../prisma/db.db`) + expect(absolutizeRelativePath('file:db.db', cwd, outputDir)).toMatchInlineSnapshot(`../../../../prisma/db.db`) + expect(absolutizeRelativePath('file:/db.db', cwd, outputDir)).toMatchInlineSnapshot(`../../../../../../../db.db`) + expect(absolutizeRelativePath('file:../db.db', cwd, outputDir)).toMatchInlineSnapshot(`../../../../db.db`) + expect(absolutizeRelativePath('file:./db.db', cwd, outputDir)).toMatchInlineSnapshot(`../../../../prisma/db.db`) + expect(absolutizeRelativePath('file:asd/another/dir/db.db', cwd, outputDir)).toMatchInlineSnapshot( + `../../../../prisma/asd/another/dir/db.db`, + ) + expect(absolutizeRelativePath('file:/some/random/dir/db.db', cwd, outputDir)).toMatchInlineSnapshot( + `../../../../../../../some/random/dir/db.db`, + ) expect( - absolutizeRelativePath('file:asd/another/dir/db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../prisma/asd/another/dir/db.db`) - expect( - absolutizeRelativePath('file:/some/random/dir/db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../../../../some/random/dir/db.db`) - expect( - absolutizeRelativePath( - 'file:/Users/tim/project/node_modules/@prisma/client/runtime', - cwd, - outputDir, - ), + absolutizeRelativePath('file:/Users/tim/project/node_modules/@prisma/client/runtime', cwd, outputDir), ).toMatchInlineSnapshot(``) - expect( - absolutizeRelativePath('file:../another-dir/db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../another-dir/db.db`) - expect( - absolutizeRelativePath('file:./some/dir/db.db', cwd, outputDir), - ).toMatchInlineSnapshot(`../../../../prisma/some/dir/db.db`) + expect(absolutizeRelativePath('file:../another-dir/db.db', cwd, outputDir)).toMatchInlineSnapshot( + `../../../../another-dir/db.db`, + ) + expect(absolutizeRelativePath('file:./some/dir/db.db', cwd, outputDir)).toMatchInlineSnapshot( + `../../../../prisma/some/dir/db.db`, + ) }) const datasources: DataSource[] = [ @@ -87,8 +72,7 @@ const datasources: DataSource[] = [ ] test('serializeDatasources', () => { - expect(serializeDatasources(datasources.map(datasourceToDatasourceOverwrite))) - .toMatchInlineSnapshot(` + expect(serializeDatasources(datasources.map(datasourceToDatasourceOverwrite))).toMatchInlineSnapshot(` [ { "name": "db", diff --git a/packages/client/src/__tests__/scalarWhereTransformation.test.ts b/packages/client/src/__tests__/scalarWhereTransformation.test.ts index 5f0510aa9898..f2ecf0af2b7b 100644 --- a/packages/client/src/__tests__/scalarWhereTransformation.test.ts +++ b/packages/client/src/__tests__/scalarWhereTransformation.test.ts @@ -359,9 +359,7 @@ describe('scalar where transformation', () => { } `) - expect(document.validate(select, false, 'tests')).toMatchInlineSnapshot( - `undefined`, - ) + expect(document.validate(select, false, 'tests')).toMatchInlineSnapshot(`undefined`) }) test('validate uuid scalar filter should error when invalid input', () => { @@ -392,9 +390,7 @@ describe('scalar where transformation', () => { `) try { - expect(document.validate(select, false, 'tests')).toMatchInlineSnapshot( - `undefined`, - ) + expect(document.validate(select, false, 'tests')).toMatchInlineSnapshot(`undefined`) } catch (e) { expect(stripAnsi(e.message)).toMatchInlineSnapshot(` " diff --git a/packages/client/src/__tests__/scripts/postinstall.test.ts b/packages/client/src/__tests__/scripts/postinstall.test.ts index 20a414e2415a..71572419e0fe 100644 --- a/packages/client/src/__tests__/scripts/postinstall.test.ts +++ b/packages/client/src/__tests__/scripts/postinstall.test.ts @@ -49,9 +49,7 @@ describe('npm_config_user_agent', () => { process.env.npm_config_user_agent = value } delete process.env.npm_config_user_agent - expect(getPostInstallTrigger()).toEqual( - `MISSING_NPM_CONFIG_USER_AGENT foo bar`, - ) + expect(getPostInstallTrigger()).toEqual(`MISSING_NPM_CONFIG_USER_AGENT foo bar`) }, ) @@ -59,9 +57,7 @@ describe('npm_config_user_agent', () => { 'if npm_config_user_agent not parsable then falls back to UNKNOWN_NPM_CONFIG_USER_AGENT', (userAgentString) => { process.env.npm_config_user_agent = userAgentString - expect(getPostInstallTrigger()).toEqual( - `UNKNOWN_NPM_CONFIG_USER_AGENT(${userAgentString}) foo bar`, - ) + expect(getPostInstallTrigger()).toEqual(`UNKNOWN_NPM_CONFIG_USER_AGENT(${userAgentString}) foo bar`) }, ) }) diff --git a/packages/client/src/__tests__/select.test.ts b/packages/client/src/__tests__/select.test.ts index cb887a2e5e0c..d58bb7b032c5 100644 --- a/packages/client/src/__tests__/select.test.ts +++ b/packages/client/src/__tests__/select.test.ts @@ -21,8 +21,7 @@ describe('select validation', () => { AND: [ { age_gt: 10123123123, - this_is_completely_arbitrary: - 'veryLongNameGoIntoaNewLineNow@gmail.com', + this_is_completely_arbitrary: 'veryLongNameGoIntoaNewLineNow@gmail.com', }, { age_gt: 10123123123, diff --git a/packages/client/src/__tests__/serializeRawParameters.test.ts b/packages/client/src/__tests__/serializeRawParameters.test.ts index 0be7f71a6fa8..663184b3ad47 100644 --- a/packages/client/src/__tests__/serializeRawParameters.test.ts +++ b/packages/client/src/__tests__/serializeRawParameters.test.ts @@ -61,10 +61,7 @@ describe('serializeRawParemeters', () => { test('nested', () => { const data = { deep: { - date: [ - new Date('2020-06-22T17:07:16.348Z'), - new Date('2020-06-22T17:07:16.348Z'), - ], + date: [new Date('2020-06-22T17:07:16.348Z'), new Date('2020-06-22T17:07:16.348Z')], bigInt: [BigInt('321804719213721'), BigInt('321804719213721')], }, } diff --git a/packages/client/src/__tests__/unpack.test.ts b/packages/client/src/__tests__/unpack.test.ts index 1598e8ac9c48..f00ad9a6d02d 100644 --- a/packages/client/src/__tests__/unpack.test.ts +++ b/packages/client/src/__tests__/unpack.test.ts @@ -26,18 +26,10 @@ describe('getField', () => { rootField: 'findUniqueUser', }) - expect(getField(document, ['findUniqueUser']).name).toMatchInlineSnapshot( - `findUniqueUser`, - ) - expect( - getField(document, ['findUniqueUser', 'id']).name, - ).toMatchInlineSnapshot(`id`) - expect( - getField(document, ['findUniqueUser', 'posts']).name, - ).toMatchInlineSnapshot(`posts`) - expect( - getField(document, ['findUniqueUser', 'posts', 'title']).name, - ).toMatchInlineSnapshot(`title`) + expect(getField(document, ['findUniqueUser']).name).toMatchInlineSnapshot(`findUniqueUser`) + expect(getField(document, ['findUniqueUser', 'id']).name).toMatchInlineSnapshot(`id`) + expect(getField(document, ['findUniqueUser', 'posts']).name).toMatchInlineSnapshot(`posts`) + expect(getField(document, ['findUniqueUser', 'posts', 'title']).name).toMatchInlineSnapshot(`title`) }) }) @@ -113,8 +105,7 @@ describe('unpack', () => { createdAt: '2019-11-17T09:56:37.690Z', updatedAt: '2019-11-17T09:56:37.690Z', published: true, - title: - "One thing for sure: If you don't read the bible, you can't belong to the tribal.", + title: "One thing for sure: If you don't read the bible, you can't belong to the tribal.", }, ], } diff --git a/packages/client/src/generation/TSClient/Args.ts b/packages/client/src/generation/TSClient/Args.ts index 23179c5bf362..d965007d9177 100644 --- a/packages/client/src/generation/TSClient/Args.ts +++ b/packages/client/src/generation/TSClient/Args.ts @@ -45,9 +45,7 @@ export class ArgsType implements Generatable { }, ] - const hasRelationField = this.type.fields.some( - (f) => f.outputType.location === 'outputObjectTypes', - ) + const hasRelationField = this.type.fields.some((f) => f.outputType.location === 'outputObjectTypes') if (hasRelationField) { const includeName = getIncludeName(name) @@ -71,9 +69,7 @@ export class ArgsType implements Generatable { comment: `Choose, which related nodes to fetch as well.`, }) } - const addRejectOnNotFound = - action === DMMF.ModelAction.findUnique || - action === DMMF.ModelAction.findFirst + const addRejectOnNotFound = action === DMMF.ModelAction.findUnique || action === DMMF.ModelAction.findFirst if (addRejectOnNotFound) { bothArgsOptional.push({ name: 'rejectOnNotFound', @@ -99,10 +95,7 @@ export class ArgsType implements Generatable { * ${name} ${action ? action : 'without action'} */ export type ${modelArgName} = { -${indent( - bothArgsOptional.map((arg) => new InputField(arg).toTS()).join('\n'), - TAB_SIZE, -)} +${indent(bothArgsOptional.map((arg) => new InputField(arg).toTS()).join('\n'), TAB_SIZE)} } ` } diff --git a/packages/client/src/generation/TSClient/Count.ts b/packages/client/src/generation/TSClient/Count.ts index 85b1aca912a3..d84263890251 100644 --- a/packages/client/src/generation/TSClient/Count.ts +++ b/packages/client/src/generation/TSClient/Count.ts @@ -55,11 +55,7 @@ export type ${getSelectName(name)} = { ${indent( type.fields .map( - (f) => - `${f.name}?: boolean` + - (f.outputType.location === 'outputObjectTypes' - ? ` | ${getFieldArgName(f)}` - : ''), + (f) => `${f.name}?: boolean` + (f.outputType.location === 'outputObjectTypes' ? ` | ${getFieldArgName(f)}` : ''), ) .join('\n'), TAB_SIZE, @@ -91,21 +87,13 @@ class CountDelegate implements Generatable { const model = this.dmmf.modelMap[name] const actions = Object.entries(mapping).filter( - ([key, value]) => - key !== 'model' && - key !== 'plural' && - key !== 'aggregate' && - key !== 'groupBy' && - value, + ([key, value]) => key !== 'model' && key !== 'plural' && key !== 'aggregate' && key !== 'groupBy' && value, ) const groupByArgsName = getGroupByArgsName(name) const countArgsName = getModelArgName(name, DMMF.ModelAction.count) return `\ type ${countArgsName} = Merge< - Omit<${getModelArgName( - name, - DMMF.ModelAction.findMany, - )}, 'select' | 'include'> & { + Omit<${getModelArgName(name, DMMF.ModelAction.findMany)}, 'select' | 'include'> & { select?: ${getCountAggregateInputName(name)} | true } > @@ -136,9 +124,7 @@ ${indent(getMethodJSDoc(DMMF.ModelAction.count, mapping, model), TAB_SIZE)} > ${indent(getMethodJSDoc(DMMF.ModelAction.aggregate, mapping, model), TAB_SIZE)} - aggregate(args: Subset(args: Subset): PrismaPromise<${getAggregateGetName(name)}> @@ -233,13 +219,9 @@ ${indent( .map((f) => { const fieldTypeName = (f.outputType.type as DMMF.OutputType).name return ` -${f.name}(args?: Subset): ${getSelectReturnType({ +${f.name}(args?: Subset): ${getSelectReturnType({ name: fieldTypeName, - actionName: f.outputType.isList - ? DMMF.ModelAction.findMany - : DMMF.ModelAction.findUnique, + actionName: f.outputType.isList ? DMMF.ModelAction.findMany : DMMF.ModelAction.findUnique, hideCondition: false, isField: true, renderPromise: true, diff --git a/packages/client/src/generation/TSClient/Enum.ts b/packages/client/src/generation/TSClient/Enum.ts index bde56085a4a0..e76e8100f1c8 100644 --- a/packages/client/src/generation/TSClient/Enum.ts +++ b/packages/client/src/generation/TSClient/Enum.ts @@ -16,9 +16,7 @@ export class Enum implements Generatable { } public toJS(): string { const { type } = this - return `exports.${this.useNamespace ? 'Prisma.' : ''}${ - type.name - } = makeEnum({ + return `exports.${this.useNamespace ? 'Prisma.' : ''}${type.name} = makeEnum({ ${indent(type.values.map((v) => `${v}: '${v}'`).join(',\n'), TAB_SIZE)} });` } diff --git a/packages/client/src/generation/TSClient/Input.ts b/packages/client/src/generation/TSClient/Input.ts index 6d6470546a79..7184bba46747 100644 --- a/packages/client/src/generation/TSClient/Input.ts +++ b/packages/client/src/generation/TSClient/Input.ts @@ -1,10 +1,6 @@ import indent from 'indent-string' import type { DMMF } from '../../runtime/dmmf-types' -import { - argIsInputType, - GraphQLScalarToJSTypeTable, - JSOutputTypeToInputType, -} from '../../runtime/utils/common' +import { argIsInputType, GraphQLScalarToJSTypeTable, JSOutputTypeToInputType } from '../../runtime/utils/common' import { uniqueBy } from '../../runtime/utils/uniqueBy' import { TAB_SIZE } from './constants' import type { Generatable } from './Generatable' @@ -26,11 +22,7 @@ export class InputField implements Generatable { : '' const comment = `${field.comment ? field.comment + '\n' : ''}${deprecated}` const jsdoc = comment ? wrapComment(comment) + '\n' : '' - const fieldType = stringifyInputTypes( - field.inputTypes, - this.prefixFilter, - this.noEnumerable, - ) + const fieldType = stringifyInputTypes(field.inputTypes, this.prefixFilter, this.noEnumerable) return `${jsdoc}${field.name}${optionalStr}: ${fieldType}` } @@ -106,33 +98,20 @@ function stringifyInputTypes( } } - const filteredInputTypes = inputTypes.filter( - (t, i) => !singularPairIndexes.has(i), - ) - - const inputObjectTypes = filteredInputTypes.filter( - (t) => t.location === 'inputObjectTypes', - ) - - const nonInputObjectTypes = filteredInputTypes.filter( - (t) => t.location !== 'inputObjectTypes', - ) - - const stringifiedInputObjectTypes = inputObjectTypes.reduce( - (acc, curr) => { - const currentStringified = stringifyInputType( - curr, - prefixFilter, - noEnumerable, - ) - if (acc.length > 0) { - return `XOR<${acc}, ${currentStringified}>` - } + const filteredInputTypes = inputTypes.filter((t, i) => !singularPairIndexes.has(i)) + + const inputObjectTypes = filteredInputTypes.filter((t) => t.location === 'inputObjectTypes') - return currentStringified - }, - '', - ) + const nonInputObjectTypes = filteredInputTypes.filter((t) => t.location !== 'inputObjectTypes') + + const stringifiedInputObjectTypes = inputObjectTypes.reduce((acc, curr) => { + const currentStringified = stringifyInputType(curr, prefixFilter, noEnumerable) + if (acc.length > 0) { + return `XOR<${acc}, ${currentStringified}>` + } + + return currentStringified + }, '') const stringifiedNonInputTypes = nonInputObjectTypes .map((type) => stringifyInputType(type, prefixFilter, noEnumerable)) @@ -150,10 +129,7 @@ function stringifyInputTypes( } export class InputType implements Generatable { - constructor( - protected readonly type: DMMF.InputType, - protected readonly collector?: ExportCollector, - ) {} + constructor(protected readonly type: DMMF.InputType, protected readonly collector?: ExportCollector) {} public toTS(): string { const { type } = this this.collector?.addSymbol(type.name) @@ -165,10 +141,7 @@ ${indent( fields .map((arg) => { // This disables enumerable on JsonFilter path argument - const noEnumerable = - type.name.includes('Json') && - type.name.includes('Filter') && - arg.name === 'path' + const noEnumerable = type.name.includes('Json') && type.name.includes('Filter') && arg.name === 'path' return new InputField(arg, false, noEnumerable).toTS() }) .join('\n'), diff --git a/packages/client/src/generation/TSClient/Model.ts b/packages/client/src/generation/TSClient/Model.ts index 1e2b5de1c100..6e06259f051d 100644 --- a/packages/client/src/generation/TSClient/Model.ts +++ b/packages/client/src/generation/TSClient/Model.ts @@ -30,13 +30,7 @@ import { TAB_SIZE } from './constants' import type { Generatable } from './Generatable' import { TS } from './Generatable' import type { ExportCollector } from './helpers' -import { - getArgFieldJSDoc, - getArgs, - getGenericMethod, - getMethodJSDoc, - wrapComment, -} from './helpers' +import { getArgFieldJSDoc, getArgs, getGenericMethod, getMethodJSDoc, wrapComment } from './helpers' import { InputType } from './Input' import { ModelOutputField, OutputType } from './Output' import { PayloadType } from './Payload' @@ -54,9 +48,7 @@ export class Model implements Generatable { ) { this.type = dmmf.outputTypeMap[model.name] this.outputType = new OutputType(dmmf, this.type) - this.mapping = dmmf.mappings.modelOperations.find( - (m) => m.model === model.name, - )! + this.mapping = dmmf.mappings.modelOperations.find((m) => m.model === model.name)! } protected get argsTypes(): Generatable[] { const { mapping, model } = this @@ -72,32 +64,12 @@ export class Model implements Generatable { } const field = this.dmmf.rootFieldMap[fieldName] if (!field) { - throw new Error( - `Oops this must not happen. Could not find field ${fieldName} on either Query or Mutation`, - ) + throw new Error(`Oops this must not happen. Could not find field ${fieldName} on either Query or Mutation`) } - if ( - action === 'updateMany' || - action === 'deleteMany' || - action === 'createMany' - ) { - argsTypes.push( - new MinimalArgsType( - field.args, - model, - action as DMMF.ModelAction, - this.collector, - ), - ) + if (action === 'updateMany' || action === 'deleteMany' || action === 'createMany') { + argsTypes.push(new MinimalArgsType(field.args, model, action as DMMF.ModelAction, this.collector)) } else if (action !== 'groupBy' && action !== 'aggregate') { - argsTypes.push( - new ArgsType( - field.args, - this.type, - action as DMMF.ModelAction, - this.collector, - ), - ) + argsTypes.push(new ArgsType(field.args, this.type, action as DMMF.ModelAction, this.collector)) } } @@ -115,9 +87,7 @@ export class Model implements Generatable { const groupByRootField = this.dmmf.rootFieldMap[mapping!.groupBy!] if (!groupByRootField) { - throw new Error( - `Could not find groupBy root field for model ${model.name}. Mapping: ${mapping?.groupBy}`, - ) + throw new Error(`Could not find groupBy root field for model ${model.name}. Mapping: ${mapping?.groupBy}`) } const groupByArgsName = getGroupByArgsName(model.name) @@ -137,9 +107,9 @@ ${indent( .filter((f) => f.outputType.location === 'outputObjectTypes') .map((f) => { if (f.outputType.location === 'outputObjectTypes') { - return `${f.name}?: ${getAggregateInputType( - (f.outputType.type as DMMF.OutputType).name, - )}${f.name === '_count' ? ' | true' : ''}` + return `${f.name}?: ${getAggregateInputType((f.outputType.type as DMMF.OutputType).name)}${ + f.name === '_count' ? ' | true' : '' + }` } // to make TS happy, but can't happen, as we filter for outputObjectTypes @@ -153,9 +123,7 @@ ${indent( ${new OutputType(this.dmmf, groupByType).toTS()} -type ${getGroupByPayloadName( - model.name, - )} = Promise< +type ${getGroupByPayloadName(model.name)} = Promise< Array< PickArray<${groupByType.name}, T['by']> & { @@ -173,19 +141,13 @@ type ${getGroupByPayloadName( const { model, mapping } = this let aggregateType = this.dmmf.outputTypeMap[getAggregateName(model.name)] if (!aggregateType) { - throw new Error( - `Could not get aggregate type "${getAggregateName(model.name)}" for "${ - model.name - }"`, - ) + throw new Error(`Could not get aggregate type "${getAggregateName(model.name)}" for "${model.name}"`) } aggregateType = klona(aggregateType) const aggregateRootField = this.dmmf.rootFieldMap[mapping!.aggregate!] if (!aggregateRootField) { - throw new Error( - `Could not find aggregate root field for model ${model.name}. Mapping: ${mapping?.aggregate}`, - ) + throw new Error(`Could not find aggregate root field for model ${model.name}. Mapping: ${mapping?.aggregate}`) } const aggregateTypes = [aggregateType] @@ -194,8 +156,7 @@ type ${getGroupByPayloadName( const sumType = this.dmmf.outputTypeMap[getSumAggregateName(model.name)] const minType = this.dmmf.outputTypeMap[getMinAggregateName(model.name)] const maxType = this.dmmf.outputTypeMap[getMaxAggregateName(model.name)] - const countType = - this.dmmf.outputTypeMap[getCountAggregateOutputName(model.name)] + const countType = this.dmmf.outputTypeMap[getCountAggregateOutputName(model.name)] if (avgType) { aggregateTypes.push(avgType) @@ -223,9 +184,7 @@ type ${getGroupByPayloadName( this.collector?.addSymbol(aggregateArgsName) - return `${aggregateTypes - .map((type) => new SchemaOutputType(type, this.collector).toTS()) - .join('\n')} + return `${aggregateTypes.map((type) => new SchemaOutputType(type, this.collector).toTS()).join('\n')} ${ aggregateTypes.length > 1 @@ -268,18 +227,12 @@ ${indent( .concat( aggregateType.fields.map((f) => { let data = '' - const comment = getArgFieldJSDoc( - this.type, - DMMF.ModelAction.aggregate, - f.name, - ) + const comment = getArgFieldJSDoc(this.type, DMMF.ModelAction.aggregate, f.name) data += comment ? wrapComment(comment) + '\n' : '' if (f.name === '_count' || f.name === 'count') { data += `${f.name}?: true | ${getCountAggregateInputName(model.name)}` } else { - data += `${f.name}?: ${getAggregateInputType( - (f.outputType.type as DMMF.OutputType).name, - )}` + data += `${f.name}?: ${getAggregateInputType((f.outputType.type as DMMF.OutputType).name)}` } return data }), @@ -289,9 +242,7 @@ ${indent( )} } -export type ${getAggregateGetName(model.name)} = { +export type ${getAggregateGetName(model.name)} = { [P in keyof T & keyof ${aggregateName}]: P extends '_count' | 'count' ? T[P] extends true ? number @@ -330,11 +281,7 @@ ${indent( outputType.fields .filter((f) => f.outputType.location === 'outputObjectTypes') .map( - (f) => - `${f.name}?: boolean` + - (f.outputType.location === 'outputObjectTypes' - ? ` | ${getFieldArgName(f)}` - : ''), + (f) => `${f.name}?: boolean` + (f.outputType.location === 'outputObjectTypes' ? ` | ${getFieldArgName(f)}` : ''), ) .join('\n'), TAB_SIZE, @@ -355,11 +302,7 @@ export type ${getSelectName(model.name)} = { ${indent( outputType.fields .map( - (f) => - `${f.name}?: boolean` + - (f.outputType.location === 'outputObjectTypes' - ? ` | ${getFieldArgName(f)}` - : ''), + (f) => `${f.name}?: boolean` + (f.outputType.location === 'outputObjectTypes' ? ` | ${getFieldArgName(f)}` : ''), ) .join('\n'), TAB_SIZE, @@ -390,21 +333,13 @@ export class ModelDelegate implements Generatable { const model = this.dmmf.modelMap[name] const actions = Object.entries(mapping).filter( - ([key, value]) => - key !== 'model' && - key !== 'plural' && - key !== 'aggregate' && - key !== 'groupBy' && - value, + ([key, value]) => key !== 'model' && key !== 'plural' && key !== 'aggregate' && key !== 'groupBy' && value, ) const groupByArgsName = getGroupByArgsName(name) const countArgsName = getModelArgName(name, DMMF.ModelAction.count) return `\ type ${countArgsName} = Merge< - Omit<${getModelArgName( - name, - DMMF.ModelAction.findMany, - )}, 'select' | 'include'> & { + Omit<${getModelArgName(name, DMMF.ModelAction.findMany)}, 'select' | 'include'> & { select?: ${getCountAggregateInputName(name)} | true } > @@ -435,9 +370,7 @@ ${indent(getMethodJSDoc(DMMF.ModelAction.count, mapping, model), TAB_SIZE)} > ${indent(getMethodJSDoc(DMMF.ModelAction.aggregate, mapping, model), TAB_SIZE)} - aggregate(args: Subset(args: Subset): PrismaPromise<${getAggregateGetName(name)}> @@ -528,20 +461,13 @@ export class Prisma__${name}Client implements PrismaPromise { readonly [Symbol.toStringTag]: 'PrismaClientPromise'; ${indent( fields - .filter( - (f) => - f.outputType.location === 'outputObjectTypes' && f.name !== '_count', - ) + .filter((f) => f.outputType.location === 'outputObjectTypes' && f.name !== '_count') .map((f) => { const fieldTypeName = (f.outputType.type as DMMF.OutputType).name return ` -${f.name}(args?: Subset): ${getSelectReturnType({ +${f.name}(args?: Subset): ${getSelectReturnType({ name: fieldTypeName, - actionName: f.outputType.isList - ? DMMF.ModelAction.findMany - : DMMF.ModelAction.findUnique, + actionName: f.outputType.isList ? DMMF.ModelAction.findMany : DMMF.ModelAction.findUnique, hideCondition: false, isField: true, renderPromise: true, diff --git a/packages/client/src/generation/TSClient/Output.ts b/packages/client/src/generation/TSClient/Output.ts index 03060176f6ba..e783bd6cf393 100644 --- a/packages/client/src/generation/TSClient/Output.ts +++ b/packages/client/src/generation/TSClient/Output.ts @@ -1,11 +1,7 @@ import indent from 'indent-string' import type { DMMFClass } from '../../runtime/dmmf' import type { BaseField, DMMF } from '../../runtime/dmmf-types' -import { - GraphQLScalarToJSTypeTable, - isSchemaEnum, - needsNamespace, -} from '../../runtime/utils/common' +import { GraphQLScalarToJSTypeTable, isSchemaEnum, needsNamespace } from '../../runtime/utils/common' import { TAB_SIZE } from './constants' import type { Generatable } from './Generatable' import type { ExportCollector } from './helpers' @@ -21,16 +17,13 @@ export class ModelOutputField implements Generatable { const { field, useNamespace } = this // ENUMTODO let fieldType = - typeof field.type === 'string' - ? GraphQLScalarToJSTypeTable[field.type] || field.type - : field.type[0].name + typeof field.type === 'string' ? GraphQLScalarToJSTypeTable[field.type] || field.type : field.type[0].name if (Array.isArray(fieldType)) { fieldType = fieldType[0] } const arrayStr = field.isList ? `[]` : '' const nullableStr = !field.isRequired && !field.isList ? ' | null' : '' - const namespaceStr = - useNamespace && needsNamespace(field, this.dmmf) ? `Prisma.` : '' + const namespaceStr = useNamespace && needsNamespace(field, this.dmmf) ? `Prisma.` : '' return `${field.name}: ${namespaceStr}${fieldType}${arrayStr}${nullableStr}` } } @@ -61,8 +54,7 @@ export class OutputField implements Generatable { } const arrayStr = field.outputType.isList ? `[]` : '' - const nullableStr = - field.isNullable && !field.outputType.isList ? ' | null' : '' + const nullableStr = field.isNullable && !field.outputType.isList ? ' | null' : '' const namespaceStr = useNamespace && needsNamespace( @@ -101,11 +93,7 @@ export class OutputType implements Generatable { return ` export type ${type.name} = { ${indent( - type.fields - .map((field) => - new OutputField(this.dmmf, { ...field, ...field.outputType }).toTS(), - ) - .join('\n'), + type.fields.map((field) => new OutputField(this.dmmf, { ...field, ...field.outputType }).toTS()).join('\n'), TAB_SIZE, )} }` diff --git a/packages/client/src/generation/TSClient/Payload.ts b/packages/client/src/generation/TSClient/Payload.ts index 34ebcf1f7123..9170992f9a21 100644 --- a/packages/client/src/generation/TSClient/Payload.ts +++ b/packages/client/src/generation/TSClient/Payload.ts @@ -2,19 +2,11 @@ import type { OutputType } from './Output' import indent from 'indent-string' import { DMMF } from '../../runtime/dmmf-types' -import { - getModelArgName, - getPayloadName, - Projection, - getArgName, -} from '../utils' +import { getModelArgName, getPayloadName, Projection, getArgName } from '../utils' import type { Generatable } from './Generatable' export class PayloadType implements Generatable { - constructor( - protected readonly type: OutputType, - protected readonly skipFindMany = false, - ) {} + constructor(protected readonly type: OutputType, protected readonly skipFindMany = false) {} public toTS(): string { const { type } = this @@ -25,9 +17,7 @@ export class PayloadType implements Generatable { const include = this.renderRelations(Projection.include) const select = this.renderRelations(Projection.select) - const findManyArg = this.skipFindMany - ? '' - : ` | ${getModelArgName(name, DMMF.ModelAction.findMany)}` + const findManyArg = this.skipFindMany ? '' : ` | ${getModelArgName(name, DMMF.ModelAction.findMany)}` return `\ export type ${getPayloadName(name)}< @@ -49,9 +39,7 @@ export type ${getPayloadName(name)}< private renderRelations(projection: Projection): string { const { type } = this // TODO: can be optimized, we're calling the filter two times - const relations = type.fields.filter( - (f) => f.outputType.location === 'outputObjectTypes', - ) + const relations = type.fields.filter((f) => f.outputType.location === 'outputObjectTypes') if (relations.length === 0 && projection === Projection.include) { return '' } @@ -66,12 +54,7 @@ export type ${getPayloadName(name)}< relations .map( (f) => `P extends '${f.name}' -? ${this.wrapType( - f, - `${getPayloadName( - (f.outputType.type as DMMF.OutputType).name, - )}`, - )} :`, +? ${this.wrapType(f, `${getPayloadName((f.outputType.type as DMMF.OutputType).name)}`)} :`, ) .join('\n'), 6, diff --git a/packages/client/src/generation/TSClient/PrismaClient.ts b/packages/client/src/generation/TSClient/PrismaClient.ts index 557999e79644..e586f4f42b5a 100644 --- a/packages/client/src/generation/TSClient/PrismaClient.ts +++ b/packages/client/src/generation/TSClient/PrismaClient.ts @@ -122,9 +122,7 @@ export class PrismaClientClass implements Generatable { * \`\`\` * const prisma = new PrismaClient() * // Fetch zero or more ${capitalize(example.plural)} - * const ${lowerCase(example.plural)} = await prisma.${lowerCase( - example.model, - )}.findMany() + * const ${lowerCase(example.plural)} = await prisma.${lowerCase(example.model)}.findMany() * \`\`\` * * @@ -199,9 +197,7 @@ ${[ const methodName = lowerCase(m.model) return `\ /** - * \`prisma.${methodName}\`: Exposes CRUD operations for the **${ - m.model - }** model. + * \`prisma.${methodName}\`: Exposes CRUD operations for the **${m.model}** model. * Example usage: * \`\`\`ts * // Fetch zero or more ${capitalize(m.plural)} diff --git a/packages/client/src/generation/TSClient/SchemaOutput.ts b/packages/client/src/generation/TSClient/SchemaOutput.ts index 6b06195fdedb..1ae17e682f28 100644 --- a/packages/client/src/generation/TSClient/SchemaOutput.ts +++ b/packages/client/src/generation/TSClient/SchemaOutput.ts @@ -11,8 +11,7 @@ export class SchemaOutputField implements Generatable { const { field } = this let fieldType = typeof field.outputType.type === 'string' - ? GraphQLScalarToJSTypeTable[field.outputType.type] || - field.outputType.type + ? GraphQLScalarToJSTypeTable[field.outputType.type] || field.outputType.type : field.outputType.type.name if (Array.isArray(fieldType)) { fieldType = fieldType[0] @@ -26,10 +25,7 @@ export class SchemaOutputField implements Generatable { export class SchemaOutputType implements Generatable { public name: string public fields: DMMF.SchemaField[] - constructor( - protected readonly type: DMMF.OutputType, - protected readonly collector?: ExportCollector, - ) { + constructor(protected readonly type: DMMF.OutputType, protected readonly collector?: ExportCollector) { this.name = type.name this.fields = type.fields collector?.addSymbol(this.name) @@ -39,11 +35,7 @@ export class SchemaOutputType implements Generatable { return ` export type ${type.name} = { ${indent( - type.fields - .map((field) => - new SchemaOutputField({ ...field, ...field.outputType }).toTS(), - ) - .join('\n'), + type.fields.map((field) => new SchemaOutputField({ ...field, ...field.outputType }).toTS()).join('\n'), TAB_SIZE, )} }` diff --git a/packages/client/src/generation/TSClient/TSClient.ts b/packages/client/src/generation/TSClient/TSClient.ts index 72c8dae9dc86..bf78ac0a1f70 100644 --- a/packages/client/src/generation/TSClient/TSClient.ts +++ b/packages/client/src/generation/TSClient/TSClient.ts @@ -67,11 +67,8 @@ export class TSClient implements Generatable { const envPaths = getEnvPaths(schemaPath, { cwd: outputDir }) const relativeEnvPaths = { - rootEnvPath: - envPaths.rootEnvPath && path.relative(outputDir, envPaths.rootEnvPath), - schemaEnvPath: - envPaths.schemaEnvPath && - path.relative(outputDir, envPaths.schemaEnvPath), + rootEnvPath: envPaths.rootEnvPath && path.relative(outputDir, envPaths.rootEnvPath), + schemaEnvPath: envPaths.schemaEnvPath && path.relative(outputDir, envPaths.schemaEnvPath), } // This ensures that any engine override is propagated to the generated clients config @@ -105,14 +102,8 @@ ${buildDirname(engineType, relativeOutdir, runtimeDir)} // https://github.com/microsoft/TypeScript/issues/3192#issuecomment-261720275 function makeEnum(x) { return x; } -${this.dmmf.schema.enumTypes.prisma - .map((type) => new Enum(type, true).toJS()) - .join('\n\n')} -${ - this.dmmf.schema.enumTypes.model - ?.map((type) => new Enum(type, false).toJS()) - .join('\n\n') ?? '' -} +${this.dmmf.schema.enumTypes.prisma.map((type) => new Enum(type, true).toJS()).join('\n\n')} +${this.dmmf.schema.enumTypes.model?.map((type) => new Enum(type, false).toJS()).join('\n\n') ?? ''} ${new Enum( { @@ -163,13 +154,9 @@ ${buildNFTAnnotations(engineType, platforms, relativeOutdir)} // TODO: Make this code more efficient and directly return 2 arrays - const prismaEnums = this.dmmf.schema.enumTypes.prisma.map((type) => - new Enum(type, true, collector).toTS(), - ) + const prismaEnums = this.dmmf.schema.enumTypes.prisma.map((type) => new Enum(type, true, collector).toTS()) - const modelEnums = this.dmmf.schema.enumTypes.model?.map((type) => - new Enum(type, false, collector).toTS(), - ) + const modelEnums = this.dmmf.schema.enumTypes.model?.map((type) => new Enum(type, false, collector).toTS()) const countTypes: Count[] = this.dmmf.schema.outputObjectTypes.prisma .filter((t) => t.name.endsWith('CountOutputType')) @@ -252,12 +239,7 @@ ${this.dmmf.inputObjectTypes.prisma > | OptionalFlat>`) collector?.addSymbol(inputType.name) - acc.push( - new InputType( - { ...inputType, name: `${inputType.name}Base` }, - collector, - ).toTS(), - ) + acc.push(new InputType({ ...inputType, name: `${inputType.name}Base` }, collector).toTS()) } else { acc.push(new InputType(inputType, collector).toTS()) } @@ -265,11 +247,7 @@ ${this.dmmf.inputObjectTypes.prisma }, [] as string[]) .join('\n')} -${ - this.dmmf.inputObjectTypes.model - ?.map((inputType) => new InputType(inputType, collector).toTS()) - .join('\n') ?? '' -} +${this.dmmf.inputObjectTypes.model?.map((inputType) => new InputType(inputType, collector).toTS()).join('\n') ?? ''} /** * Batch Payload for updateMany & deleteMany & createMany @@ -303,14 +281,8 @@ export const dmmf: runtime.DMMF.Document; // https://github.com/microsoft/TypeScript/issues/3192#issuecomment-261720275 function makeEnum(x) { return x; } -${this.dmmf.schema.enumTypes.prisma - .map((type) => new Enum(type, true).toJS()) - .join('\n\n')} -${ - this.dmmf.schema.enumTypes.model - ?.map((type) => new Enum(type, false).toJS()) - .join('\n\n') ?? '' -} +${this.dmmf.schema.enumTypes.prisma.map((type) => new Enum(type, true).toJS()).join('\n\n')} +${this.dmmf.schema.enumTypes.model?.map((type) => new Enum(type, false).toJS()).join('\n\n') ?? ''} ${new Enum( { diff --git a/packages/client/src/generation/TSClient/common.ts b/packages/client/src/generation/TSClient/common.ts index b22574bf17f7..dda40e07e055 100644 --- a/packages/client/src/generation/TSClient/common.ts +++ b/packages/client/src/generation/TSClient/common.ts @@ -46,26 +46,11 @@ Prisma.prismaVersion = { engine: "${engineVersion}" } -Prisma.PrismaClientKnownRequestError = ${notSupportOnBrowser( - 'PrismaClientKnownRequestError', - browser, -)}; -Prisma.PrismaClientUnknownRequestError = ${notSupportOnBrowser( - 'PrismaClientUnknownRequestError', - browser, -)} -Prisma.PrismaClientRustPanicError = ${notSupportOnBrowser( - 'PrismaClientRustPanicError', - browser, -)} -Prisma.PrismaClientInitializationError = ${notSupportOnBrowser( - 'PrismaClientInitializationError', - browser, -)} -Prisma.PrismaClientValidationError = ${notSupportOnBrowser( - 'PrismaClientValidationError', - browser, -)} +Prisma.PrismaClientKnownRequestError = ${notSupportOnBrowser('PrismaClientKnownRequestError', browser)}; +Prisma.PrismaClientUnknownRequestError = ${notSupportOnBrowser('PrismaClientUnknownRequestError', browser)} +Prisma.PrismaClientRustPanicError = ${notSupportOnBrowser('PrismaClientRustPanicError', browser)} +Prisma.PrismaClientInitializationError = ${notSupportOnBrowser('PrismaClientInitializationError', browser)} +Prisma.PrismaClientValidationError = ${notSupportOnBrowser('PrismaClientValidationError', browser)} Prisma.Decimal = Decimal /** @@ -94,14 +79,8 @@ In case this error is unexpected for you, please report it in https://github.com return fnc } -export const commonCodeTS = ({ - runtimeDir, - runtimeName, - clientVersion, - engineVersion, -}: TSClientOptions) => ({ - tsWithoutNamespace: - () => `import * as runtime from '${runtimeDir}/${runtimeName}'; +export const commonCodeTS = ({ runtimeDir, runtimeName, clientVersion, engineVersion }: TSClientOptions) => ({ + tsWithoutNamespace: () => `import * as runtime from '${runtimeDir}/${runtimeName}'; declare const prisma: unique symbol export type PrismaPromise = Promise & {[prisma]: true} type UnwrapPromise

= P extends Promise ? R : P diff --git a/packages/client/src/generation/TSClient/helpers.ts b/packages/client/src/generation/TSClient/helpers.ts index ea5605eca8f7..4ac066c52d89 100644 --- a/packages/client/src/generation/TSClient/helpers.ts +++ b/packages/client/src/generation/TSClient/helpers.ts @@ -5,11 +5,7 @@ import { getAggregateArgsName, getModelArgName, unique } from '../utils' import type { JSDocMethodBodyCtx } from './jsdoc' import { JSDocs } from './jsdoc' -export function getMethodJSDocBody( - action: DMMF.ModelAction, - mapping: DMMF.ModelMapping, - model: DMMF.Model, -): string { +export function getMethodJSDocBody(action: DMMF.ModelAction, mapping: DMMF.ModelMapping, model: DMMF.Model): string { const ctx: JSDocMethodBodyCtx = { singular: capitalize(mapping.model), plural: capitalize(mapping.plural), @@ -24,11 +20,7 @@ export function getMethodJSDocBody( return jsdoc ? jsdoc : '' } -export function getMethodJSDoc( - action: DMMF.ModelAction, - mapping: DMMF.ModelMapping, - model: DMMF.Model, -): string { +export function getMethodJSDoc(action: DMMF.ModelAction, mapping: DMMF.ModelMapping, model: DMMF.Model): string { return wrapComment(getMethodJSDocBody(action, mapping, model)) } export function getGenericMethod(name: string, actionName: DMMF.ModelAction) { @@ -52,10 +44,7 @@ export function getGenericMethod(name: string, actionName: DMMF.ModelAction) { } export function getArgs(name: string, actionName: DMMF.ModelAction) { if (actionName === 'count') { - return `args?: Omit<${getModelArgName( - name, - DMMF.ModelAction.findMany, - )}, 'select' | 'include'>` + return `args?: Omit<${getModelArgName(name, DMMF.ModelAction.findMany)}, 'select' | 'include'>` } if (actionName === 'aggregate') { return `args: Subset` @@ -93,10 +82,7 @@ export function getArgFieldJSDoc( } export function escapeJson(str: string): string { - return str - .replace(/\\n/g, '\\\\n') - .replace(/\\r/g, '\\\\r') - .replace(/\\t/g, '\\\\t') + return str.replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r').replace(/\\t/g, '\\\\t') } export class ExportCollector { diff --git a/packages/client/src/generation/TSClient/jsdoc.ts b/packages/client/src/generation/TSClient/jsdoc.ts index f76af3ee918b..8f6714f152ee 100644 --- a/packages/client/src/generation/TSClient/jsdoc.ts +++ b/packages/client/src/generation/TSClient/jsdoc.ts @@ -41,36 +41,20 @@ const undefinedNote = `Note, that providing \`undefined\` is treated as the valu Read more here: https://pris.ly/d/null-undefined` const JSDocFields = { - take: (singular, plural) => - addLinkToDocs( - `Take \`Ā±n\` ${plural} from the position of the cursor.`, - 'pagination', - ), - skip: (singular, plural) => - addLinkToDocs(`Skip the first \`n\` ${plural}.`, 'pagination'), - _count: (singular, plural) => - addLinkToDocs(`Count returned ${plural}`, 'aggregations'), + take: (singular, plural) => addLinkToDocs(`Take \`Ā±n\` ${plural} from the position of the cursor.`, 'pagination'), + skip: (singular, plural) => addLinkToDocs(`Skip the first \`n\` ${plural}.`, 'pagination'), + _count: (singular, plural) => addLinkToDocs(`Count returned ${plural}`, 'aggregations'), _avg: () => addLinkToDocs(`Select which fields to average`, 'aggregations'), _sum: () => addLinkToDocs(`Select which fields to sum`, 'aggregations'), - _min: () => - addLinkToDocs( - `Select which fields to find the minimum value`, - 'aggregations', - ), - _max: () => - addLinkToDocs( - `Select which fields to find the maximum value`, - 'aggregations', - ), + _min: () => addLinkToDocs(`Select which fields to find the minimum value`, 'aggregations'), + _max: () => addLinkToDocs(`Select which fields to find the maximum value`, 'aggregations'), count: () => getDeprecationString('2.23.0', '_count'), avg: () => getDeprecationString('2.23.0', '_avg'), sum: () => getDeprecationString('2.23.0', '_sum'), min: () => getDeprecationString('2.23.0', '_min'), max: () => getDeprecationString('2.23.0', '_max'), - distinct: (singular, plural) => - addLinkToDocs(`Filter by unique combinations of ${plural}.`, 'distinct'), - orderBy: (singular, plural) => - addLinkToDocs(`Determine the order of ${plural} to fetch.`, 'sorting'), + distinct: (singular, plural) => addLinkToDocs(`Filter by unique combinations of ${plural}.`, 'distinct'), + orderBy: (singular, plural) => addLinkToDocs(`Determine the order of ${plural} to fetch.`, 'sorting'), } export const JSDocs: JSDocsType = { groupBy: { @@ -93,10 +77,7 @@ const result = await prisma.user.groupBy({ }, create: { body: (ctx) => `Create a ${ctx.singular}. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to create a ${ctx.singular}. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to create a ${ctx.singular}. @example // Create one ${ctx.singular} const ${ctx.singular} = await ${ctx.method}({ @@ -111,10 +92,7 @@ const ${ctx.singular} = await ${ctx.method}({ }, createMany: { body: (ctx) => `Create many ${ctx.plural}. - @param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to create many ${ctx.plural}. + @param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to create many ${ctx.plural}. @example // Create many ${ctx.plural} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -130,10 +108,7 @@ const ${ctx.singular} = await ${ctx.method}({ findUnique: { body: (ctx) => `Find zero or one ${ctx.singular} that matches the filter. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to find a ${ctx.singular} +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to find a ${ctx.singular} @example // Get one ${ctx.singular} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -149,10 +124,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ body: (ctx) => `Find the first ${ctx.singular} that matches the filter. ${undefinedNote} -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to find a ${ctx.singular} +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to find a ${ctx.singular} @example // Get one ${ctx.singular} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -163,11 +135,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ fields: { where: (singular) => `Filter, which ${singular} to fetch.`, orderBy: JSDocFields.orderBy, - cursor: (singular, plural) => - addLinkToDocs( - `Sets the position for searching for ${plural}.`, - 'cursor', - ), + cursor: (singular, plural) => addLinkToDocs(`Sets the position for searching for ${plural}.`, 'cursor'), take: JSDocFields.take, skip: JSDocFields.skip, distinct: JSDocFields.distinct, @@ -177,19 +145,14 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ body: (ctx) => { const onlySelect = ctx.firstScalar ? `\n// Only select the \`${ctx.firstScalar.name}\` -const ${lowerCase(ctx.mapping.model)}With${capitalize( - ctx.firstScalar.name, - )}Only = await ${ctx.method}({ select: { ${ +const ${lowerCase(ctx.mapping.model)}With${capitalize(ctx.firstScalar.name)}Only = await ${ctx.method}({ select: { ${ ctx.firstScalar.name }: true } })` : '' return `Find zero or more ${ctx.plural} that matches the filter. ${undefinedNote} -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}=} args - Arguments to filter and select certain fields only. +@param {${getModelArgName(ctx.model.name, ctx.action)}=} args - Arguments to filter and select certain fields only. @example // Get all ${ctx.plural} const ${ctx.mapping.plural} = await ${ctx.method}() @@ -203,18 +166,14 @@ ${onlySelect} where: (singular, plural) => `Filter, which ${plural} to fetch.`, orderBy: JSDocFields.orderBy, skip: JSDocFields.skip, - cursor: (singular, plural) => - addLinkToDocs(`Sets the position for listing ${plural}.`, 'cursor'), + cursor: (singular, plural) => addLinkToDocs(`Sets the position for listing ${plural}.`, 'cursor'), take: JSDocFields.take, }, }, update: { body: (ctx) => `Update one ${ctx.singular}. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to update one ${ctx.singular}. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to update one ${ctx.singular}. @example // Update one ${ctx.singular} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -234,10 +193,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ upsert: { body: (ctx) => `Create or update one ${ctx.singular}. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to update or create a ${ctx.singular}. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to update or create a ${ctx.singular}. @example // Update or create a ${ctx.singular} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -252,8 +208,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ } })`, fields: { - where: (singular) => - `The filter to search for the ${singular} to update in case it exists.`, + where: (singular) => `The filter to search for the ${singular} to update in case it exists.`, create: (singular) => `In case the ${singular} found by the \`where\` argument doesn't exist, create a new ${singular} with this data.`, update: (singular) => @@ -263,10 +218,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ delete: { body: (ctx) => `Delete a ${ctx.singular}. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to delete one ${ctx.singular}. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to delete one ${ctx.singular}. @example // Delete one ${ctx.singular} const ${ctx.singular} = await ${ctx.method}({ @@ -327,10 +279,7 @@ const aggregations = await prisma.user.aggregate({ body: (ctx) => `Count the number of ${ctx.plural}. ${undefinedNote} -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to filter ${ctx.plural} to count. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to filter ${ctx.plural} to count. @example // Count the number of ${ctx.plural} const count = await ${ctx.method}({ @@ -344,10 +293,7 @@ const count = await ${ctx.method}({ body: (ctx) => `Update zero or more ${ctx.plural}. ${undefinedNote} -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to update one or more rows. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to update one or more rows. @example // Update many ${ctx.plural} const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ @@ -367,10 +313,7 @@ const ${lowerCase(ctx.mapping.model)} = await ${ctx.method}({ deleteMany: { body: (ctx) => `Delete zero or more ${ctx.plural}. -@param {${getModelArgName( - ctx.model.name, - ctx.action, - )}} args - Arguments to filter ${ctx.plural} to delete. +@param {${getModelArgName(ctx.model.name, ctx.action)}} args - Arguments to filter ${ctx.plural} to delete. @example // Delete a few ${ctx.plural} const { count } = await ${ctx.method}({ diff --git a/packages/client/src/generation/extractSqliteSources.ts b/packages/client/src/generation/extractSqliteSources.ts index bb0a19bf0178..5c612cbaa549 100644 --- a/packages/client/src/generation/extractSqliteSources.ts +++ b/packages/client/src/generation/extractSqliteSources.ts @@ -41,9 +41,7 @@ export function extractSqliteSources( } if (!startLine) { - throw new Error( - `Could not parse datamodel, invalid datasource block without opening \`{\``, - ) + throw new Error(`Could not parse datamodel, invalid datasource block without opening \`{\``) } const startMatch = startRegex.exec(startLine) @@ -56,20 +54,11 @@ export function extractSqliteSources( } else { overrides.push({ name: startMatch[1], - url: absolutizeRelativePath( - match[3], - cwd, - outputDir, - absolutePaths, - ), + url: absolutizeRelativePath(match[3], cwd, outputDir, absolutePaths), }) } } else { - throw new Error( - `Could not parse datamodel, line ${ - searchIndex + 1 - }: \`${startLine}\` is not parseable`, - ) + throw new Error(`Could not parse datamodel, line ${searchIndex + 1}: \`${startLine}\` is not parseable`) } } }) diff --git a/packages/client/src/generation/generateClient.ts b/packages/client/src/generation/generateClient.ts index a55498764ce7..98a88a3aaf64 100644 --- a/packages/client/src/generation/generateClient.ts +++ b/packages/client/src/generation/generateClient.ts @@ -1,10 +1,5 @@ import { BinaryType } from '@prisma/fetch-engine' -import type { - BinaryPaths, - DataSource, - DMMF, - GeneratorConfig, -} from '@prisma/generator-helper' +import type { BinaryPaths, DataSource, DMMF, GeneratorConfig } from '@prisma/generator-helper' import type { Platform } from '@prisma/sdk' import { getVersion } from '@prisma/sdk' import copy from '@timsuchanek/copy' @@ -16,10 +11,7 @@ import pkgUp from 'pkg-up' import { promisify } from 'util' import type { DMMF as PrismaClientDMMF } from '../runtime/dmmf-types' import type { Dictionary } from '../runtime/utils/common' -import { - ClientEngineType, - getClientEngineType, -} from '../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../runtime/utils/getClientEngineType' import { getPrismaClientDMMF } from './getDMMF' import { JS, TS, TSClient } from './TSClient' import { BrowserJS } from './TSClient/Generatable' @@ -156,17 +148,14 @@ export async function generateClient({ }: GenerateClientOptions): Promise { const useDotPrisma = testMode ? !runtimeDir : !generator?.isCustomOutput const clientEngineType = getClientEngineType(generator!) - runtimeDir = - runtimeDir || (useDotPrisma ? '@prisma/client/runtime' : './runtime') + runtimeDir = runtimeDir || (useDotPrisma ? '@prisma/client/runtime' : './runtime') // we make sure that we point to the right engine build if (clientEngineType === ClientEngineType.DataProxy) { runtimeName = 'proxy' } - const finalOutputDir = useDotPrisma - ? await getDotPrismaDir(outputDir) - : outputDir + const finalOutputDir = useDotPrisma ? await getDotPrismaDir(outputDir) : outputDir const packageRoot = await pkgUp({ cwd: path.dirname(finalOutputDir) }) const projectRoot = packageRoot ? path.dirname(packageRoot) : process.cwd() @@ -224,10 +213,7 @@ export async function generateClient({ : eval(`require('path').join(__dirname, '../runtime')`) // tslint:disable-line // if users use a custom output dir - if ( - copyRuntime || - !path.resolve(outputDir).endsWith(`@prisma${path.sep}client`) - ) { + if (copyRuntime || !path.resolve(outputDir).endsWith(`@prisma${path.sep}client`)) { // TODO: Windows, / is not working here... const copyTarget = path.join(outputDir, 'runtime') await makeDir(copyTarget) @@ -242,16 +228,12 @@ export async function generateClient({ } } const enginePath = - clientEngineType === ClientEngineType.Library - ? binaryPaths.libqueryEngine - : binaryPaths.queryEngine + clientEngineType === ClientEngineType.Library ? binaryPaths.libqueryEngine : binaryPaths.queryEngine if (!enginePath) { throw new Error( `Prisma Client needs \`${ - clientEngineType === ClientEngineType.Library - ? 'libqueryEngine' - : 'queryEngine' + clientEngineType === ClientEngineType.Library ? 'libqueryEngine' : 'queryEngine' }\` in the \`binaryPaths\` object.`, ) } @@ -266,10 +248,7 @@ export async function generateClient({ process.env.NETLIFY && binaryTarget !== 'rhel-openssl-1.0.x' ? path.join('/tmp/prisma-engines', fileName) : path.join(finalOutputDir, fileName) - const [sourceFileSize, targetFileSize] = await Promise.all([ - fileSize(filePath), - fileSize(target), - ]) + const [sourceFileSize, targetFileSize] = await Promise.all([fileSize(filePath), fileSize(target)]) // If the target doesn't exist yet, copy it if (!targetFileSize) { @@ -282,18 +261,12 @@ export async function generateClient({ } // If target !== source size, they're definitely different, copy it - if ( - targetFileSize && - sourceFileSize && - targetFileSize !== sourceFileSize - ) { + if (targetFileSize && sourceFileSize && targetFileSize !== sourceFileSize) { await copyFile(filePath, target) continue } const binaryName = - clientEngineType === ClientEngineType.Binary - ? BinaryType.queryEngine - : BinaryType.libqueryEngine + clientEngineType === ClientEngineType.Binary ? BinaryType.queryEngine : BinaryType.libqueryEngine // They must have an equal size now, let's check for the hash const [sourceVersion, targetVersion] = await Promise.all([ getVersion(filePath, binaryName).catch(() => null), @@ -329,10 +302,7 @@ export async function generateClient({ } if (!testMode && process.env.INIT_CWD) { - const backupPath = path.join( - process.env.INIT_CWD, - 'node_modules/.prisma/client', - ) + const backupPath = path.join(process.env.INIT_CWD, 'node_modules/.prisma/client') if (finalOutputDir !== backupPath && !generator?.isCustomOutput) { await copy({ from: finalOutputDir, @@ -356,10 +326,7 @@ export async function generateClient({ } if (!fs.existsSync(proxyIndexBrowserJsPath)) { - await copyFile( - path.join(__dirname, '../../index-browser.js'), - proxyIndexBrowserJsPath, - ) + await copyFile(path.join(__dirname, '../../index-browser.js'), proxyIndexBrowserJsPath) } return { prismaClientDmmf, fileMap } @@ -374,9 +341,7 @@ async function fileSize(name: string): Promise { } } -function validateDmmfAgainstDenylists( - prismaClientDmmf: PrismaClientDMMF.Document, -): Error[] | null { +function validateDmmfAgainstDenylists(prismaClientDmmf: PrismaClientDMMF.Document): Error[] | null { const errorArray = [] as Error[] const denylists = { @@ -438,10 +403,7 @@ function validateDmmfAgainstDenylists( if (prismaClientDmmf.datamodel.enums) { for (const it of prismaClientDmmf.datamodel.enums) { - if ( - denylists.models.includes(it.name) || - denylists.fields.includes(it.name) - ) { + if (denylists.models.includes(it.name) || denylists.fields.includes(it.name)) { errorArray.push(Error(`"enum ${it.name}"`)) } } @@ -449,10 +411,7 @@ function validateDmmfAgainstDenylists( if (prismaClientDmmf.datamodel.models) { for (const it of prismaClientDmmf.datamodel.models) { - if ( - denylists.models.includes(it.name) || - denylists.fields.includes(it.name) - ) { + if (denylists.models.includes(it.name) || denylists.fields.includes(it.name)) { errorArray.push(Error(`"model ${it.name}"`)) } } diff --git a/packages/client/src/generation/generator.ts b/packages/client/src/generation/generator.ts index 5da7c6723f9e..ad7ecd834f56 100755 --- a/packages/client/src/generation/generator.ts +++ b/packages/client/src/generation/generator.ts @@ -5,10 +5,7 @@ import { parseEnvValue } from '@prisma/sdk' import { generateClient } from './generateClient' import { getDMMF } from './getDMMF' import { externalToInternalDmmf } from '../runtime/externalToInternalDmmf' -import { - ClientEngineType, - getClientEngineType, -} from '../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../runtime/utils/getClientEngineType' const debug = Debug('prisma:client:generator') // As specced in https://github.com/prisma/specs/tree/master/generators @@ -20,10 +17,7 @@ const clientVersion = pkg.version if (process.argv[1] === __filename) { generatorHandler({ onManifest(config) { - const requiredEngine = - getClientEngineType(config) === ClientEngineType.Library - ? 'libqueryEngine' - : 'queryEngine' + const requiredEngine = getClientEngineType(config) === ClientEngineType.Library ? 'libqueryEngine' : 'queryEngine' debug(`requiredEngine: ${requiredEngine}`) return { defaultOutput: '.prisma/client', // the value here doesn't matter, as it's resolved in https://github.com/prisma/prisma/blob/main/cli/sdk/src/getGenerators.ts diff --git a/packages/client/src/generation/getDMMF.ts b/packages/client/src/generation/getDMMF.ts index 69458c5a9efb..d1a7e7365d24 100644 --- a/packages/client/src/generation/getDMMF.ts +++ b/packages/client/src/generation/getDMMF.ts @@ -4,16 +4,12 @@ import { getDMMF as getRawDMMF } from '@prisma/sdk' import type { DMMF as PrismaClientDMMF } from '../runtime/dmmf-types' import { externalToInternalDmmf } from '../runtime/externalToInternalDmmf' -export function getPrismaClientDMMF( - dmmf: DMMF.Document, -): PrismaClientDMMF.Document { +export function getPrismaClientDMMF(dmmf: DMMF.Document): PrismaClientDMMF.Document { return externalToInternalDmmf(dmmf) } // Mostly used for tests -export async function getDMMF( - options: GetDMMFOptions, -): Promise { +export async function getDMMF(options: GetDMMFOptions): Promise { const dmmf = await getRawDMMF(options) return getPrismaClientDMMF(dmmf) } diff --git a/packages/client/src/generation/serializeDatasources.ts b/packages/client/src/generation/serializeDatasources.ts index 61102061d4e4..017254ca56b0 100644 --- a/packages/client/src/generation/serializeDatasources.ts +++ b/packages/client/src/generation/serializeDatasources.ts @@ -5,9 +5,7 @@ import type { DatasourceOverwrite } from './extractSqliteSources' // object used for generation // this is needed, as we need to print `path.resolve` statements // it basically just strips the quotes -export function serializeDatasources( - datasources: DatasourceOverwrite[], -): string { +export function serializeDatasources(datasources: DatasourceOverwrite[]): string { const str = JSON.stringify(datasources, null, 2) const replaceRegex = /"('file:'.*'\))"/ @@ -21,13 +19,9 @@ export function serializeDatasources( .join('\n') } -export function datasourceToDatasourceOverwrite( - datasource: DataSource, -): DatasourceOverwrite { +export function datasourceToDatasourceOverwrite(datasource: DataSource): DatasourceOverwrite { return { name: datasource.name, - url: datasource.url.fromEnvVar - ? `env("${datasource.url.fromEnvVar}")` - : datasource.url.value, + url: datasource.url.fromEnvVar ? `env("${datasource.url.fromEnvVar}")` : datasource.url.value, } } diff --git a/packages/client/src/generation/utils.ts b/packages/client/src/generation/utils.ts index 7a9fad5218ee..c9531684a225 100644 --- a/packages/client/src/generation/utils.ts +++ b/packages/client/src/generation/utils.ts @@ -89,10 +89,7 @@ export function getDefaultName(modelName: string): string { } export function getFieldArgName(field: DMMF.SchemaField): string { - return getArgName( - (field.outputType.type as DMMF.OutputType).name, - field.outputType.isList, - ) + return getArgName((field.outputType.type as DMMF.OutputType).name, field.outputType.isList) } export function getArgName(name: string, isList: boolean): string { @@ -105,10 +102,7 @@ export function getArgName(name: string, isList: boolean): string { // we need names for all top level args, // as GraphQL doesn't have the concept of unnamed args -export function getModelArgName( - modelName: string, - action?: DMMF.ModelAction, -): string { +export function getModelArgName(modelName: string, action?: DMMF.ModelAction): string { if (!action) { return `${modelName}Args` } @@ -142,14 +136,8 @@ export function getModelArgName( } } -export function getDefaultArgName( - dmmf: DMMFClass, - modelName: string, - action: DMMF.ModelAction, -): string { - const mapping = dmmf.mappings.modelOperations.find( - (m) => m.model === modelName, - )! +export function getDefaultArgName(dmmf: DMMFClass, modelName: string, action: DMMF.ModelAction): string { + const mapping = dmmf.mappings.modelOperations.find((m) => m.model === modelName)! const fieldName = mapping[action] const operation = getOperation(action) @@ -159,10 +147,7 @@ export function getDefaultArgName( } export function getOperation(action: DMMF.ModelAction): 'query' | 'mutation' { - if ( - action === DMMF.ModelAction.findMany || - action === DMMF.ModelAction.findUnique - ) { + if (action === DMMF.ModelAction.findMany || action === DMMF.ModelAction.findUnique) { return 'query' } return 'mutation' @@ -199,11 +184,7 @@ export function getFieldTypeName(field: DMMF.SchemaField): string { return field.outputType.type.name } -export function getType( - name: string, - isList: boolean, - isOptional?: boolean, -): string { +export function getType(name: string, isList: boolean, isOptional?: boolean): string { return name + (isList ? '[]' : '') + (isOptional ? ' | null' : '') } @@ -236,16 +217,11 @@ export function getSelectReturnType({ if (actionName === 'count') { return `Promise` } - if (actionName === 'aggregate') - return `Promise<${getAggregateGetName(name)}>` + if (actionName === 'aggregate') return `Promise<${getAggregateGetName(name)}>` const isList = actionName === DMMF.ModelAction.findMany - if ( - actionName === 'deleteMany' || - actionName === 'updateMany' || - actionName === 'createMany' - ) { + if (actionName === 'deleteMany' || actionName === 'updateMany' || actionName === 'createMany') { return `PrismaPromise` } @@ -264,10 +240,7 @@ export function getSelectReturnType({ } if (actionName === 'findFirst' || actionName === 'findUnique') { if (isField) { - return `CheckSelect, Prisma__${name}Client<${getType( + return `CheckSelect, Prisma__${name}Client<${getType( getPayloadName(name) + '', isList, )} | null >>` @@ -278,30 +251,22 @@ export function getSelectReturnType({ )}>, Prisma__${name}Client<${getType( getPayloadName(name) + '', isList, - )}>> : CheckSelect, Prisma__${name}Client<${getType( + )}>> : CheckSelect, Prisma__${name}Client<${getType( getPayloadName(name) + '', isList, )} | null >>` } - return `CheckSelect, Prisma__${name}Client<${getType( + getPayloadName(name) + '', isList, - )}>, Prisma__${name}Client<${getType(getPayloadName(name) + '', isList)}>>` + )}>>` } -export function isQueryAction( - action: DMMF.ModelAction, - operation: 'query' | 'mutation', -): boolean { +export function isQueryAction(action: DMMF.ModelAction, operation: 'query' | 'mutation'): boolean { if (!(action in DMMF.ModelAction)) { return false } - const result = - action === DMMF.ModelAction.findUnique || - action === DMMF.ModelAction.findMany + const result = action === DMMF.ModelAction.findUnique || action === DMMF.ModelAction.findMany return operation === 'query' ? result : !result } @@ -309,25 +274,17 @@ export function capitalize(str: string): string { return str[0].toUpperCase() + str.slice(1) } -export function indentAllButFirstLine( - str: string, - indentation: number, -): string { +export function indentAllButFirstLine(str: string, indentation: number): string { const lines = str.split('\n') return lines[0] + '\n' + indent(lines.slice(1).join('\n'), indentation) } -export function getRelativePathResolveStatement( - outputDir: string, - cwd?: string, -): string { +export function getRelativePathResolveStatement(outputDir: string, cwd?: string): string { if (!cwd) { return 'undefined' } - return `path.resolve(__dirname, ${JSON.stringify( - path.relative(outputDir, cwd), - )})` + return `path.resolve(__dirname, ${JSON.stringify(path.relative(outputDir, cwd))})` } function flatten(array): any[] { diff --git a/packages/client/src/generation/utils/buildDirname.ts b/packages/client/src/generation/utils/buildDirname.ts index aa9b304d6315..c13852632b5a 100644 --- a/packages/client/src/generation/utils/buildDirname.ts +++ b/packages/client/src/generation/utils/buildDirname.ts @@ -8,11 +8,7 @@ import path from 'path' * @param runtimeDir * @returns */ -export function buildDirname( - clientEngineType: ClientEngineType, - relativeOutdir: string, - runtimeDir: string, -) { +export function buildDirname(clientEngineType: ClientEngineType, relativeOutdir: string, runtimeDir: string) { if (clientEngineType !== ClientEngineType.DataProxy) { return buildDirnameFind(relativeOutdir, runtimeDir) } @@ -34,10 +30,7 @@ export function buildDirname( */ function buildDirnameFind(relativeOutdir: string, runtimePath: string) { // potential client location on serverless envs - const slsRelativeOutputDir = relativeOutdir - .split(path.sep) - .slice(1) - .join(path.sep) + const slsRelativeOutputDir = relativeOutdir.split(path.sep).slice(1).join(path.sep) return ` const { findSync } = require('${runtimePath}') diff --git a/packages/client/src/generation/utils/buildInlineDatasources.ts b/packages/client/src/generation/utils/buildInlineDatasources.ts index 8003dde25d1a..d3eb9c04b073 100644 --- a/packages/client/src/generation/utils/buildInlineDatasources.ts +++ b/packages/client/src/generation/utils/buildInlineDatasources.ts @@ -15,10 +15,7 @@ export type InlineDatasources = { * @param internalDatasources * @returns */ -export function buildInlineDatasource( - engineType: ClientEngineType, - internalDatasources: InternalDatasource[], -) { +export function buildInlineDatasource(engineType: ClientEngineType, internalDatasources: InternalDatasource[]) { if (engineType === ClientEngineType.DataProxy) { const datasources = internalToInlineDatasources(internalDatasources) @@ -34,9 +31,7 @@ config.inlineDatasources = ${JSON.stringify(datasources, null, 2)}` * @param internalDatasources * @returns */ -function internalToInlineDatasources( - internalDatasources: InternalDatasource[], -) { +function internalToInlineDatasources(internalDatasources: InternalDatasource[]) { return internalDatasources.reduce((acc, ds) => { acc[ds.name] = { url: ds.url } diff --git a/packages/client/src/generation/utils/buildInlineSchema.ts b/packages/client/src/generation/utils/buildInlineSchema.ts index d49e6be3208b..b81efe0e5b15 100644 --- a/packages/client/src/generation/utils/buildInlineSchema.ts +++ b/packages/client/src/generation/utils/buildInlineSchema.ts @@ -10,10 +10,7 @@ const readFile = fs.promises.readFile * @param schemaPath * @returns */ -export async function buildInlineSchema( - clientEngineType: ClientEngineType, - schemaPath: string, -) { +export async function buildInlineSchema(clientEngineType: ClientEngineType, schemaPath: string) { if (clientEngineType === ClientEngineType.DataProxy) { const b64Schema = (await readFile(schemaPath)).toString('base64') diff --git a/packages/client/src/generation/utils/buildNFTAnnotations.ts b/packages/client/src/generation/utils/buildNFTAnnotations.ts index a45ead34cbb3..49d67ba0eece 100644 --- a/packages/client/src/generation/utils/buildNFTAnnotations.ts +++ b/packages/client/src/generation/utils/buildNFTAnnotations.ts @@ -42,10 +42,7 @@ export function buildNFTAnnotations( * @param platform * @returns */ -function getQueryEngineFilename( - engineType: ClientEngineType, - platform: Platform, -) { +function getQueryEngineFilename(engineType: ClientEngineType, platform: Platform) { if (engineType === ClientEngineType.Library) { return getNodeAPIName(platform, 'fs') } @@ -78,11 +75,7 @@ path.join(process.cwd(), './${path.join(relativeOutdir, fileName)}')` * @param relativeOutdir * @returns */ -function buildNFTEngineAnnotation( - engineType: ClientEngineType, - platform: Platform, - relativeOutdir: string, -) { +function buildNFTEngineAnnotation(engineType: ClientEngineType, platform: Platform, relativeOutdir: string) { const engineFilename = getQueryEngineFilename(engineType, platform) if (engineFilename === undefined) return '' @@ -96,10 +89,7 @@ function buildNFTEngineAnnotation( * @param relativeOutdir * @returns */ -function buildNFTSchemaAnnotation( - engineType: ClientEngineType, - relativeOutdir: string, -) { +function buildNFTSchemaAnnotation(engineType: ClientEngineType, relativeOutdir: string) { if (engineType === ClientEngineType.DataProxy) return '' return buildNFTAnnotation('schema.prisma', relativeOutdir) diff --git a/packages/client/src/generation/utils/buildWarnEnvConflicts.ts b/packages/client/src/generation/utils/buildWarnEnvConflicts.ts index 621b107b9081..24a26ef055f1 100644 --- a/packages/client/src/generation/utils/buildWarnEnvConflicts.ts +++ b/packages/client/src/generation/utils/buildWarnEnvConflicts.ts @@ -8,11 +8,7 @@ import { ClientEngineType } from '../../runtime/utils/getClientEngineType' * @param runtimeName * @returns */ -export function buildWarnEnvConflicts( - clientEngineType: ClientEngineType, - runtimeDir: string, - runtimeName: string, -) { +export function buildWarnEnvConflicts(clientEngineType: ClientEngineType, runtimeDir: string, runtimeName: string) { if (clientEngineType !== ClientEngineType.DataProxy) { return ` const { warnEnvConflicts } = require('${runtimeDir}/${runtimeName}') diff --git a/packages/client/src/keyby.ts b/packages/client/src/keyby.ts index e7c394f82395..bcffda24934d 100644 --- a/packages/client/src/keyby.ts +++ b/packages/client/src/keyby.ts @@ -2,10 +2,7 @@ export interface Dictionary { [key: string]: T } -export const keyBy: ( - collection: T[], - iteratee: (value: T) => string, -) => Dictionary = (collection, iteratee) => { +export const keyBy: (collection: T[], iteratee: (value: T) => string) => Dictionary = (collection, iteratee) => { return collection.reduce((acc, curr) => { acc[iteratee(curr)] = curr return acc diff --git a/packages/client/src/runtime/MiddlewareHandler.ts b/packages/client/src/runtime/MiddlewareHandler.ts index 08c0514ff046..4fa9c40a0e91 100644 --- a/packages/client/src/runtime/MiddlewareHandler.ts +++ b/packages/client/src/runtime/MiddlewareHandler.ts @@ -21,9 +21,7 @@ export type QueryMiddlewareParams = { export type EngineMiddleware = ( params: EngineMiddlewareParams, - next: ( - params: EngineMiddlewareParams, - ) => Promise<{ data: T; elapsed: number }>, + next: (params: EngineMiddlewareParams) => Promise<{ data: T; elapsed: number }>, ) => Promise<{ data: T; elapsed: number }> export type EngineMiddlewareParams = { diff --git a/packages/client/src/runtime/PrismaClientFetcher.ts b/packages/client/src/runtime/PrismaClientFetcher.ts index 14a723ea4799..ed10807cf06b 100644 --- a/packages/client/src/runtime/PrismaClientFetcher.ts +++ b/packages/client/src/runtime/PrismaClientFetcher.ts @@ -150,13 +150,7 @@ export class PrismaClientFetcher { /** * Unpack */ - const unpackResult = this.unpack( - document, - data, - dataPath, - rootField, - unpacker, - ) + const unpackResult = this.unpack(document, data, dataPath, rootField, unpacker) throwIfNotFound(unpackResult, clientMethod, typeName, rejectOnNotFound) if (process.env.PRISMA_CLIENT_GET_TIME) { return { data: unpackResult, elapsed } @@ -178,32 +172,15 @@ export class PrismaClientFetcher { message = this.sanitizeMessage(message) // TODO: Do request with callsite instead, so we don't need to rethrow if (e.code) { - throw new PrismaClientKnownRequestError( - message, - e.code, - this.prisma._clientVersion, - e.meta, - ) + throw new PrismaClientKnownRequestError(message, e.code, this.prisma._clientVersion, e.meta) } else if (e.isPanic) { - throw new PrismaClientRustPanicError( - message, - this.prisma._clientVersion, - ) + throw new PrismaClientRustPanicError(message, this.prisma._clientVersion) } else if (e instanceof PrismaClientUnknownRequestError) { - throw new PrismaClientUnknownRequestError( - message, - this.prisma._clientVersion, - ) + throw new PrismaClientUnknownRequestError(message, this.prisma._clientVersion) } else if (e instanceof PrismaClientInitializationError) { - throw new PrismaClientInitializationError( - message, - this.prisma._clientVersion, - ) + throw new PrismaClientInitializationError(message, this.prisma._clientVersion) } else if (e instanceof PrismaClientRustPanicError) { - throw new PrismaClientRustPanicError( - message, - this.prisma._clientVersion, - ) + throw new PrismaClientRustPanicError(message, this.prisma._clientVersion) } e.clientVersion = this.prisma._clientVersion diff --git a/packages/client/src/runtime/RequestHandler.ts b/packages/client/src/runtime/RequestHandler.ts index 192bd6ffd8df..88c9d5478be5 100644 --- a/packages/client/src/runtime/RequestHandler.ts +++ b/packages/client/src/runtime/RequestHandler.ts @@ -134,13 +134,7 @@ export class RequestHandler { /** * Unpack */ - const unpackResult = this.unpack( - document, - data, - dataPath, - rootField, - unpacker, - ) + const unpackResult = this.unpack(document, data, dataPath, rootField, unpacker) throwIfNotFound(unpackResult, clientMethod, typeName, rejectOnNotFound) if (process.env.PRISMA_CLIENT_GET_TIME) { return { data: unpackResult, elapsed } @@ -162,32 +156,15 @@ export class RequestHandler { message = this.sanitizeMessage(message) // TODO: Do request with callsite instead, so we don't need to rethrow if (e.code) { - throw new PrismaClientKnownRequestError( - message, - e.code, - this.client._clientVersion, - e.meta, - ) + throw new PrismaClientKnownRequestError(message, e.code, this.client._clientVersion, e.meta) } else if (e.isPanic) { - throw new PrismaClientRustPanicError( - message, - this.client._clientVersion, - ) + throw new PrismaClientRustPanicError(message, this.client._clientVersion) } else if (e instanceof PrismaClientUnknownRequestError) { - throw new PrismaClientUnknownRequestError( - message, - this.client._clientVersion, - ) + throw new PrismaClientUnknownRequestError(message, this.client._clientVersion) } else if (e instanceof PrismaClientInitializationError) { - throw new PrismaClientInitializationError( - message, - this.client._clientVersion, - ) + throw new PrismaClientInitializationError(message, this.client._clientVersion) } else if (e instanceof PrismaClientRustPanicError) { - throw new PrismaClientRustPanicError( - message, - this.client._clientVersion, - ) + throw new PrismaClientRustPanicError(message, this.client._clientVersion) } e.clientVersion = this.client._clientVersion diff --git a/packages/client/src/runtime/dmmf.ts b/packages/client/src/runtime/dmmf.ts index dd5decab0d7b..0f11a49f0d07 100644 --- a/packages/client/src/runtime/dmmf.ts +++ b/packages/client/src/runtime/dmmf.ts @@ -55,9 +55,7 @@ export class DMMFClass implements DMMF.Document { get [Symbol.toStringTag]() { return 'DMMFClass' } - protected outputTypeToMergedOutputType = ( - outputType: DMMF.OutputType, - ): DMMF.OutputType => { + protected outputTypeToMergedOutputType = (outputType: DMMF.OutputType): DMMF.OutputType => { const model = this.modelMap[outputType.name] return { ...outputType, @@ -68,10 +66,7 @@ export class DMMFClass implements DMMF.Document { protected resolveOutputTypes() { for (const type of this.outputTypes.model) { for (const field of type.fields) { - if ( - typeof field.outputType.type === 'string' && - !ScalarTypeTable[field.outputType.type] - ) { + if (typeof field.outputType.type === 'string' && !ScalarTypeTable[field.outputType.type]) { field.outputType.type = this.outputTypeMap[field.outputType.type] || this.outputTypeMap[field.outputType.type] || @@ -83,10 +78,7 @@ export class DMMFClass implements DMMF.Document { } for (const type of this.outputTypes.prisma) { for (const field of type.fields) { - if ( - typeof field.outputType.type === 'string' && - !ScalarTypeTable[field.outputType.type] - ) { + if (typeof field.outputType.type === 'string' && !ScalarTypeTable[field.outputType.type]) { field.outputType.type = this.outputTypeMap[field.outputType.type] || this.outputTypeMap[field.outputType.type] || @@ -111,10 +103,7 @@ export class DMMFClass implements DMMF.Document { !ScalarTypeTable[fieldType] && (this.inputTypeMap[fieldType] || this.enumMap[fieldType]) ) { - fieldInputType.type = - this.inputTypeMap[fieldType] || - this.enumMap[fieldType] || - fieldType + fieldInputType.type = this.inputTypeMap[fieldType] || this.enumMap[fieldType] || fieldType } } } @@ -128,8 +117,7 @@ export class DMMFClass implements DMMF.Document { for (const argInputType of arg.inputTypes) { const argType = argInputType.type if (typeof argType === 'string' && !ScalarTypeTable[argType]) { - argInputType.type = - this.inputTypeMap[argType] || this.enumMap[argType] || argType + argInputType.type = this.inputTypeMap[argType] || this.enumMap[argType] || argType } } } @@ -141,10 +129,7 @@ export class DMMFClass implements DMMF.Document { for (const argInputType of arg.inputTypes) { const argType = argInputType.type if (typeof argType === 'string' && !ScalarTypeTable[argType]) { - argInputType.type = - this.inputTypeMap[argType] || - this.enumMap[argType] || - argInputType.type + argInputType.type = this.inputTypeMap[argType] || this.enumMap[argType] || argInputType.type } } } @@ -155,21 +140,15 @@ export class DMMFClass implements DMMF.Document { return this.schema.outputObjectTypes.prisma.find((t) => t.name === 'Query')! } protected getMutationType(): DMMF.OutputType { - return this.schema.outputObjectTypes.prisma.find( - (t) => t.name === 'Mutation', - )! + return this.schema.outputObjectTypes.prisma.find((t) => t.name === 'Mutation')! } protected getOutputTypes(): { model: DMMF.OutputType[] prisma: DMMF.OutputType[] } { return { - model: this.schema.outputObjectTypes.model.map( - this.outputTypeToMergedOutputType, - ), - prisma: this.schema.outputObjectTypes.prisma.map( - this.outputTypeToMergedOutputType, - ), + model: this.schema.outputObjectTypes.model.map(this.outputTypeToMergedOutputType), + prisma: this.schema.outputObjectTypes.prisma.map(this.outputTypeToMergedOutputType), } } protected getDatamodelEnumMap(): Dictionary { @@ -178,9 +157,7 @@ export class DMMFClass implements DMMF.Document { protected getEnumMap(): Dictionary { return { ...keyBy(this.schema.enumTypes.prisma, 'name'), - ...(this.schema.enumTypes.model - ? keyBy(this.schema.enumTypes.model, 'name') - : undefined), + ...(this.schema.enumTypes.model ? keyBy(this.schema.enumTypes.model, 'name') : undefined), } } protected getModelMap(): Dictionary { @@ -194,9 +171,7 @@ export class DMMFClass implements DMMF.Document { } protected getInputTypeMap(): Dictionary { return { - ...(this.schema.inputObjectTypes.model - ? keyBy(this.schema.inputObjectTypes.model, 'name') - : undefined), + ...(this.schema.inputObjectTypes.model ? keyBy(this.schema.inputObjectTypes.model, 'name') : undefined), ...keyBy(this.schema.inputObjectTypes.prisma, 'name'), } } diff --git a/packages/client/src/runtime/externalToInternalDmmf.ts b/packages/client/src/runtime/externalToInternalDmmf.ts index 6fb5c908c4c8..a26239654454 100644 --- a/packages/client/src/runtime/externalToInternalDmmf.ts +++ b/packages/client/src/runtime/externalToInternalDmmf.ts @@ -11,19 +11,14 @@ export function getCountAggregateOutputName(modelName: string): string { * Turns type: string into type: string[] for all args in order to support union input types * @param document */ -export function externalToInternalDmmf( - document: ExternalDMMF.Document, -): DMMF.Document { +export function externalToInternalDmmf(document: ExternalDMMF.Document): DMMF.Document { return { ...document, mappings: getMappings(document.mappings, document.datamodel), } } -function getMappings( - mappings: ExternalDMMF.Mappings, - datamodel: DMMF.Datamodel, -): DMMF.Mappings { +function getMappings(mappings: ExternalDMMF.Mappings, datamodel: DMMF.Datamodel): DMMF.Mappings { const modelOperations = mappings.modelOperations .filter((mapping) => { const model = datamodel.models.find((m) => m.name === mapping.model) diff --git a/packages/client/src/runtime/getLogLevel.ts b/packages/client/src/runtime/getLogLevel.ts index f2c652f9f3ac..0cb3a39a7050 100644 --- a/packages/client/src/runtime/getLogLevel.ts +++ b/packages/client/src/runtime/getLogLevel.ts @@ -4,9 +4,7 @@ type LogDefinition = { emit: 'stdout' | 'event' } -export function getLogLevel( - log: LogLevel | Array, -): LogLevel | undefined { +export function getLogLevel(log: LogLevel | Array): LogLevel | undefined { if (typeof log === 'string') { return log } diff --git a/packages/client/src/runtime/getPrismaClient.ts b/packages/client/src/runtime/getPrismaClient.ts index 52b023f4af28..dafc3119c4b8 100644 --- a/packages/client/src/runtime/getPrismaClient.ts +++ b/packages/client/src/runtime/getPrismaClient.ts @@ -1,10 +1,5 @@ import Debug from '@prisma/debug' -import type { - DatasourceOverwrite, - Engine, - EngineConfig, - EngineEventType, -} from '@prisma/engine-core' +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' @@ -16,20 +11,12 @@ import { AsyncResource } from 'async_hooks' import fs from 'fs' import path from 'path' import * as sqlTemplateTag from 'sql-template-tag' -import { - ClientEngineType, - getClientEngineType, -} from './utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from './utils/getClientEngineType' 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 type { EngineMiddleware, Namespace, QueryMiddleware, QueryMiddlewareParams } from './MiddlewareHandler' import { Middlewares } from './MiddlewareHandler' import { PrismaClientFetcher } from './PrismaClientFetcher' import { makeDocument, transformDocument } from './query' @@ -38,10 +25,7 @@ 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 type { InstanceRejectOnNotFound, RejectOnNotFound } from './utils/rejectOnNotFound' import { getRejectOnNotFound } from './utils/rejectOnNotFound' import { serializeRawParameters } from './utils/serializeRawParameters' import { validatePrismaClientOptions } from './utils/validatePrismaClientOptions' @@ -189,12 +173,11 @@ export type LogDefinition = { emit: 'stdout' | 'event' } -export type GetLogType = - T extends LogDefinition - ? T['emit'] extends 'event' - ? T['level'] - : never +export type GetLogType = T extends LogDefinition + ? T['emit'] extends 'event' + ? T['level'] : never + : never export type GetEvents> = | GetLogType | GetLogType @@ -291,18 +274,12 @@ export interface Client { _engineConfig: EngineConfig _clientVersion: string _errorFormat: ErrorFormat - $use( - arg0: Namespace | QueryMiddleware, - arg1?: QueryMiddleware | EngineMiddleware, - ) + $use(arg0: Namespace | QueryMiddleware, arg1?: QueryMiddleware | EngineMiddleware) $on(eventType: EngineEventType, callback: (event: any) => void) $connect() $disconnect() _runDisconnect() - $executeRaw( - query: TemplateStringsArray | sqlTemplateTag.Sql, - ...values: any[] - ) + $executeRaw(query: TemplateStringsArray | sqlTemplateTag.Sql, ...values: any[]) $queryRaw(query: TemplateStringsArray | sqlTemplateTag.Sql, ...values: any[]) __internal_triggerPanic(fatal: boolean) $transaction(input: any, options?: any) @@ -341,16 +318,12 @@ export function getPrismaClient(config: GetPrismaClientConfig) { this._clientEngineType = getClientEngineType(config.generator!) const envPaths = { rootEnvPath: - config.relativeEnvPaths.rootEnvPath && - path.resolve(config.dirname, config.relativeEnvPaths.rootEnvPath), + config.relativeEnvPaths.rootEnvPath && path.resolve(config.dirname, config.relativeEnvPaths.rootEnvPath), schemaEnvPath: - config.relativeEnvPaths.schemaEnvPath && - path.resolve(config.dirname, config.relativeEnvPaths.schemaEnvPath), + config.relativeEnvPaths.schemaEnvPath && path.resolve(config.dirname, config.relativeEnvPaths.schemaEnvPath), } - const loadedEnv = - globalThis.NOT_PRISMA_DATA_PROXY && - tryLoadEnvs(envPaths, { conflictCheck: 'none' }) + const loadedEnv = globalThis.NOT_PRISMA_DATA_PROXY && tryLoadEnvs(envPaths, { conflictCheck: 'none' }) try { const options: PrismaClientOptions = optionsArg ?? {} @@ -383,11 +356,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { url, })) - const datasources = mergeBy( - [], - inputDatasources, - (source: any) => source.name, - ) + const datasources = mergeBy([], inputDatasources, (source: any) => source.name) const engineConfig = internal.engine || {} @@ -422,9 +391,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { Boolean( typeof options.log === 'string' ? options.log === 'query' - : options.log.find((o) => - typeof o === 'string' ? o === 'query' : o.level === 'query', - ), + : options.log.find((o) => (typeof o === 'string' ? o === 'query' : o.level === 'query')), ), // we attempt to load env with fs -> attempt inline env -> default env: loadedEnv ? loadedEnv.parsed : config.inlineEnv?.parsed ?? {}, @@ -459,18 +426,10 @@ export function getPrismaClient(config: GetPrismaClientConfig) { if (options.log) { for (const log of options.log) { - const level = - typeof log === 'string' - ? log - : log.emit === 'stdout' - ? log.level - : null + 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, - ) + logger.log(`${logger.tags[level] ?? ''}`, event.message || event.query) }) } } @@ -489,14 +448,12 @@ export function getPrismaClient(config: GetPrismaClientConfig) { if (this._clientEngineType === ClientEngineType.Library) { return ( // this is for tree-shaking for esbuild - globalThis.NOT_PRISMA_DATA_PROXY && - new LibraryEngine(this._engineConfig) + globalThis.NOT_PRISMA_DATA_PROXY && new LibraryEngine(this._engineConfig) ) } else if (this._clientEngineType === ClientEngineType.Binary) { return ( // this is for tree-shaking for esbuild - globalThis.NOT_PRISMA_DATA_PROXY && - new BinaryEngine(this._engineConfig) + globalThis.NOT_PRISMA_DATA_PROXY && new BinaryEngine(this._engineConfig) ) } else { return new DataProxyEngine(this._engineConfig) @@ -510,10 +467,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { $use(middleware: QueryMiddleware) $use(namespace: 'all', cb: QueryMiddleware) // TODO: 'all' actually means 'query', to be changed $use(namespace: 'engine', cb: EngineMiddleware) - $use( - arg0: Namespace | QueryMiddleware, - arg1?: QueryMiddleware | EngineMiddleware, - ) { + $use(arg0: Namespace | QueryMiddleware, arg1?: QueryMiddleware | EngineMiddleware) { // TODO use a mixin and move this into MiddlewareHandler if (typeof arg0 === 'function') { this._middlewares.query.use(arg0 as QueryMiddleware) @@ -611,11 +565,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { values: serializeRawParameters(values || []), __prismaRawParamaters__: true, } - checkAlter( - queryString, - values, - 'prisma.$executeRawUnsafe(, [...values])', - ) + checkAlter(queryString, values, 'prisma.$executeRawUnsafe(, [...values])') } else if (isReadonlyArray(query)) { // If this was called as prisma.$executeRaw``, try to generate a SQL prepared statement switch (this._activeProvider) { @@ -635,11 +585,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { const queryInstance = sqlTemplateTag.sqltag(query, ...values) queryString = queryInstance.text - checkAlter( - queryString, - queryInstance.values, - 'prisma.$executeRaw``', - ) + checkAlter(queryString, queryInstance.values, 'prisma.$executeRaw``') parameters = { values: serializeRawParameters(queryInstance.values), __prismaRawParamaters__: true, @@ -665,11 +611,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { break case 'postgresql': queryString = query.text - checkAlter( - queryString, - query.values, - 'prisma.$executeRaw(sql``)', - ) + checkAlter(queryString, query.values, 'prisma.$executeRaw(sql``)') break case 'sqlserver': queryString = mssqlPreparedStatement(query.strings) @@ -710,12 +652,7 @@ export function getPrismaClient(config: GetPrismaClientConfig) { ) { const request = (transactionId?: number, runInTransaction?: boolean) => { try { - const promise = this.$executeRawInternal( - runInTransaction ?? false, - transactionId, - query, - ...values, - ) + const promise = this.$executeRawInternal(runInTransaction ?? false, transactionId, query, ...values) ;(promise as any).isExecuteRaw = true return promise } catch (e: any) { @@ -735,15 +672,9 @@ export function getPrismaClient(config: GetPrismaClientConfig) { * @param values * @returns */ - $executeRaw( - query: TemplateStringsArray | sqlTemplateTag.Sql, - ...values: any[] - ) { + $executeRaw(query: TemplateStringsArray | sqlTemplateTag.Sql, ...values: any[]) { return createPrismaPromise(() => { - if ( - (query as TemplateStringsArray).raw || - (query as sqlTemplateTag.Sql).sql - ) { + if ((query as TemplateStringsArray).raw || (query as sqlTemplateTag.Sql).sql) { return this.$executeRawRequest(query, ...values) } @@ -884,12 +815,7 @@ Or read our docs at https://www.prisma.io/docs/concepts/components/prisma-client ) { const request = (transactionId?: number, runInTransaction?: boolean) => { try { - const promise = this.$queryRawInternal( - runInTransaction ?? false, - transactionId, - query, - ...values, - ) + const promise = this.$queryRawInternal(runInTransaction ?? false, transactionId, query, ...values) ;(promise as any).isQueryRaw = true return promise } catch (e: any) { @@ -909,15 +835,9 @@ Or read our docs at https://www.prisma.io/docs/concepts/components/prisma-client * @param values * @returns */ - $queryRaw( - query: TemplateStringsArray | sqlTemplateTag.Sql, - ...values: any[] - ) { + $queryRaw(query: TemplateStringsArray | sqlTemplateTag.Sql, ...values: any[]) { return createPrismaPromise(() => { - if ( - (query as TemplateStringsArray).raw || - (query as sqlTemplateTag.Sql).sql - ) { + if ((query as TemplateStringsArray).raw || (query as sqlTemplateTag.Sql).sql) { return this.$queryRawRequest(query, ...values) } @@ -957,9 +877,7 @@ new PrismaClient({ // TODO: make a `fatal` boolean instead & let be handled in `engine-core` // in `runtimeHeadersToHttpHeaders` maybe add a shared in `Engine` - const headers: Record = fatal - ? { 'X-DEBUG-FATAL': '1' } - : { 'X-DEBUG-NON-FATAL': '1' } + const headers: Record = fatal ? { 'X-DEBUG-FATAL': '1' } : { 'X-DEBUG-NON-FATAL': '1' } return this._request({ action: 'queryRaw', @@ -993,8 +911,7 @@ new PrismaClient({ ) } if ( - (!p.requestTransaction || - typeof p.requestTransaction !== 'function') && + (!p.requestTransaction || typeof p.requestTransaction !== 'function') && !p?.isQueryRaw && !p?.isExecuteRaw ) { @@ -1235,12 +1152,7 @@ new PrismaClient({ const { isList } = field.outputType const typeName = getOutputTypeName(field.outputType.type) - const rejectOnNotFound: RejectOnNotFound = getRejectOnNotFound( - action, - typeName, - args, - this._rejectOnNotFound, - ) + const rejectOnNotFound: RejectOnNotFound = getRejectOnNotFound(action, typeName, args, this._rejectOnNotFound) let document = makeDocument({ dmmf: this._dmmf, rootField: rootField!, @@ -1289,100 +1201,90 @@ new PrismaClient({ } 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 modelClientBuilders = this._dmmf.mappings.modelOperations.reduce((modelClientBuilders, modelMapping) => { + const lowerCaseModel = lowerCase(modelMapping.model) + const model = this._dmmf.modelMap[modelMapping.model] - // creates a builder for `prisma...` in the runtime so that - // all models will get their own sub-"client" for query execution - const ModelClientBuilder = ({ - operation, - actionName, - args, - dataPath, - modelName, - unpacker, - }: { - operation: string - actionName: Action - args: any - dataPath: string[] - modelName: string - unpacker?: Unpacker - }) => { - let requestPromise: Promise | undefined - - // prepare a request with current context & prevent multi-calls we - // save it into `requestPromise` to allow one request per promise - const callsite = this._getCallsite() - const request = ( - transactionId?: number, - runInTransaction?: boolean, - ) => { - 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 - } + if (!model) { + throw new Error(`Invalid mapping ${modelMapping.model}, can't find model`) + } - // `modelClient` implements promises to have deferred actions that - // will be called later on through model delegated functions - const modelClient = createPrismaPromise(request) - - // add relation fields - 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]({ - operation, - actionName, - args: newArgs, - dataPath: newDataPath, - isList: field.isList, - /* - * necessary for user.posts() calls -> the original model name needs to be preserved - */ - modelName: modelName || model.name, - }) - } - } + // creates a builder for `prisma...` in the runtime so that + // all models will get their own sub-"client" for query execution + const ModelClientBuilder = ({ + operation, + actionName, + args, + dataPath, + modelName, + unpacker, + }: { + operation: string + actionName: Action + args: any + dataPath: string[] + modelName: string + unpacker?: Unpacker + }) => { + let requestPromise: Promise | undefined + + // prepare a request with current context & prevent multi-calls we + // save it into `requestPromise` to allow one request per promise + const callsite = this._getCallsite() + const request = (transactionId?: number, runInTransaction?: boolean) => { + 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 + } - return modelClient + // `modelClient` implements promises to have deferred actions that + // will be called later on through model delegated functions + const modelClient = createPrismaPromise(request) + + // add relation fields + 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]({ + operation, + actionName, + args: newArgs, + dataPath: newDataPath, + isList: field.isList, + /* + * necessary for user.posts() calls -> the original model name needs to be preserved + */ + modelName: modelName || model.name, + }) + } } - modelClientBuilders[model.name] = ModelClientBuilder + return modelClient + } + + modelClientBuilders[model.name] = ModelClientBuilder - return modelClientBuilders - }, - {}, - ) + return modelClientBuilders + }, {}) for (const mapping of this._dmmf.mappings.modelOperations) { const lowerCaseModel = lowerCase(mapping.model) @@ -1509,11 +1411,7 @@ new PrismaClient({ unpacker = (data) => { if (Array.isArray(data)) { data = data.map((row) => { - if ( - row && - typeof row._count === 'object' && - row._count?._all - ) { + if (row && typeof row._count === 'object' && row._count?._all) { row._count = row._count?._all } return row @@ -1637,10 +1535,7 @@ interface PrismaPromise extends Promise { * @returns */ function createPrismaPromise( - callback: ( - transactionId?: number, - runInTransaction?: boolean, - ) => PrismaPromise, + callback: (transactionId?: number, runInTransaction?: boolean) => PrismaPromise, ): PrismaPromise { // we handle exceptions that happen in the scope as `Promise` rejections const _callback = (transactionId?: number, runInTransaction?: boolean) => { diff --git a/packages/client/src/runtime/highlight/languages/sql.ts b/packages/client/src/runtime/highlight/languages/sql.ts index 94e98a350c54..804471c39b50 100644 --- a/packages/client/src/runtime/highlight/languages/sql.ts +++ b/packages/client/src/runtime/highlight/languages/sql.ts @@ -17,8 +17,7 @@ export const sql: SyntaxDefinition = { greedy: true, lookbehind: true, }, - function: - /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too? + function: /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too? keyword: /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i, boolean: /\b(?:TRUE|FALSE|NULL)\b/i, diff --git a/packages/client/src/runtime/index.ts b/packages/client/src/runtime/index.ts index d139b98eaf66..493aee373cfc 100644 --- a/packages/client/src/runtime/index.ts +++ b/packages/client/src/runtime/index.ts @@ -1,11 +1,6 @@ export { DMMF } from './dmmf-types' export { DMMFClass } from './dmmf' -export { - makeDocument, - transformDocument, - unpack, - PrismaClientValidationError, -} from './query' +export { makeDocument, transformDocument, unpack, PrismaClientValidationError } from './query' export { Engine, diff --git a/packages/client/src/runtime/mergeBy.ts b/packages/client/src/runtime/mergeBy.ts index 2b0536848f3c..7c8808781c1e 100644 --- a/packages/client/src/runtime/mergeBy.ts +++ b/packages/client/src/runtime/mergeBy.ts @@ -6,16 +6,10 @@ * @param arr2 Array to overwrite the first one if there is a match * @param cb The function to calculate uniqueness */ -export function mergeBy( - arr1: T[], - arr2: T[], - cb: (element: T) => string, -): T[] { +export function mergeBy(arr1: T[], arr2: T[], cb: (element: T) => string): T[] { const groupedArr1 = groupBy(arr1, cb) const groupedArr2 = groupBy(arr2, cb) - const result: T[] = Object.values(groupedArr2).map( - (value) => value[value.length - 1], - ) + const result: T[] = Object.values(groupedArr2).map((value) => value[value.length - 1]) const arr2Keys = Object.keys(groupedArr2) Object.entries(groupedArr1).forEach(([key, value]) => { @@ -27,10 +21,7 @@ export function mergeBy( return result } -const groupBy = ( - arr: T[], - cb: (element: T) => string, -): { [key: string]: T[] } => { +const groupBy = (arr: T[], cb: (element: T) => string): { [key: string]: T[] } => { return arr.reduce<{ [key: string]: T[] }>((acc, curr) => { const key = cb(curr) if (!acc[key]) { diff --git a/packages/client/src/runtime/query.ts b/packages/client/src/runtime/query.ts index fe432a3aa62f..bbe00f7bd26c 100644 --- a/packages/client/src/runtime/query.ts +++ b/packages/client/src/runtime/query.ts @@ -30,10 +30,7 @@ import { filterObject } from './utils/filterObject' import { flatMap } from './utils/flatMap' import { isObject } from './utils/isObject' import { omit } from './utils/omit' -import type { - MissingItem, - PrintJsonWithErrorsArgs, -} from './utils/printJsonErrors' +import type { MissingItem, PrintJsonWithErrorsArgs } from './utils/printJsonErrors' import { printJsonWithErrors } from './utils/printJsonErrors' import { printStack } from './utils/printStack' import stringifyObject from './utils/stringifyObject' @@ -41,10 +38,7 @@ import stringifyObject from './utils/stringifyObject' const tab = 2 export class Document { - constructor( - public readonly type: 'query' | 'mutation', - public readonly children: Field[], - ) { + constructor(public readonly type: 'query' | 'mutation', public readonly children: Field[]) { this.type = type this.children = children } @@ -66,21 +60,14 @@ ${indent(this.children.map(String).join('\n'), tab)} if (!select) { select = {} } - const invalidChildren = this.children.filter( - (child) => child.hasInvalidChild || child.hasInvalidArg, - ) + const invalidChildren = this.children.filter((child) => child.hasInvalidChild || child.hasInvalidArg) if (invalidChildren.length === 0) { return } const fieldErrors: FieldError[] = [] const argErrors: ArgError[] = [] - const prefix = - select && select.select - ? 'select' - : select.include - ? 'include' - : undefined + const prefix = select && select.select ? 'select' : select.include ? 'include' : undefined for (const child of invalidChildren) { const errors = child.collectErrors(prefix) @@ -111,17 +98,11 @@ ${indent(this.children.map(String).join('\n'), tab)} const fieldType = fieldError.error.outputType const { isInclude } = fieldError.error fieldType.fields - .filter((field) => - isInclude - ? field.outputType.location === 'outputObjectTypes' - : true, - ) + .filter((field) => (isInclude ? field.outputType.location === 'outputObjectTypes' : true)) .forEach((field) => { const splittedPath = path.split('.') missingItems.push({ - path: `${splittedPath - .slice(0, splittedPath.length - 1) - .join('.')}.${field.name}`, + path: `${splittedPath.slice(0, splittedPath.length - 1).join('.')}.${field.name}`, type: 'true', isRequired: false, }) @@ -138,18 +119,13 @@ ${indent(this.children.map(String).join('\n'), tab)} fieldError.error.type === 'emptyInclude' ) { const selectPathArray = this.normalizePath(fieldError.path, select) - const selectPath = selectPathArray - .slice(0, selectPathArray.length - 1) - .join('.') + const selectPath = selectPathArray.slice(0, selectPathArray.length - 1).join('.') - const fieldType = fieldError.error.field.outputType - .type as DMMF.OutputType + const fieldType = fieldError.error.field.outputType.type as DMMF.OutputType fieldType.fields ?.filter((field) => - fieldError.error.type === 'emptyInclude' - ? field.outputType.location === 'outputObjectTypes' - : true, + fieldError.error.type === 'emptyInclude' ? field.outputType.location === 'outputObjectTypes' : true, ) .forEach((field) => { missingItems.push({ @@ -165,10 +141,7 @@ ${indent(this.children.map(String).join('\n'), tab)} const path = this.normalizePath(argError.path, select).join('.') if (argError.error.type === 'invalidName') { keyPaths.push(path) - } else if ( - argError.error.type !== 'missingArg' && - argError.error.type !== 'atLeastOne' - ) { + } else if (argError.error.type !== 'missingArg' && argError.error.type !== 'atLeastOne') { valuePaths.push(path) } else if (argError.error.type === 'missingArg') { const type = @@ -199,19 +172,15 @@ ${indent(this.children.map(String).join('\n'), tab)} (e) => e.error.type === 'missingArg' && e.error.missingArg.isRequired, ) const hasOptionalMissingArgsErrors = Boolean( - argErrors.find( - (e) => - e.error.type === 'missingArg' && !e.error.missingArg.isRequired, - ), + argErrors.find((e) => e.error.type === 'missingArg' && !e.error.missingArg.isRequired), ) - const hasMissingArgsErrors = - hasOptionalMissingArgsErrors || hasRequiredMissingArgsErrors + const hasMissingArgsErrors = hasOptionalMissingArgsErrors || hasRequiredMissingArgsErrors let missingArgsLegend = '' if (hasRequiredMissingArgsErrors) { - missingArgsLegend += `\n${chalk.dim( - 'Note: Lines with ', - )}${chalk.reset.greenBright('+')} ${chalk.dim('are required')}` + missingArgsLegend += `\n${chalk.dim('Note: Lines with ')}${chalk.reset.greenBright('+')} ${chalk.dim( + 'are required', + )}` } if (hasOptionalMissingArgsErrors) { @@ -219,35 +188,21 @@ ${indent(this.children.map(String).join('\n'), tab)} missingArgsLegend = '\n' } if (hasRequiredMissingArgsErrors) { - missingArgsLegend += chalk.dim( - `, lines with ${chalk.green('?')} are optional`, - ) + missingArgsLegend += chalk.dim(`, lines with ${chalk.green('?')} are optional`) } else { - missingArgsLegend += chalk.dim( - `Note: Lines with ${chalk.green('?')} are optional`, - ) + missingArgsLegend += chalk.dim(`Note: Lines with ${chalk.green('?')} are optional`) } missingArgsLegend += chalk.dim('.') } - const relevantArgErrors = argErrors.filter( - (e) => e.error.type !== 'missingArg' || e.error.missingArg.isRequired, - ) + const relevantArgErrors = argErrors.filter((e) => e.error.type !== 'missingArg' || e.error.missingArg.isRequired) let errorMessages = relevantArgErrors - .map((e) => - this.printArgError( - e, - hasMissingArgsErrors, - errorFormat === 'minimal', - ), - ) // if no callsite is provided, just render the minimal error + .map((e) => this.printArgError(e, hasMissingArgsErrors, errorFormat === 'minimal')) // if no callsite is provided, just render the minimal error .join('\n') errorMessages += ` -${fieldErrors - .map((e) => this.printFieldError(e, missingItems, errorFormat === 'minimal')) - .join('\n')}` +${fieldErrors.map((e) => this.printFieldError(e, missingItems, errorFormat === 'minimal')).join('\n')}` if (errorFormat === 'minimal') { return stripAnsi(errorMessages) @@ -277,10 +232,9 @@ ${fieldErrors printJsonArgs = transformAggregatePrintJsonArgs(printJsonArgs) } - const errorStr = `${stack}${indent( - printJsonWithErrors(printJsonArgs), + const errorStr = `${stack}${indent(printJsonWithErrors(printJsonArgs), indentValue).slice( indentValue, - ).slice(indentValue)}${chalk.dim(afterLines)} + )}${chalk.dim(afterLines)} ${errorMessages}${missingArgsLegend}\n` @@ -291,9 +245,7 @@ ${errorMessages}${missingArgsLegend}\n` } // end renderErrorStr definition - const error = new PrismaClientValidationError( - renderErrorStr(validationCallsite), - ) + const error = new PrismaClientValidationError(renderErrorStr(validationCallsite)) // @ts-ignore if (process.env.NODE_ENV !== 'production') { @@ -304,18 +256,10 @@ ${errorMessages}${missingArgsLegend}\n` } throw error } - protected printFieldError = ( - { error }: FieldError, - missingItems: MissingItem[], - minimal: boolean, - ) => { + protected printFieldError = ({ error }: FieldError, missingItems: MissingItem[], minimal: boolean) => { if (error.type === 'emptySelect') { - const additional = minimal - ? '' - : ` Available options are listed in ${chalk.greenBright.dim('green')}.` - return `The ${chalk.redBright( - '`select`', - )} statement for type ${chalk.bold( + const additional = minimal ? '' : ` Available options are listed in ${chalk.greenBright.dim('green')}.` + return `The ${chalk.redBright('`select`')} statement for type ${chalk.bold( getOutputTypeName(error.field.outputType.type), )} must not be empty.${additional}` } @@ -323,32 +267,22 @@ ${errorMessages}${missingArgsLegend}\n` if (missingItems.length === 0) { return `${chalk.bold( getOutputTypeName(error.field.outputType.type), - )} does not have any relation and therefore can't have an ${chalk.redBright( - '`include`', - )} statement.` + )} does not have any relation and therefore can't have an ${chalk.redBright('`include`')} statement.` } - const additional = minimal - ? '' - : ` Available options are listed in ${chalk.greenBright.dim('green')}.` - return `The ${chalk.redBright( - '`include`', - )} statement for type ${chalk.bold( + const additional = minimal ? '' : ` Available options are listed in ${chalk.greenBright.dim('green')}.` + return `The ${chalk.redBright('`include`')} statement for type ${chalk.bold( getOutputTypeName(error.field.outputType.type), )} must not be empty.${additional}` } if (error.type === 'noTrueSelect') { - return `The ${chalk.redBright( - '`select`', - )} statement for type ${chalk.bold( + return `The ${chalk.redBright('`select`')} statement for type ${chalk.bold( getOutputTypeName(error.field.outputType.type), )} needs ${chalk.bold('at least one truthy value')}.` } if (error.type === 'includeAndSelect') { - return `Please ${chalk.bold('either')} use ${chalk.greenBright( - '`include`', - )} or ${chalk.greenBright('`select`')}, but ${chalk.redBright( - 'not both', - )} at the same time.` + return `Please ${chalk.bold('either')} use ${chalk.greenBright('`include`')} or ${chalk.greenBright( + '`select`', + )}, but ${chalk.redBright('not both')} at the same time.` } if (error.type === 'invalidFieldName') { const statement = error.isInclude ? 'include' : 'select' @@ -356,24 +290,18 @@ ${errorMessages}${missingArgsLegend}\n` const additional = minimal ? '' : error.isInclude && missingItems.length === 0 - ? `\nThis model has no relations, so you can't use ${chalk.redBright( - 'include', - )} with it.` + ? `\nThis model has no relations, so you can't use ${chalk.redBright('include')} with it.` : ` Available options are listed in ${chalk.greenBright.dim('green')}.` - let str = `${wording} field ${chalk.redBright( - `\`${error.providedName}\``, - )} for ${chalk.bold(statement)} statement on model ${chalk.bold.white( - error.modelName, - )}.${additional}` + let str = `${wording} field ${chalk.redBright(`\`${error.providedName}\``)} for ${chalk.bold( + statement, + )} statement on model ${chalk.bold.white(error.modelName)}.${additional}` if (error.didYouMean) { str += ` Did you mean ${chalk.greenBright(`\`${error.didYouMean}\``)}?` } if (error.isIncludeScalar) { - str += `\nNote, that ${chalk.bold( - 'include', - )} statements only accept relation fields.` + str += `\nNote, that ${chalk.bold('include')} statements only accept relation fields.` } return str @@ -381,15 +309,11 @@ ${errorMessages}${missingArgsLegend}\n` if (error.type === 'invalidFieldType') { const str = `Invalid value ${chalk.redBright( `${stringifyObject(error.providedValue)}`, - )} of type ${chalk.redBright( - getGraphQLType(error.providedValue, undefined), - )} for field ${chalk.bold( + )} of type ${chalk.redBright(getGraphQLType(error.providedValue, undefined))} for field ${chalk.bold( `${error.fieldName}`, - )} on model ${chalk.bold.white( - error.modelName, - )}. Expected either ${chalk.greenBright('true')} or ${chalk.greenBright( - 'false', - )}.` + )} on model ${chalk.bold.white(error.modelName)}. Expected either ${chalk.greenBright( + 'true', + )} or ${chalk.greenBright('false')}.` return str } @@ -397,44 +321,25 @@ ${errorMessages}${missingArgsLegend}\n` return undefined } - protected printArgError = ( - { error, path, id }: ArgError, - hasMissingItems: boolean, - minimal: boolean, - ) => { + protected printArgError = ({ error, path, id }: ArgError, hasMissingItems: boolean, minimal: boolean) => { if (error.type === 'invalidName') { - let str = `Unknown arg ${chalk.redBright( - `\`${error.providedName}\``, - )} in ${chalk.bold(path.join('.'))} for type ${chalk.bold( - error.outputType - ? error.outputType.name - : getInputTypeName(error.originalType), - )}.` + let str = `Unknown arg ${chalk.redBright(`\`${error.providedName}\``)} in ${chalk.bold( + path.join('.'), + )} for type ${chalk.bold(error.outputType ? error.outputType.name : getInputTypeName(error.originalType))}.` if (error.didYouMeanField) { - str += `\nā†’ Did you forget to wrap it with \`${chalk.greenBright( - 'select', - )}\`? ${chalk.dim( - 'e.g. ' + - chalk.greenBright( - `{ select: { ${error.providedName}: ${error.providedValue} } }`, - ), + str += `\nā†’ Did you forget to wrap it with \`${chalk.greenBright('select')}\`? ${chalk.dim( + 'e.g. ' + chalk.greenBright(`{ select: { ${error.providedName}: ${error.providedValue} } }`), )}` } else if (error.didYouMeanArg) { str += ` Did you mean \`${chalk.greenBright(error.didYouMeanArg)}\`?` if (!hasMissingItems && !minimal) { - str += - ` ${chalk.dim('Available args:')}\n` + - stringifyInputType(error.originalType, true) + str += ` ${chalk.dim('Available args:')}\n` + stringifyInputType(error.originalType, true) } } else { if ((error.originalType as DMMF.InputType).fields.length === 0) { - str += ` The field ${chalk.bold( - (error.originalType as DMMF.InputType).name, - )} has no arguments.` + str += ` The field ${chalk.bold((error.originalType as DMMF.InputType).name)} has no arguments.` } else if (!hasMissingItems && !minimal) { - str += - ` Available args:\n\n` + - stringifyInputType(error.originalType, true) + str += ` Available args:\n\n` + stringifyInputType(error.originalType, true) } } return str @@ -449,13 +354,9 @@ ${errorMessages}${missingArgsLegend}\n` // TODO: we don't yet support enums in a union with a non enum. This is mostly due to not implemented error handling // at this code part. if (error.requiredType.bestFittingType.location === 'enumTypes') { - return `Argument ${chalk.bold( - error.argName, - )}: Provided value ${chalk.redBright(valueStr)}${ + return `Argument ${chalk.bold(error.argName)}: Provided value ${chalk.redBright(valueStr)}${ multilineValue ? '' : ' ' - }of type ${chalk.redBright( - getGraphQLType(error.providedValue), - )} on ${chalk.bold( + }of type ${chalk.redBright(getGraphQLType(error.providedValue))} on ${chalk.bold( `prisma.${this.children[0].name}`, )} is not a ${chalk.greenBright( wrapWithList( @@ -463,32 +364,18 @@ ${errorMessages}${missingArgsLegend}\n` error.requiredType.bestFittingType.isList, ), )}. -ā†’ Possible values: ${( - error.requiredType.bestFittingType.type as DMMF.SchemaEnum - ).values - .map((v) => - chalk.greenBright( - `${stringifyGraphQLType( - error.requiredType.bestFittingType.type, - )}.${v}`, - ), - ) +ā†’ Possible values: ${(error.requiredType.bestFittingType.type as DMMF.SchemaEnum).values + .map((v) => chalk.greenBright(`${stringifyGraphQLType(error.requiredType.bestFittingType.type)}.${v}`)) .join(', ')}` } let typeStr = '.' if (isInputArgType(error.requiredType.bestFittingType.type)) { - typeStr = - ':\n' + stringifyInputType(error.requiredType.bestFittingType.type) + typeStr = ':\n' + stringifyInputType(error.requiredType.bestFittingType.type) } let expected = `${error.requiredType.inputType .map((t) => - chalk.greenBright( - wrapWithList( - stringifyGraphQLType(t.type), - error.requiredType.bestFittingType.isList, - ), - ), + chalk.greenBright(wrapWithList(stringifyGraphQLType(t.type), error.requiredType.bestFittingType.isList)), ) .join(' or ')}${typeStr}` const inputType: null | DMMF.SchemaArgInputType = @@ -498,44 +385,26 @@ ${errorMessages}${missingArgsLegend}\n` if (inputType) { expected += `\n` + stringifyInputType(inputType.type, true) } - return `Argument ${chalk.bold( - error.argName, - )}: Got invalid value ${chalk.redBright(valueStr)}${ + return `Argument ${chalk.bold(error.argName)}: Got invalid value ${chalk.redBright(valueStr)}${ multilineValue ? '' : ' ' - }on ${chalk.bold( - `prisma.${this.children[0].name}`, - )}. Provided ${chalk.redBright( + }on ${chalk.bold(`prisma.${this.children[0].name}`)}. Provided ${chalk.redBright( getGraphQLType(error.providedValue), )}, expected ${expected}` } if (error.type === 'invalidNullArg') { - const forStr = - path.length === 1 && path[0] === error.name - ? '' - : ` for ${chalk.bold(`${path.join('.')}`)}` - const undefinedTip = ` Please use ${chalk.bold.greenBright( - 'undefined', - )} instead.` - return `Argument ${chalk.greenBright( - error.name, - )}${forStr} must not be ${chalk.bold('null')}.${undefinedTip}` + const forStr = path.length === 1 && path[0] === error.name ? '' : ` for ${chalk.bold(`${path.join('.')}`)}` + const undefinedTip = ` Please use ${chalk.bold.greenBright('undefined')} instead.` + return `Argument ${chalk.greenBright(error.name)}${forStr} must not be ${chalk.bold('null')}.${undefinedTip}` } if (error.type === 'missingArg') { - const forStr = - path.length === 1 && path[0] === error.missingName - ? '' - : ` for ${chalk.bold(`${path.join('.')}`)}` - return `Argument ${chalk.greenBright( - error.missingName, - )}${forStr} is missing.` + const forStr = path.length === 1 && path[0] === error.missingName ? '' : ` for ${chalk.bold(`${path.join('.')}`)}` + return `Argument ${chalk.greenBright(error.missingName)}${forStr} is missing.` } if (error.type === 'atLeastOne') { - const additional = minimal - ? '' - : ` Available args are listed in ${chalk.dim.green('green')}.` + const additional = minimal ? '' : ` Available args are listed in ${chalk.dim.green('green')}.` return `Argument ${chalk.bold(path.join('.'))} of type ${chalk.bold( error.inputType.name, )} needs ${chalk.greenBright('at least one')} argument.${additional}` @@ -544,14 +413,10 @@ ${errorMessages}${missingArgsLegend}\n` if (error.type === 'atMostOne') { const additional = minimal ? '' - : ` Please choose one. ${chalk.dim( - 'Available args:', - )} \n${stringifyInputType(error.inputType, true)}` + : ` Please choose one. ${chalk.dim('Available args:')} \n${stringifyInputType(error.inputType, true)}` return `Argument ${chalk.bold(path.join('.'))} of type ${chalk.bold( error.inputType.name, - )} needs ${chalk.greenBright( - 'exactly one', - )} argument, but you provided ${error.providedKeys + )} needs ${chalk.greenBright('exactly one')} argument, but you provided ${error.providedKeys .map((key) => chalk.redBright(key)) .join(' and ')}.${additional}` } @@ -628,9 +493,7 @@ export class Field { this.error = error this.schemaField = schemaField this.hasInvalidChild = children - ? children.some((child) => - Boolean(child.error || child.hasInvalidArg || child.hasInvalidChild), - ) + ? children.some((child) => Boolean(child.error || child.hasInvalidArg || child.hasInvalidChild)) : false this.hasInvalidArg = args ? args.hasInvalidArg : false } @@ -696,11 +559,7 @@ ${indent(this.children.map(String).join('\n'), tab)} // get all errors from args if (this.args) { - argErrors.push( - ...this.args - .collectErrors() - .map((e) => ({ ...e, path: [this.name, ...e.path] })), - ) + argErrors.push(...this.args.collectErrors().map((e) => ({ ...e, path: [this.name, ...e.path] }))) } return { @@ -715,9 +574,7 @@ export class Args { public readonly hasInvalidArg: boolean constructor(args: Arg[] = []) { this.args = args - this.hasInvalidArg = args - ? args.some((arg) => Boolean(arg.hasError)) - : false + this.hasInvalidArg = args ? args.some((arg) => Boolean(arg.hasError)) : false } get [Symbol.toStringTag]() { return 'Args' @@ -812,14 +669,7 @@ export class Arg { public isNullable: boolean public inputType?: DMMF.SchemaArgInputType - constructor({ - key, - value, - isEnum = false, - error, - schemaArg, - inputType, - }: ArgOptions) { + constructor({ key, value, isEnum = false, error, schemaArg, inputType }: ArgOptions) { this.inputType = inputType this.key = key this.value = value @@ -827,15 +677,11 @@ export class Arg { this.error = error this.schemaArg = schemaArg this.isNullable = - schemaArg?.inputTypes.reduce( - (isNullable) => isNullable && schemaArg.isNullable, - true, - ) || false + schemaArg?.inputTypes.reduce((isNullable) => isNullable && schemaArg.isNullable, true) || false this.hasError = Boolean(error) || (value instanceof Args ? value.hasInvalidArg : false) || - (Array.isArray(value) && - value.some((v) => (v instanceof Args ? v.hasInvalidArg : false))) + (Array.isArray(value) && value.some((v) => (v instanceof Args ? v.hasInvalidArg : false))) } get [Symbol.toStringTag]() { return 'Arg' @@ -912,28 +758,14 @@ ${indent(value.toString(), 2)} // collect errors of children if there are any if (this.value instanceof Args) { - errors.push( - ...this.value - .collectErrors() - .map((e) => ({ ...e, path: [this.key, ...e.path] })), - ) + errors.push(...this.value.collectErrors().map((e) => ({ ...e, path: [this.key, ...e.path] }))) } return errors } } -export type ArgValue = - | string - | boolean - | number - | undefined - | Args - | string[] - | boolean[] - | number[] - | Args[] - | null +export type ArgValue = string | boolean | number | undefined | Args | string[] | boolean[] | number[] | Args[] | null export interface DocumentInput { dmmf: DMMFClass @@ -942,12 +774,7 @@ export interface DocumentInput { select?: any } -export function makeDocument({ - dmmf, - rootTypeName, - rootField, - select, -}: DocumentInput): Document { +export function makeDocument({ dmmf, rootTypeName, rootField, select }: DocumentInput): Document { if (!select) { select = {} } @@ -962,12 +789,7 @@ export function makeDocument({ }, name: rootTypeName, } - const children = selectionToFields( - dmmf, - { [rootField]: select }, - fakeRootField, - [rootTypeName], - ) + const children = selectionToFields(dmmf, { [rootField]: select }, fakeRootField, [rootTypeName]) return new Document(rootTypeName, children) as any } @@ -984,9 +806,7 @@ export function selectionToFields( ): Field[] { const outputType = schemaField.outputType.type as DMMF.OutputType return Object.entries(selection).reduce((acc, [name, value]: any) => { - const field = outputType.fieldMap - ? outputType.fieldMap[name] - : outputType.fields.find((f) => f.name === name) + const field = outputType.fieldMap ? outputType.fieldMap[name] : outputType.fields.find((f) => f.name === name) if (!field) { // if the field name is incorrect, we ignore the args and child fields altogether @@ -1047,16 +867,13 @@ export function selectionToFields( maxNumFields: null, }, } - const argsWithoutIncludeAndSelect = - typeof value === 'object' ? omit(value, ['include', 'select']) : undefined + const argsWithoutIncludeAndSelect = typeof value === 'object' ? omit(value, ['include', 'select']) : undefined const args = argsWithoutIncludeAndSelect ? objectToArgs( argsWithoutIncludeAndSelect, transformedField, [], - typeof field === 'string' - ? undefined - : (field.outputType.type as DMMF.OutputType), + typeof field === 'string' ? undefined : (field.outputType.type as DMMF.OutputType), ) : undefined const isRelation = field.outputType.location === 'outputObjectTypes' @@ -1129,12 +946,9 @@ export function selectionToFields( modelName: fieldOutputType.name, outputType: fieldOutputType, providedName: invalidKey, - didYouMean: - getSuggestion(invalidKey, allowedKeys) || undefined, + didYouMean: getSuggestion(invalidKey, allowedKeys) || undefined, isInclude: true, - isIncludeScalar: fieldOutputType.fields.some( - (f) => f.name === invalidKey, - ), + isIncludeScalar: fieldOutputType.fields.some((f) => f.name === invalidKey), }, }), ], @@ -1191,9 +1005,7 @@ export function selectionToFields( } } // either use select or default selection, but not both at the same time - const defaultSelection = isRelation - ? getDefaultSelection(field.outputType.type as DMMF.OutputType) - : null + const defaultSelection = isRelation ? getDefaultSelection(field.outputType.type as DMMF.OutputType) : null let select = defaultSelection if (value) { @@ -1222,9 +1034,7 @@ export function selectionToFields( } const children = - select !== false && isRelation - ? selectionToFields(dmmf, select, field, [...path, name]) - : undefined + select !== false && isRelation ? selectionToFields(dmmf, select, field, [...path, name]) : undefined acc.push(new Field({ name, args, children, schemaField: field })) @@ -1244,10 +1054,7 @@ function getDefaultSelection(outputType: DMMF.OutputType) { const acc = Object.create(null) for (const f of outputType.fields) { - if ( - f.outputType.location === 'scalar' || - f.outputType.location === 'enumTypes' - ) { + if (f.outputType.location === 'scalar' || f.outputType.location === 'enumTypes') { acc[f.name] = true } else { // otherwise field is a relation. Only continue if it's an embedded type @@ -1289,11 +1096,7 @@ function getInvalidTypeArg( } // TODO: Refactor -function hasCorrectScalarType( - value: any, - arg: DMMF.SchemaArg, - inputType: DMMF.SchemaArgInputType, -): boolean { +function hasCorrectScalarType(value: any, arg: DMMF.SchemaArg, inputType: DMMF.SchemaArgInputType): boolean { const { type, isList } = inputType const expectedType = wrapWithList(stringifyGraphQLType(type), isList) const graphQLType = getGraphQLType(value, type) @@ -1326,17 +1129,11 @@ function hasCorrectScalarType( return true } - if ( - (graphQLType === 'Int' || graphQLType === 'Float') && - expectedType === 'Decimal' - ) { + if ((graphQLType === 'Int' || graphQLType === 'Float') && expectedType === 'Decimal') { return true } - if ( - (graphQLType === 'List' || graphQLType === 'List') && - expectedType === 'List' - ) { + if ((graphQLType === 'List' || graphQLType === 'List') && expectedType === 'List') { return true } @@ -1369,8 +1166,7 @@ function hasCorrectScalarType( if ( expectedType === 'List' && - (graphQLType === 'List' || - graphQLType === 'List') + (graphQLType === 'List' || graphQLType === 'List') ) { return true } @@ -1392,11 +1188,7 @@ function hasCorrectScalarType( // to match all strings which are valid decimals // from https://github.com/MikeMcl/decimal.js/blob/master/decimal.js#L115 - if ( - graphQLType === 'String' && - expectedType === 'Decimal' && - /^\-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i.test(value) - ) { + if (graphQLType === 'String' && expectedType === 'Decimal' && /^\-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i.test(value)) { return true } @@ -1443,11 +1235,7 @@ function valueToArg(key: string, value: any, arg: DMMF.SchemaArg): Arg | null { score += Math.log(e.path.length) if (e.error.type === 'missingArg') { - if ( - arg.inputType && - isInputArgType(arg.inputType.type) && - arg.inputType.type.name.includes('Unchecked') - ) { + if (arg.inputType && isInputArgType(arg.inputType.type) && arg.inputType.type.name.includes('Unchecked')) { score *= 2 } } @@ -1509,12 +1297,7 @@ function sum(n: number[]): number { * @param arg * @param inputType */ -function tryInferArgs( - key: string, - value: any, - arg: DMMF.SchemaArg, - inputType: DMMF.SchemaArgInputType, -): Arg | null { +function tryInferArgs(key: string, value: any, arg: DMMF.SchemaArg, inputType: DMMF.SchemaArgInputType): Arg | null { if (typeof value === 'undefined') { // the arg is undefined and not required - we're fine if (!arg.isRequired) { @@ -1542,8 +1325,7 @@ function tryInferArgs( if (value === null && !isNullable && !isRequired) { // we don't need to execute this ternery if not necessary const isAtLeastOne = isInputArgType(inputType.type) - ? inputType.type.constraints.minNumFields !== null && - inputType.type.constraints.minNumFields > 0 + ? inputType.type.constraints.minNumFields !== null && inputType.type.constraints.minNumFields > 0 : false if (!isAtLeastOne) { return new Arg({ @@ -1603,10 +1385,7 @@ function tryInferArgs( return new Arg({ key, - value: - val === null - ? null - : objectToArgs(val, inputType.type, arg.inputTypes), + value: val === null ? null : objectToArgs(val, inputType.type, arg.inputTypes), isEnum: inputType.location === 'enumTypes', error, inputType, @@ -1637,10 +1416,8 @@ function tryInferArgs( const argInputType = inputType.type as DMMF.InputType const hasAtLeastOneError = - typeof argInputType.constraints?.minNumFields === 'number' && - argInputType.constraints?.minNumFields > 0 - ? Array.isArray(value) && - value.some((v) => !v || Object.keys(cleanObject(v)).length === 0) + typeof argInputType.constraints?.minNumFields === 'number' && argInputType.constraints?.minNumFields > 0 + ? Array.isArray(value) && value.some((v) => !v || Object.keys(cleanObject(v)).length === 0) : false let err: AtLeastOneError | undefined | AtMostOneError = hasAtLeastOneError ? { @@ -1651,10 +1428,8 @@ function tryInferArgs( : undefined if (!err) { const hasOneOfError = - typeof argInputType.constraints?.maxNumFields === 'number' && - argInputType.constraints?.maxNumFields < 2 - ? Array.isArray(value) && - value.find((v) => !v || Object.keys(cleanObject(v)).length !== 1) + typeof argInputType.constraints?.maxNumFields === 'number' && argInputType.constraints?.maxNumFields < 2 + ? Array.isArray(value) && value.find((v) => !v || Object.keys(cleanObject(v)).length !== 1) : false if (hasOneOfError) { err = { @@ -1668,10 +1443,7 @@ function tryInferArgs( if (!Array.isArray(value)) { for (const nestedArgInputType of arg.inputTypes) { - const args = objectToArgs( - value, - nestedArgInputType.type as DMMF.InputType, - ) + const args = objectToArgs(value, nestedArgInputType.type as DMMF.InputType) if (args.collectErrors().length === 0) { return new Arg({ key, @@ -1702,9 +1474,7 @@ function tryInferArgs( }) } -export function isInputArgType( - argType: DMMF.ArgType, -): argType is DMMF.InputType { +export function isInputArgType(argType: DMMF.ArgType): argType is DMMF.InputType { if (typeof argType === 'string') { return false } @@ -1716,12 +1486,7 @@ export function isInputArgType( return true } -function scalarToArg( - key: string, - value: any, - arg: DMMF.SchemaArg, - inputType: DMMF.SchemaArgInputType, -): Arg { +function scalarToArg(key: string, value: any, arg: DMMF.SchemaArg, inputType: DMMF.SchemaArgInputType): Arg { if (hasCorrectScalarType(value, arg, inputType)) { return new Arg({ key, @@ -1747,16 +1512,10 @@ function objectToArgs( const objEntries = Object.entries(obj || {}) const entries = unionBy(objEntries, requiredArgs, (a) => a[0]) const argsList = entries.reduce((acc, [argName, value]: any) => { - const schemaArg = fieldMap - ? fieldMap[argName] - : args.find((a) => a.name === argName) + const schemaArg = fieldMap ? fieldMap[argName] : args.find((a) => a.name === argName) if (!schemaArg) { const didYouMeanField = - typeof value === 'boolean' && - outputType && - outputType.fields.some((f) => f.name === argName) - ? argName - : null + typeof value === 'boolean' && outputType && outputType.fields.some((f) => f.name === argName) ? argName : null acc.push( new Arg({ key: argName, @@ -1767,12 +1526,7 @@ function objectToArgs( providedValue: value, didYouMeanField, didYouMeanArg: - (!didYouMeanField && - getSuggestion(argName, [ - ...args.map((a) => a.name), - 'select', - ])) || - undefined, + (!didYouMeanField && getSuggestion(argName, [...args.map((a) => a.name), 'select'])) || undefined, originalType: inputType, possibilities, outputType, @@ -1794,16 +1548,10 @@ function objectToArgs( if ( (typeof inputType.constraints.minNumFields === 'number' && objEntries.length < inputType.constraints.minNumFields) || - argsList.find( - (arg) => - arg.error?.type === 'missingArg' || arg.error?.type === 'atLeastOne', - ) + argsList.find((arg) => arg.error?.type === 'missingArg' || arg.error?.type === 'atLeastOne') ) { const optionalMissingArgs = inputType.fields.filter( - (field) => - !field.isRequired && - obj && - (typeof obj[field.name] === 'undefined' || obj[field.name] === null), + (field) => !field.isRequired && obj && (typeof obj[field.name] === 'undefined' || obj[field.name] === null), ) argsList.push( ...optionalMissingArgs.map((arg) => { @@ -1859,12 +1607,7 @@ export interface MapScalarsOptions { } export function mapScalars({ field, data }: MapScalarsOptions): any { - if ( - !data || - typeof data !== 'object' || - !field.children || - !field.schemaField - ) { + if (!data || typeof data !== 'object' || !field.children || !field.schemaField) { return data } @@ -1886,10 +1629,7 @@ export function mapScalars({ field, data }: MapScalarsOptions): any { if (Array.isArray(data)) { for (const entry of data) { // in the very unlikely case, that a field is not there in the result, ignore it - if ( - typeof entry[child.name] !== 'undefined' && - entry[child.name] !== null - ) { + if (typeof entry[child.name] !== 'undefined' && entry[child.name] !== null) { // for scalar lists if (Array.isArray(entry[child.name])) { entry[child.name] = entry[child.name].map(deserializer) @@ -1900,10 +1640,7 @@ export function mapScalars({ field, data }: MapScalarsOptions): any { } } else { // same here, ignore it if it's undefined - if ( - typeof data[child.name] !== 'undefined' && - data[child.name] !== null - ) { + if (typeof data[child.name] !== 'undefined' && data[child.name] !== null) { // for scalar lists if (Array.isArray(data[child.name])) { data[child.name] = data[child.name].map(deserializer) @@ -1915,10 +1652,7 @@ export function mapScalars({ field, data }: MapScalarsOptions): any { } } - if ( - child.schemaField && - child.schemaField.outputType.location === 'outputObjectTypes' - ) { + if (child.schemaField && child.schemaField.outputType.location === 'outputObjectTypes') { if (Array.isArray(data)) { for (const entry of data) { mapScalars({ field: child, data: entry[child.name] }) @@ -1939,17 +1673,13 @@ export function getField(document: Document, path: string[]): Field { let pointer = document.children.find((c) => c.name === firstElement) if (!pointer) { - throw new Error( - `Could not find field ${firstElement} in document ${document}`, - ) + throw new Error(`Could not find field ${firstElement} in document ${document}`) } while (todo.length > 0) { const key = todo.shift() if (!pointer!.children) { - throw new Error( - `Can't get children for field ${pointer} with child ${key}`, - ) + throw new Error(`Can't get children for field ${pointer} with child ${key}`) } const child = pointer!.children.find((c) => c.name === key) if (!child) { diff --git a/packages/client/src/runtime/utils/common.ts b/packages/client/src/runtime/utils/common.ts index be59e71e5fe7..f767727451ea 100644 --- a/packages/client/src/runtime/utils/common.ts +++ b/packages/client/src/runtime/utils/common.ts @@ -9,10 +9,7 @@ export interface Dictionary { [key: string]: T } -export const keyBy: (collection: T[], prop: string) => Dictionary = ( - collection, - prop, -) => { +export const keyBy: (collection: T[], prop: string) => Dictionary = (collection, prop) => { const acc = {} for (const obj of collection) { @@ -22,11 +19,11 @@ export const keyBy: (collection: T[], prop: string) => Dictionary = ( return acc } -export const keyBy2: ( - collection1: T[], - collection2: T[], - prop: string, -) => Dictionary = (collection1, collection2, prop) => { +export const keyBy2: (collection1: T[], collection2: T[], prop: string) => Dictionary = ( + collection1, + collection2, + prop, +) => { const acc = {} for (const obj of collection1) { @@ -106,9 +103,7 @@ export const JSTypeToGraphQLType = { object: 'Json', } -export function stringifyGraphQLType( - type: string | DMMF.InputType | DMMF.SchemaEnum, -) { +export function stringifyGraphQLType(type: string | DMMF.InputType | DMMF.SchemaEnum) { if (typeof type === 'string') { return type } @@ -127,13 +122,9 @@ export function wrapWithList(str: string, isList: boolean) { const RFC_3339_REGEX = /^(\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60))(\.\d{1,})?(([Z])|([+|-]([01][0-9]|2[0-3]):[0-5][0-9]))$/ -const UUID_REGEX = - /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i -export function getGraphQLType( - value: any, - potentialType?: string | DMMF.SchemaEnum | DMMF.InputType, -): string { +export function getGraphQLType(value: any, potentialType?: string | DMMF.SchemaEnum | DMMF.InputType): string { if (value === null) { return 'null' } @@ -205,10 +196,7 @@ export function graphQLToJSType(gql: string) { return GraphQLScalarToJSTypeTable[gql] } -export function getSuggestion( - str: string, - possibilities: string[], -): string | null { +export function getSuggestion(str: string, possibilities: string[]): string | null { const bestMatch = possibilities.reduce<{ distance: number str: string | null @@ -226,10 +214,7 @@ export function getSuggestion( }, { // heuristic to be not too strict, but allow some big mistakes (<= ~ 5) - distance: Math.min( - Math.floor(str.length) * 1.1, - ...possibilities.map((p) => p.length * 3), - ), + distance: Math.min(Math.floor(str.length) * 1.1, ...possibilities.map((p) => p.length * 3)), str: null, }, ) @@ -237,32 +222,22 @@ export function getSuggestion( return bestMatch.str } -export function stringifyInputType( - input: string | DMMF.InputType | DMMF.SchemaEnum, - greenKeys = false, -): string { +export function stringifyInputType(input: string | DMMF.InputType | DMMF.SchemaEnum, greenKeys = false): string { if (typeof input === 'string') { return input } if ((input as DMMF.SchemaEnum).values) { - return `enum ${input.name} {\n${indent( - (input as DMMF.SchemaEnum).values.join(', '), - 2, - )}\n}` + return `enum ${input.name} {\n${indent((input as DMMF.SchemaEnum).values.join(', '), 2)}\n}` } else { const body = indent( (input as DMMF.InputType).fields // TS doesn't discriminate based on existence of fields properly .map((arg) => { const key = `${arg.name}` - const str = `${greenKeys ? chalk.green(key) : key}${ - arg.isRequired ? '' : '?' - }: ${chalk.white( + const str = `${greenKeys ? chalk.green(key) : key}${arg.isRequired ? '' : '?'}: ${chalk.white( arg.inputTypes .map((argType) => { return wrapWithList( - argIsInputType(argType.type) - ? argType.type.name - : stringifyGraphQLType(argType.type), + argIsInputType(argType.type) ? argType.type.name : stringifyGraphQLType(argType.type), argType.isList, ) }) @@ -277,9 +252,7 @@ export function stringifyInputType( .join('\n'), 2, ) - return `${chalk.dim('type')} ${chalk.bold.dim(input.name)} ${chalk.dim( - '{', - )}\n${body}\n${chalk.dim('}')}` + return `${chalk.dim('type')} ${chalk.bold.dim(input.name)} ${chalk.dim('{')}\n${body}\n${chalk.dim('}')}` } } @@ -291,9 +264,7 @@ export function argIsInputType(arg: DMMF.ArgType): arg is DMMF.InputType { return true } -export function getInputTypeName( - input: string | DMMF.InputType | DMMF.SchemaField | DMMF.SchemaEnum, -) { +export function getInputTypeName(input: string | DMMF.InputType | DMMF.SchemaField | DMMF.SchemaEnum) { if (typeof input === 'string') { if (input === 'Null') { return 'null' @@ -304,9 +275,7 @@ export function getInputTypeName( return input.name } -export function getOutputTypeName( - input: string | DMMF.OutputType | DMMF.SchemaField | DMMF.SchemaEnum, -) { +export function getOutputTypeName(input: string | DMMF.OutputType | DMMF.SchemaField | DMMF.SchemaEnum) { if (typeof input === 'string') { return input } @@ -338,9 +307,7 @@ export function inputTypeToJson( const showDeepType = isRequired && inputType.fields.every( - (arg) => - arg.inputTypes[0].location === 'inputObjectTypes' || - arg.inputTypes[1]?.location === 'inputObjectTypes', + (arg) => arg.inputTypes[0].location === 'inputObjectTypes' || arg.inputTypes[1]?.location === 'inputObjectTypes', ) if (nameOnly) { @@ -351,15 +318,9 @@ export function inputTypeToJson( let str = '' if (!showDeepType && !curr.isRequired) { - str = curr.inputTypes - .map((argType) => getInputTypeName(argType.type)) - .join(' | ') + str = curr.inputTypes.map((argType) => getInputTypeName(argType.type)).join(' | ') } else { - str = curr.inputTypes - .map((argInputType) => - inputTypeToJson(argInputType.type, curr.isRequired, true), - ) - .join(' | ') + str = curr.inputTypes.map((argInputType) => inputTypeToJson(argInputType.type, curr.isRequired, true)).join(' | ') } acc[curr.name + (curr.isRequired ? '' : '?')] = str @@ -407,11 +368,7 @@ export function destroyCircular(from, seen: any[] = []) { return to } -export function unionBy( - arr1: T[], - arr2: T[], - iteratee: (element: T) => string | number, -): T[] { +export function unionBy(arr1: T[], arr2: T[], iteratee: (element: T) => string | number): T[] { const map = {} for (const element of arr1) { @@ -428,10 +385,7 @@ export function unionBy( return Object.values(map) } -export function uniqBy( - arr: T[], - iteratee: (element: T) => string | number, -): T[] { +export function uniqBy(arr: T[], iteratee: (element: T) => string | number): T[] { const map = {} for (const element of arr) { @@ -459,10 +413,6 @@ export function isGroupByOutputName(type: string): boolean { export function isSchemaEnum(type: any): type is DMMF.SchemaEnum { return ( - typeof type === 'object' && - type.name && - typeof type.name === 'string' && - type.values && - Array.isArray(type.values) + typeof type === 'object' && type.name && typeof type.name === 'string' && type.values && Array.isArray(type.values) ) } diff --git a/packages/client/src/runtime/utils/deep-extend.ts b/packages/client/src/runtime/utils/deep-extend.ts index 9f5d0a3f0d79..d4c636bbc408 100644 --- a/packages/client/src/runtime/utils/deep-extend.ts +++ b/packages/client/src/runtime/utils/deep-extend.ts @@ -30,9 +30,7 @@ /* tslint:disable */ function isSpecificValue(val) { - return val instanceof Buffer || val instanceof Date || val instanceof RegExp - ? true - : false + return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false } function cloneSpecificValue(val) { @@ -127,11 +125,7 @@ export const deepExtend = function (target, ...args) { continue // overwrite by new value if source isn't object or array - } else if ( - typeof src !== 'object' || - src === null || - Array.isArray(src) - ) { + } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { target[key] = deepExtend({}, val) continue diff --git a/packages/client/src/runtime/utils/deep-set.ts b/packages/client/src/runtime/utils/deep-set.ts index 005fd18851ed..b8f769e389f7 100644 --- a/packages/client/src/runtime/utils/deep-set.ts +++ b/packages/client/src/runtime/utils/deep-set.ts @@ -9,8 +9,7 @@ const keys = (ks: string | string[]) => (Array.isArray(ks) ? ks : ks.split('.')) // returning the current value in each iteration. // if at any point the value for the current key does not exist, // return the default value -export const deepGet = (o, kp: string[]) => - keys(kp).reduce((o, k) => o && o[k], o) +export const deepGet = (o, kp: string[]) => keys(kp).reduce((o, k) => o && o[k], o) // traverse the set of keys right to left, // returning a new object containing both properties from the object @@ -24,7 +23,4 @@ export const deepGet = (o, kp: string[]) => // 2. b = Object.assign({}, { b: { c: 1 } }, { b: c }) // 3. returned = Object.assign({}, { a: { b: { c: 1 } } }, { a: b }) export const deepSet = (o: any, kp: string | string[], v: any) => - keys(kp).reduceRight( - (v, k, i, ks) => Object.assign({}, deepGet(o, ks.slice(0, i)), { [k]: v }), - v, - ) + keys(kp).reduceRight((v, k, i, ks) => Object.assign({}, deepGet(o, ks.slice(0, i)), { [k]: v }), v) diff --git a/packages/client/src/runtime/utils/filterObject.ts b/packages/client/src/runtime/utils/filterObject.ts index ef4d380e2c7c..63005e15357b 100644 --- a/packages/client/src/runtime/utils/filterObject.ts +++ b/packages/client/src/runtime/utils/filterObject.ts @@ -1,9 +1,5 @@ export function filterObject(obj, cb) { - if ( - !obj || - typeof obj !== 'object' || - typeof obj.hasOwnProperty !== 'function' - ) { + if (!obj || typeof obj !== 'object' || typeof obj.hasOwnProperty !== 'function') { return obj } const newObj = {} diff --git a/packages/client/src/runtime/utils/find.ts b/packages/client/src/runtime/utils/find.ts index 725f1523baa4..2e084f043ff4 100644 --- a/packages/client/src/runtime/utils/find.ts +++ b/packages/client/src/runtime/utils/find.ts @@ -20,13 +20,7 @@ type Handler = (base: string, item: string, type: ItemType) => boolean | string * @returns */ function direntToType(dirent: fs.Dirent | fs.Stats) { - return dirent.isFile() - ? 'f' - : dirent.isDirectory() - ? 'd' - : dirent.isSymbolicLink() - ? 'l' - : undefined + return dirent.isFile() ? 'f' : dirent.isDirectory() ? 'd' : dirent.isSymbolicLink() ? 'l' : undefined } /** @@ -235,16 +229,7 @@ export async function findAsync( // dive within the directory tree if (deep.includes(itemType as any)) { // we recurse and continue mutating `found` - await findAsync( - itemPath, - match, - types, - deep, - limit, - handler, - found, - seen, - ) + await findAsync(itemPath, match, types, deep, limit, handler, found, seen) } } } catch {} diff --git a/packages/client/src/runtime/utils/getClientEngineType.ts b/packages/client/src/runtime/utils/getClientEngineType.ts index 2ac85a444346..83e7ae7d76a4 100644 --- a/packages/client/src/runtime/utils/getClientEngineType.ts +++ b/packages/client/src/runtime/utils/getClientEngineType.ts @@ -7,18 +7,14 @@ export enum ClientEngineType { } export const DEFAULT_CLIENT_ENGINE_TYPE = ClientEngineType.Library -export function getClientEngineType( - generatorConfig?: GeneratorConfig, -): ClientEngineType { +export function getClientEngineType(generatorConfig?: GeneratorConfig): ClientEngineType { const engineTypeFromEnvVar = getEngineTypeFromEnvVar() if (engineTypeFromEnvVar) return engineTypeFromEnvVar if (generatorConfig?.config.engineType === ClientEngineType.Library) { return ClientEngineType.Library } else if (generatorConfig?.config.engineType === ClientEngineType.Binary) { return ClientEngineType.Binary - } else if ( - generatorConfig?.config.engineType === ClientEngineType.DataProxy - ) { + } else if (generatorConfig?.config.engineType === ClientEngineType.DataProxy) { return ClientEngineType.DataProxy } else { return DEFAULT_CLIENT_ENGINE_TYPE diff --git a/packages/client/src/runtime/utils/isObject.ts b/packages/client/src/runtime/utils/isObject.ts index 35f6d7ddf0bf..0de236ce812f 100644 --- a/packages/client/src/runtime/utils/isObject.ts +++ b/packages/client/src/runtime/utils/isObject.ts @@ -11,9 +11,5 @@ const notReallyObjects = { } export function isObject(value: any): boolean { - return ( - value && - typeof value === 'object' && - !notReallyObjects[Object.prototype.toString.call(value)] - ) + return value && typeof value === 'object' && !notReallyObjects[Object.prototype.toString.call(value)] } diff --git a/packages/client/src/runtime/utils/mssqlPreparedStatement.ts b/packages/client/src/runtime/utils/mssqlPreparedStatement.ts index 6ac16f6be955..acded77fc553 100644 --- a/packages/client/src/runtime/utils/mssqlPreparedStatement.ts +++ b/packages/client/src/runtime/utils/mssqlPreparedStatement.ts @@ -1,6 +1,4 @@ // Generate something like: SELECT * FROM User WHERE name = @P1 AND email = @P2 ... -export const mssqlPreparedStatement = ( - template: ReadonlyArray | TemplateStringsArray, -) => { +export const mssqlPreparedStatement = (template: ReadonlyArray | TemplateStringsArray) => { return template.reduce((acc, str, idx) => `${acc}@P${idx}${str}`) } diff --git a/packages/client/src/runtime/utils/omit.ts b/packages/client/src/runtime/utils/omit.ts index bd8ba91591bf..0a4b84a077c2 100644 --- a/packages/client/src/runtime/utils/omit.ts +++ b/packages/client/src/runtime/utils/omit.ts @@ -3,17 +3,11 @@ export type Exclude = T extends U ? never : T export type Omit = { [P in Exclude]: T[P] } -export function omit( - object: T, - path: K | K[], -): Omit { +export function omit(object: T, path: K | K[]): Omit { const result: any = {} const paths = Array.isArray(path) ? path : [path] for (const key in object) { - if ( - Object.hasOwnProperty.call(object, key) && - !paths.includes(key as any) - ) { + if (Object.hasOwnProperty.call(object, key) && !paths.includes(key as any)) { result[key] = object[key] } } diff --git a/packages/client/src/runtime/utils/printDatasources.ts b/packages/client/src/runtime/utils/printDatasources.ts index ea2e4ed875ee..3bec008b56f1 100644 --- a/packages/client/src/runtime/utils/printDatasources.ts +++ b/packages/client/src/runtime/utils/printDatasources.ts @@ -1,12 +1,6 @@ import type { Dictionary } from './common' -export type ConnectorType = - | 'mysql' - | 'mongodb' - | 'sqlite' - | 'postgresql' - | 'sqlserver' - | 'jdbc:sqlserver' +export type ConnectorType = 'mysql' | 'mongodb' | 'sqlite' | 'postgresql' | 'sqlserver' | 'jdbc:sqlserver' export interface GeneratorConfig { name: string diff --git a/packages/client/src/runtime/utils/printJsonErrors.ts b/packages/client/src/runtime/utils/printJsonErrors.ts index cb7031fd6696..ebcf2760235c 100644 --- a/packages/client/src/runtime/utils/printJsonErrors.ts +++ b/packages/client/src/runtime/utils/printJsonErrors.ts @@ -18,12 +18,7 @@ export type PrintJsonWithErrorsArgs = { missingItems: MissingItem[] } -export function printJsonWithErrors({ - ast, - keyPaths, - valuePaths, - missingItems, -}: PrintJsonWithErrorsArgs) { +export function printJsonWithErrors({ ast, keyPaths, valuePaths, missingItems }: PrintJsonWithErrorsArgs) { let obj = ast for (const { path, type } of missingItems) { obj = deepSet(obj, path, type) @@ -47,21 +42,13 @@ export function printJsonWithErrors({ const isRequiredStr = missingItem.isRequired ? '' : '?' const prefix = missingItem.isRequired ? '+' : '?' const color = missingItem.isRequired ? chalk.greenBright : chalk.green - let output = color( - prefixLines( - key + isRequiredStr + ': ' + valueStr + eol, - indent, - prefix, - ), - ) + let output = color(prefixLines(key + isRequiredStr + ': ' + valueStr + eol, indent, prefix)) if (!missingItem.isRequired) { output = chalk.dim(output) } return output } else { - const isOnMissingItemPath = missingItems.some((item) => - dottedPath.startsWith(item.path), - ) + const isOnMissingItemPath = missingItems.some((item) => dottedPath.startsWith(item.path)) const isOptional = key[key.length - 2] === '?' if (isOptional) { key = key.slice(1, key.length - 1) @@ -69,9 +56,7 @@ export function printJsonWithErrors({ if (isOptional && typeof value === 'object' && value !== null) { valueStr = valueStr .split('\n') - .map((line, index, arr) => - index === arr.length - 1 ? line + DIM_TOKEN : line, - ) + .map((line, index, arr) => (index === arr.length - 1 ? line + DIM_TOKEN : line)) .join('\n') } if (isOnMissingItemPath && typeof value === 'string') { @@ -80,23 +65,14 @@ export function printJsonWithErrors({ valueStr = chalk.bold(valueStr) } } - if ( - (typeof value !== 'object' || value === null) && - !valueError && - !isOnMissingItemPath - ) { + if ((typeof value !== 'object' || value === null) && !valueError && !isOnMissingItemPath) { valueStr = chalk.dim(valueStr) } const keyStr = keyError ? chalk.redBright(key) : key valueStr = valueError ? chalk.redBright(valueStr) : valueStr // valueStr can be multiple lines if it's an object - let output = - indent + - keyStr + - ': ' + - valueStr + - (isOnMissingItemPath ? eol : chalk.dim(eol)) + let output = indent + keyStr + ': ' + valueStr + (isOnMissingItemPath ? eol : chalk.dim(eol)) // if there is an error, add the scribble lines // 3 options: @@ -106,19 +82,11 @@ export function printJsonWithErrors({ if (keyError || valueError) { const lines = output.split('\n') const keyLength = String(key).length - const keyScribbles = keyError - ? chalk.redBright('~'.repeat(keyLength)) - : ' '.repeat(keyLength) - - const valueLength = valueError - ? getValueLength(indent, key, value, stringifiedValue) - : 0 - const hideValueScribbles = Boolean( - valueError && typeof value === 'object' && value !== null, - ) - const valueScribbles = valueError - ? ' ' + chalk.redBright('~'.repeat(valueLength)) - : '' + const keyScribbles = keyError ? chalk.redBright('~'.repeat(keyLength)) : ' '.repeat(keyLength) + + const valueLength = valueError ? getValueLength(indent, key, value, stringifiedValue) : 0 + const hideValueScribbles = Boolean(valueError && typeof value === 'object' && value !== null) + const valueScribbles = valueError ? ' ' + chalk.redBright('~'.repeat(valueLength)) : '' // Either insert both keyScribles and valueScribbles in one line if (keyScribbles && keyScribbles.length > 0 && !hideValueScribbles) { @@ -127,11 +95,7 @@ export function printJsonWithErrors({ // or the valueScribbles for a multiline string if (keyScribbles && keyScribbles.length > 0 && hideValueScribbles) { - lines.splice( - lines.length - 1, - 0, - indent.slice(0, indent.length - 2) + valueScribbles, - ) + lines.splice(lines.length - 1, 0, indent.slice(0, indent.length - 2) + valueScribbles) } output = lines.join('\n') @@ -142,12 +106,7 @@ export function printJsonWithErrors({ }) } -function getValueLength( - indent: string, - key: string, - value: any, - stringifiedValue: string, -) { +function getValueLength(indent: string, key: string, value: any, stringifiedValue: string) { if (value === null) { return 4 } @@ -156,29 +115,21 @@ function getValueLength( } if (typeof value === 'object') { - return Math.abs( - getLongestLine(`${key}: ${stripAnsi(stringifiedValue)}`) - indent.length, - ) + return Math.abs(getLongestLine(`${key}: ${stripAnsi(stringifiedValue)}`) - indent.length) } return String(value).length } function getLongestLine(str: string): number { - return str - .split('\n') - .reduce((max, curr) => (curr.length > max ? curr.length : max), 0) + return str.split('\n').reduce((max, curr) => (curr.length > max ? curr.length : max), 0) } function prefixLines(str: string, indent: string, prefix: string): string { return str .split('\n') .map((line, index, arr) => - index === 0 - ? prefix + indent.slice(1) + line - : index < arr.length - 1 - ? prefix + line.slice(1) - : line, + index === 0 ? prefix + indent.slice(1) + line : index < arr.length - 1 ? prefix + line.slice(1) : line, ) .map((line) => { // we need to use a special token to "mark" a line a "to be dimmed", as chalk (or rather ansi) doesn't allow nesting of dimmed & colored content diff --git a/packages/client/src/runtime/utils/printStack.ts b/packages/client/src/runtime/utils/printStack.ts index 8e0ea8f519a4..87844724e99e 100644 --- a/packages/client/src/runtime/utils/printStack.ts +++ b/packages/client/src/runtime/utils/printStack.ts @@ -88,17 +88,9 @@ function parseStack({ ) }) - if ( - process.env.NODE_ENV !== 'production' && - trace && - trace.file && - trace.lineNumber && - trace.column - ) { + if (process.env.NODE_ENV !== 'production' && trace && trace.file && trace.lineNumber && trace.column) { const lineNumber = trace.lineNumber - const printedFileName = renderPathRelative - ? require('path').relative(process.cwd(), trace.file) - : trace.file + const printedFileName = renderPathRelative ? require('path').relative(process.cwd(), trace.file) : trace.file const start = Math.max(0, lineNumber - 4) const fs = require('fs') @@ -113,56 +105,34 @@ function parseStack({ params.callsiteStr = ':' } else { // Why even all this effort? Because if a user calls the client instance "db", we want to be able to also say "db.user.findMany" - const prismaClientRegex = - /(\S+(create|createMany|updateMany|deleteMany|update|delete|findMany|findUnique)\()/ + const prismaClientRegex = /(\S+(create|createMany|updateMany|deleteMany|update|delete|findMany|findUnique)\()/ const match = prismaClientRegex.exec(theLine) if (!match) { return params } params.functionName = `${match[1]})` // only add this, if the line matches - params.callsiteStr = ` in\n${chalk.underline( - `${printedFileName}:${trace.lineNumber}:${trace.column}`, - )}` + params.callsiteStr = ` in\n${chalk.underline(`${printedFileName}:${trace.lineNumber}:${trace.column}`)}` const slicePoint = theLine.indexOf('{') const linesToHighlight = lines .map((l, i, all) => - !onUs && i === all.length - 1 - ? l.slice(0, slicePoint > -1 ? slicePoint : l.length - 1) - : l, + !onUs && i === all.length - 1 ? l.slice(0, slicePoint > -1 ? slicePoint : l.length - 1) : l, ) .join('\n') - const highlightedLines = showColors - ? highlightTS(linesToHighlight).split('\n') - : linesToHighlight.split('\n') + const highlightedLines = showColors ? highlightTS(linesToHighlight).split('\n') : linesToHighlight.split('\n') params.prevLines = '\n' + highlightedLines - .map( - (l, i) => - chalk.grey( - renderN(i + start + 1, lineNumber + start + 1) + ' ', - ) + - chalk.reset() + - l, - ) - .map((l, i, arr) => - i === arr.length - 1 - ? `${chalk.red.bold('ā†’')} ${chalk.dim(l)}` - : chalk.dim(' ' + l), - ) + .map((l, i) => chalk.grey(renderN(i + start + 1, lineNumber + start + 1) + ' ') + chalk.reset() + l) + .map((l, i, arr) => (i === arr.length - 1 ? `${chalk.red.bold('ā†’')} ${chalk.dim(l)}` : chalk.dim(' ' + l))) .join('\n') if (!match && !isValidationError) { params.prevLines += '\n\n' } params.afterLines = ')' - params.indentValue = - String(lineNumber + start + 1).length + - getIndent(theLine) + - 1 + - (match ? 2 : 0) + params.indentValue = String(lineNumber + start + 1).length + getIndent(theLine) + 1 + (match ? 2 : 0) } } } @@ -170,25 +140,12 @@ function parseStack({ } export const printStack = (args: ErrorArgs): PrintStackResult => { - const { - callsiteStr, - prevLines, - functionName, - afterLines, - indentValue, - lastErrorHeight, - } = parseStack(args) + const { callsiteStr, prevLines, functionName, afterLines, indentValue, lastErrorHeight } = parseStack(args) const introText = args.onUs - ? chalk.red(`Oops, an unknown error occured! This is ${chalk.bold( - 'on us', - )}, you did nothing wrong. -It occured in the ${chalk.bold( - `\`${functionName}\``, - )} invocation${callsiteStr}`) - : chalk.red( - `Invalid ${chalk.bold(`\`${functionName}\``)} invocation${callsiteStr}`, - ) + ? chalk.red(`Oops, an unknown error occured! This is ${chalk.bold('on us')}, you did nothing wrong. +It occured in the ${chalk.bold(`\`${functionName}\``)} invocation${callsiteStr}`) + : chalk.red(`Invalid ${chalk.bold(`\`${functionName}\``)} invocation${callsiteStr}`) const stackStr = `\n${introText} ${prevLines}${chalk.reset()}` diff --git a/packages/client/src/runtime/utils/rejectOnNotFound.ts b/packages/client/src/runtime/utils/rejectOnNotFound.ts index 23c8057744db..30c5e63aced8 100644 --- a/packages/client/src/runtime/utils/rejectOnNotFound.ts +++ b/packages/client/src/runtime/utils/rejectOnNotFound.ts @@ -29,21 +29,12 @@ export function getRejectOnNotFound( clientInstance?: InstanceRejectOnNotFound, ): RejectOnNotFound { let rejectOnNotFound: RejectOnNotFound - if ( - args && - typeof args === 'object' && - 'rejectOnNotFound' in args && - args['rejectOnNotFound'] !== undefined - ) { + if (args && typeof args === 'object' && 'rejectOnNotFound' in args && args['rejectOnNotFound'] !== undefined) { rejectOnNotFound = args['rejectOnNotFound'] delete args['rejectOnNotFound'] } else if (typeof clientInstance === 'boolean') { rejectOnNotFound = clientInstance - } else if ( - clientInstance && - typeof clientInstance === 'object' && - action in clientInstance - ) { + } else if (clientInstance && typeof clientInstance === 'object' && action in clientInstance) { const rejectPerOperation = clientInstance[action] if (rejectPerOperation && typeof rejectPerOperation === 'object') { if (modelName in rejectPerOperation) { @@ -51,12 +42,7 @@ export function getRejectOnNotFound( } return undefined } - rejectOnNotFound = getRejectOnNotFound( - action, - modelName, - args, - rejectPerOperation, - ) + rejectOnNotFound = getRejectOnNotFound(action, modelName, args, rejectPerOperation) } else if (typeof clientInstance === 'function') { rejectOnNotFound = clientInstance } else { diff --git a/packages/client/src/runtime/utils/stringifyObject.ts b/packages/client/src/runtime/utils/stringifyObject.ts index 3b0f1220d918..6d5fe01fb574 100644 --- a/packages/client/src/runtime/utils/stringifyObject.ts +++ b/packages/client/src/runtime/utils/stringifyObject.ts @@ -1,8 +1,7 @@ 'use strict' const isRegexp = require('is-regexp') const isObj = require('is-obj') -const getOwnEnumPropSymbols = - require('get-own-enumerable-property-symbols').default +const getOwnEnumPropSymbols = require('get-own-enumerable-property-symbols').default // Fork of https://github.com/yeoman/stringify-object/blob/master/index.js // with possibility to overwrite the whole key-value pair (options.transformLine) @@ -48,10 +47,7 @@ const stringifyObject = (input, options?: any, pad?: any) => { } return string - .replace( - new RegExp(tokens.newLine + '|' + tokens.newLineOrSpace, 'g'), - '\n', - ) + .replace(new RegExp(tokens.newLine + '|' + tokens.newLineOrSpace, 'g'), '\n') .replace(new RegExp(tokens.pad, 'g'), pad) .replace(new RegExp(tokens.indent, 'g'), pad + options.indent) } @@ -92,15 +88,9 @@ const stringifyObject = (input, options?: any, pad?: any) => { tokens.newLine + input .map((el, i) => { - const eol = - input.length - 1 === i - ? tokens.newLine - : ',' + tokens.newLineOrSpace - - let value = stringifyObject(el, options, pad + options.indent, [ - ...path, - i, - ] as any) + const eol = input.length - 1 === i ? tokens.newLine : ',' + tokens.newLineOrSpace + + let value = stringifyObject(el, options, pad + options.indent, [...path, i] as any) if (options.transformValue) { value = options.transformValue(input, i, value) } @@ -134,23 +124,12 @@ const stringifyObject = (input, options?: any, pad?: any) => { tokens.newLine + objKeys .map((el, i) => { - const eol = - objKeys.length - 1 === i - ? tokens.newLine - : ',' + tokens.newLineOrSpace + const eol = objKeys.length - 1 === i ? tokens.newLine : ',' + tokens.newLineOrSpace const isSymbol = typeof el === 'symbol' const isClassic = !isSymbol && /^[a-z$_][a-z$_0-9]*$/i.test(el) - const key = - isSymbol || isClassic - ? el - : stringifyObject(el, options, undefined, [...path, el] as any) - - let value = stringifyObject( - input[el], - options, - pad + options.indent, - [...path, el] as any, - ) + const key = isSymbol || isClassic ? el : stringifyObject(el, options, undefined, [...path, el] as any) + + let value = stringifyObject(input[el], options, pad + options.indent, [...path, el] as any) if (options.transformValue) { value = options.transformValue(input, el, value) } @@ -181,9 +160,7 @@ const stringifyObject = (input, options?: any, pad?: any) => { return expandWhiteSpace(ret) } - input = String(input).replace(/[\r\n]/g, (x) => - x === '\n' ? '\\n' : '\\r', - ) + input = String(input).replace(/[\r\n]/g, (x) => (x === '\n' ? '\\n' : '\\r')) if (options.singleQuotes === false) { input = input.replace(/"/g, '\\"') diff --git a/packages/client/src/runtime/utils/validatePrismaClientOptions.ts b/packages/client/src/runtime/utils/validatePrismaClientOptions.ts index 83688d6ae4b6..491545c2a747 100644 --- a/packages/client/src/runtime/utils/validatePrismaClientOptions.ts +++ b/packages/client/src/runtime/utils/validatePrismaClientOptions.ts @@ -1,19 +1,9 @@ import { isError } from '@prisma/sdk' import leven from 'js-levenshtein' -import type { - ErrorFormat, - LogLevel, - PrismaClientOptions, -} from '../getPrismaClient' +import type { ErrorFormat, LogLevel, PrismaClientOptions } from '../getPrismaClient' import { PrismaClientConstructorValidationError } from '../query' -const knownProperties = [ - 'datasources', - 'errorFormat', - 'log', - '__internal', - 'rejectOnNotFound', -] +const knownProperties = ['datasources', 'errorFormat', 'log', '__internal', 'rejectOnNotFound'] const errorFormats: ErrorFormat[] = ['pretty', 'colorless', 'minimal'] const logLevels: LogLevel[] = ['info', 'query', 'warn', 'error'] @@ -24,26 +14,20 @@ const validators = { } if (typeof options !== 'object' || Array.isArray(options)) { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - options, - )} for "datasources" provided to PrismaClient constructor`, + `Invalid value ${JSON.stringify(options)} for "datasources" provided to PrismaClient constructor`, ) } for (const [key, value] of Object.entries(options)) { if (!datasourceNames.includes(key)) { - const didYouMean = - getDidYouMean(key, datasourceNames) || - `Available datasources: ${datasourceNames.join(', ')}` + const didYouMean = getDidYouMean(key, datasourceNames) || `Available datasources: ${datasourceNames.join(', ')}` throw new PrismaClientConstructorValidationError( `Unknown datasource ${key} provided to PrismaClient constructor.${didYouMean}`, ) } if (typeof value !== 'object' || Array.isArray(value)) { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - options, - )} for datasource "${key}" provided to PrismaClient constructor. + `Invalid value ${JSON.stringify(options)} for datasource "${key}" provided to PrismaClient constructor. It should have this form: { url: "CONNECTION_STRING" }`, ) } @@ -51,17 +35,13 @@ It should have this form: { url: "CONNECTION_STRING" }`, for (const [key1, value1] of Object.entries(value)) { if (key1 !== 'url') { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - options, - )} for datasource "${key}" provided to PrismaClient constructor. + `Invalid value ${JSON.stringify(options)} for datasource "${key}" provided to PrismaClient constructor. It should have this form: { url: "CONNECTION_STRING" }`, ) } if (typeof value1 !== 'string') { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - value1, - )} for datasource "${key}" provided to PrismaClient constructor. + `Invalid value ${JSON.stringify(value1)} for datasource "${key}" provided to PrismaClient constructor. It should have this form: { url: "CONNECTION_STRING" }`, ) } @@ -75,9 +55,7 @@ It should have this form: { url: "CONNECTION_STRING" }`, } if (typeof options !== 'string') { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - options, - )} for "errorFormat" provided to PrismaClient constructor.`, + `Invalid value ${JSON.stringify(options)} for "errorFormat" provided to PrismaClient constructor.`, ) } if (!errorFormats.includes(options as ErrorFormat)) { @@ -93,9 +71,7 @@ It should have this form: { url: "CONNECTION_STRING" }`, } if (!Array.isArray(options)) { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - options, - )} for "log" provided to PrismaClient constructor.`, + `Invalid value ${JSON.stringify(options)} for "log" provided to PrismaClient constructor.`, ) } @@ -145,27 +121,17 @@ It should have this form: { url: "CONNECTION_STRING" }`, if (!value) { return } - const knownKeys = [ - 'debug', - 'hooks', - 'useUds', - 'engine', - 'measurePerformance', - ] + const knownKeys = ['debug', 'hooks', 'useUds', 'engine', 'measurePerformance'] if (typeof value !== 'object') { throw new PrismaClientConstructorValidationError( - `Invalid value ${JSON.stringify( - value, - )} for "__internal" to PrismaClient constructor`, + `Invalid value ${JSON.stringify(value)} for "__internal" to PrismaClient constructor`, ) } for (const [key] of Object.entries(value)) { if (!knownKeys.includes(key)) { const didYouMean = getDidYouMean(key, knownKeys) throw new PrismaClientConstructorValidationError( - `Invalid property ${JSON.stringify( - key, - )} for "__internal" provided to PrismaClient constructor.${didYouMean}`, + `Invalid property ${JSON.stringify(key)} for "__internal" provided to PrismaClient constructor.${didYouMean}`, ) } } @@ -176,12 +142,7 @@ It should have this form: { url: "CONNECTION_STRING" }`, if (!value) { return } - if ( - isError(value) || - typeof value === 'boolean' || - typeof value === 'object' || - typeof value === 'function' - ) { + if (isError(value) || typeof value === 'boolean' || typeof value === 'object' || typeof value === 'function') { return value } throw new PrismaClientConstructorValidationError( @@ -192,10 +153,7 @@ It should have this form: { url: "CONNECTION_STRING" }`, }, } -export function validatePrismaClientOptions( - options: PrismaClientOptions, - datasourceNames: string[], -) { +export function validatePrismaClientOptions(options: PrismaClientOptions, datasourceNames: string[]) { for (const [key, value] of Object.entries(options)) { if (!knownProperties.includes(key)) { const didYouMean = getDidYouMean(key, knownProperties) diff --git a/packages/client/src/utils/ensureTestClientQueryEngine.ts b/packages/client/src/utils/ensureTestClientQueryEngine.ts index 3b96420975e4..bd80f0fa32ea 100644 --- a/packages/client/src/utils/ensureTestClientQueryEngine.ts +++ b/packages/client/src/utils/ensureTestClientQueryEngine.ts @@ -12,34 +12,22 @@ import { ClientEngineType } from '../runtime/utils/getClientEngineType' * @param clientEngineType * @param platform */ -export async function ensureTestClientQueryEngine( - clientEngineType: ClientEngineType, - platform: Platform, -) { +export async function ensureTestClientQueryEngine(clientEngineType: ClientEngineType, platform: Platform) { const enginesPath = getEnginesPath() - const queryEngineLibraryPath = path.join( - enginesPath, - getNodeAPIName(platform, 'fs'), - ) + const queryEngineLibraryPath = path.join(enginesPath, getNodeAPIName(platform, 'fs')) const queryEngineBinaryPath = path.join( enginesPath, `query-engine-${platform}${platform === 'windows' ? '.exe' : ''}`, ) - if ( - clientEngineType === ClientEngineType.Library && - !fs.existsSync(queryEngineLibraryPath) - ) { + if (clientEngineType === ClientEngineType.Library && !fs.existsSync(queryEngineLibraryPath)) { await download({ binaries: { 'libquery-engine': enginesPath, }, version: enginesVersion, }) - } else if ( - clientEngineType === ClientEngineType.Binary && - !fs.existsSync(queryEngineBinaryPath) - ) { + } else if (clientEngineType === ClientEngineType.Binary && !fs.existsSync(queryEngineBinaryPath)) { await download({ binaries: { 'query-engine': enginesPath, diff --git a/packages/client/src/utils/generateInFolder.ts b/packages/client/src/utils/generateInFolder.ts index 7252bd47f5ff..3cae4be16a60 100644 --- a/packages/client/src/utils/generateInFolder.ts +++ b/packages/client/src/utils/generateInFolder.ts @@ -2,13 +2,7 @@ import Debug from '@prisma/debug' import { enginesVersion, getEnginesPath } from '@prisma/engines' import { download } from '@prisma/fetch-engine' import { getNodeAPIName, getPlatform } from '@prisma/get-platform' -import { - extractPreviewFeatures, - getConfig, - getDMMF, - getPackedPackage, - mapPreviewFeatures, -} from '@prisma/sdk' +import { extractPreviewFeatures, getConfig, getDMMF, getPackedPackage, mapPreviewFeatures } from '@prisma/sdk' import copy from '@timsuchanek/copy' import fs from 'fs' import path from 'path' @@ -16,10 +10,7 @@ import { performance } from 'perf_hooks' import rimraf from 'rimraf' import { promisify } from 'util' import { generateClient } from '../generation/generateClient' -import { - ClientEngineType, - getClientEngineType, -} from '../runtime/utils/getClientEngineType' +import { ClientEngineType, getClientEngineType } from '../runtime/utils/getClientEngineType' import { ensureTestClientQueryEngine } from './ensureTestClientQueryEngine' const debug = Debug('prisma:generateInFolder') const del = promisify(rimraf) @@ -41,9 +32,7 @@ export async function generateInFolder({ }: GenerateInFolderOptions): Promise { const before = performance.now() if (!projectDir) { - throw new Error( - `Project dir missing. Usage: ts-node examples/generate.ts examples/accounts`, - ) + throw new Error(`Project dir missing. Usage: ts-node examples/generate.ts examples/accounts`) } if (!fs.existsSync(projectDir)) { throw new Error(`Path ${projectDir} does not exist`) @@ -91,23 +80,15 @@ export async function generateInFolder({ let runtimeDir if (useLocalRuntime) { if (useBuiltRuntime) { - runtimeDir = path.relative( - outputDir, - path.join(__dirname, '../../runtime'), - ) + runtimeDir = path.relative(outputDir, path.join(__dirname, '../../runtime')) } else { runtimeDir = path.relative(outputDir, path.join(__dirname, '../runtime')) } } else if (useBuiltRuntime) { - throw new Error( - `Please provide useBuiltRuntime and useLocalRuntime at the same time or just useLocalRuntime`, - ) + throw new Error(`Please provide useBuiltRuntime and useLocalRuntime at the same time or just useLocalRuntime`) } const enginesPath = getEnginesPath() - const queryEngineLibraryPath = path.join( - enginesPath, - getNodeAPIName(platform, 'fs'), - ) + const queryEngineLibraryPath = path.join(enginesPath, getNodeAPIName(platform, 'fs')) const queryEngineBinaryPath = path.join( enginesPath, `query-engine-${platform}${platform === 'windows' ? '.exe' : ''}`, @@ -162,7 +143,5 @@ function getSchemaPath(projectDir: string): string { if (fs.existsSync(path.join(projectDir, 'prisma/schema.prisma'))) { return path.join(projectDir, 'prisma/schema.prisma') } - throw new Error( - `Could not find any schema.prisma in ${projectDir} or sub directories.`, - ) + throw new Error(`Could not find any schema.prisma in ${projectDir} or sub directories.`) } diff --git a/packages/client/src/utils/getTestClient.ts b/packages/client/src/utils/getTestClient.ts index aa4c06bafd8f..18c32bf7c540 100644 --- a/packages/client/src/utils/getTestClient.ts +++ b/packages/client/src/utils/getTestClient.ts @@ -25,10 +25,7 @@ const readFile = promisify(fs.readFile) /** * Returns an in-memory client for testing */ -export async function getTestClient( - schemaDir?: string, - printWarnings?: boolean, -): Promise { +export async function getTestClient(schemaDir?: string, printWarnings?: boolean): Promise { if (!schemaDir) { const callsite = parse(new Error('').stack!) schemaDir = path.dirname(callsite[1].file!) @@ -40,9 +37,7 @@ export async function getTestClient( printConfigWarnings(config.warnings) } - const generator = config.generators.find( - (g) => parseEnvValue(g.provider) === 'prisma-client-js', - ) + const generator = config.generators.find((g) => parseEnvValue(g.provider) === 'prisma-client-js') const previewFeatures = mapPreviewFeatures(extractPreviewFeatures(config)) const platform = await getPlatform() const clientEngineType = getClientEngineType(generator!) diff --git a/packages/client/src/utils/resolveDatasources.ts b/packages/client/src/utils/resolveDatasources.ts index 93320745fe70..c2d27493e88e 100644 --- a/packages/client/src/utils/resolveDatasources.ts +++ b/packages/client/src/utils/resolveDatasources.ts @@ -1,11 +1,6 @@ import path from 'path' -export function absolutizeRelativePath( - url: string, - cwd: string, - outputDir: string, - absolutePaths?: boolean, -): string { +export function absolutizeRelativePath(url: string, cwd: string, outputDir: string, absolutePaths?: boolean): string { let filePath = url if (filePath.startsWith('file:')) { diff --git a/packages/debug/.prettierrc.yml b/packages/debug/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/debug/.prettierrc.yml +++ b/packages/debug/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/debug/src/__tests__/basic.test.ts b/packages/debug/src/__tests__/basic.test.ts index e17851124b0e..7c91ef97bb55 100644 --- a/packages/debug/src/__tests__/basic.test.ts +++ b/packages/debug/src/__tests__/basic.test.ts @@ -12,9 +12,7 @@ describe('debug', () => { debug('Does it even log?') debug('I dont know') - expect(removeISODate(JSON.stringify(logs, null, 2))).toMatchInlineSnapshot( - `"[]"`, - ) + expect(removeISODate(JSON.stringify(logs, null, 2))).toMatchInlineSnapshot(`"[]"`) expect(sanitizeTestLogs(getLogs())).toMatchInlineSnapshot(` "my-namespace Does it even log? diff --git a/packages/debug/src/common.ts b/packages/debug/src/common.ts index 88495d6b1d86..03b19fcc7e76 100644 --- a/packages/debug/src/common.ts +++ b/packages/debug/src/common.ts @@ -150,11 +150,7 @@ export function setup(env) { createDebug.selectColor = selectColor function extend(this, namespace, delimiter) { - const newDebug = createDebug( - this.namespace + - (typeof delimiter === 'undefined' ? ':' : delimiter) + - namespace, - ) + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace) newDebug.log = this.log return newDebug } @@ -174,9 +170,7 @@ export function setup(env) { createDebug.skips = [] let i - const split = (typeof namespaces === 'string' ? namespaces : '').split( - /[\s,]+/, - ) + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/) const len = split.length for (i = 0; i < len; i++) { diff --git a/packages/debug/src/node.ts b/packages/debug/src/node.ts index 778562ddef53..503f331bfd87 100644 --- a/packages/debug/src/node.ts +++ b/packages/debug/src/node.ts @@ -65,9 +65,7 @@ exports.inspectOpts = Object.keys(process.env) */ function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty((process.stderr as any)?.fd) + return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty((process.stderr as any)?.fd) } /** @@ -85,9 +83,7 @@ function formatArgs(this, args) { const prefix = ` ${colorCode};1m${name} \u001B[0m` args[0] = prefix + args[0].split('\n').join('\n' + prefix) - args.push( - colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m', - ) + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m') } else { args[0] = getDate() + name + ' ' + args[0] } diff --git a/packages/debug/src/util.ts b/packages/debug/src/util.ts index 8722c372a46f..12c79fbbee4b 100644 --- a/packages/debug/src/util.ts +++ b/packages/debug/src/util.ts @@ -1,10 +1,7 @@ import stripAnsi from 'strip-ansi' export function removeISODate(str: string): string { - return str.replace( - /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/gim, - '', - ) + return str.replace(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/gim, '') } export function sanitizeTestLogs(str: string): string { diff --git a/packages/engine-core/.prettierrc.yml b/packages/engine-core/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/engine-core/.prettierrc.yml +++ b/packages/engine-core/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/engine-core/src/binary/BinaryEngine.ts b/packages/engine-core/src/binary/BinaryEngine.ts index de47c51820ca..1e613a82b80d 100644 --- a/packages/engine-core/src/binary/BinaryEngine.ts +++ b/packages/engine-core/src/binary/BinaryEngine.ts @@ -16,12 +16,7 @@ import type { Readable } from 'stream' import { URL } from 'url' import { promisify } from 'util' import byline from '../tools/byline' -import type { - DatasourceOverwrite, - EngineConfig, - EngineEventType, - GetConfigResult, -} from '../common/Engine' +import type { DatasourceOverwrite, EngineConfig, EngineEventType, GetConfigResult } from '../common/Engine' import { Engine } from '../common/Engine' import type { RequestError } from '../common/errors/types/RequestError' import { PrismaClientKnownRequestError } from '../common/errors/PrismaClientKnownRequestError' @@ -31,22 +26,14 @@ import { PrismaClientRustPanicError } from '../common/errors/PrismaClientRustPan import { PrismaClientUnknownRequestError } from '../common/errors/PrismaClientUnknownRequestError' import { getErrorMessageWithLink } from '../common/errors/utils/getErrorMessageWithLink' import type { RustError, RustLog } from '../common/errors/utils/log' -import { - convertLog, - getMessage, - isRustError, - isRustErrorLog, -} from '../common/errors/utils/log' +import { convertLog, getMessage, isRustError, isRustErrorLog } from '../common/errors/utils/log' import { omit } from '../tools/omit' import { printGeneratorConfig } from '../common/utils/printGeneratorConfig' import type { Result } from './Connection' import { Connection } from './Connection' import { fixBinaryTargets, getRandomString, plusX } from '../common/utils/util' import type * as Tx from '../common/types/Transaction' -import type { - QueryEngineRequestHeaders, - QueryEngineResult, -} from '../common/types/QueryEngine' +import type { QueryEngineRequestHeaders, QueryEngineResult } from '../common/types/QueryEngine' import type { IncomingHttpHeaders } from 'http' const debug = Debug('prisma:engine') @@ -193,26 +180,17 @@ export class BinaryEngine extends Engine { 'referentialActions', 'microsoftSqlServer', ] - const removedFlagsUsed = this.previewFeatures.filter((e) => - removedFlags.includes(e), - ) + const removedFlagsUsed = this.previewFeatures.filter((e) => removedFlags.includes(e)) - if ( - removedFlagsUsed.length > 0 && - !process.env.PRISMA_HIDE_PREVIEW_FLAG_WARNINGS - ) { + if (removedFlagsUsed.length > 0 && !process.env.PRISMA_HIDE_PREVIEW_FLAG_WARNINGS) { console.log( - `${chalk.blueBright( - 'info', - )} The preview flags \`${removedFlagsUsed.join( + `${chalk.blueBright('info')} The preview flags \`${removedFlagsUsed.join( '`, `', )}\` were removed, you can now safely remove them from your schema.prisma.`, ) } - this.previewFeatures = this.previewFeatures.filter( - (e) => !removedFlags.includes(e), - ) + this.previewFeatures = this.previewFeatures.filter((e) => !removedFlags.includes(e)) this.engineEndpoint = engineEndpoint if (engineEndpoint) { @@ -221,21 +199,14 @@ export class BinaryEngine extends Engine { } if (this.platform) { - if ( - !knownPlatforms.includes(this.platform as Platform) && - !fs.existsSync(this.platform) - ) { + if (!knownPlatforms.includes(this.platform as Platform) && !fs.existsSync(this.platform)) { throw new PrismaClientInitializationError( - `Unknown ${chalk.red( - 'PRISMA_QUERY_ENGINE_BINARY', - )} ${chalk.redBright.bold( + `Unknown ${chalk.red('PRISMA_QUERY_ENGINE_BINARY')} ${chalk.redBright.bold( this.platform, )}. Possible binaryTargets: ${chalk.greenBright( knownPlatforms.join(', '), )} or a path to the query engine binary. -You may have to run ${chalk.greenBright( - 'prisma generate', - )} for your changes to take effect.`, +You may have to run ${chalk.greenBright('prisma generate')} for your changes to take effect.`, this.clientVersion!, ) } @@ -283,11 +254,7 @@ You may have to run ${chalk.greenBright( if (engines.length >= 10) { const runningEngines = engines.filter((e) => e.child) if (runningEngines.length === 10) { - console.warn( - `${chalk.yellow( - 'warn(prisma-client)', - )} Already 10 Prisma Clients are actively running.`, - ) + console.warn(`${chalk.yellow('warn(prisma-client)')} Already 10 Prisma Clients are actively running.`) } } } @@ -329,10 +296,7 @@ You may have to run ${chalk.greenBright( return this.platformPromise } - private getQueryEnginePath( - platform: string, - prefix: string = __dirname, - ): string { + private getQueryEnginePath(platform: string, prefix: string = __dirname): string { let queryEnginePath = path.join(prefix, `query-engine-${platform}`) if (platform === 'windows') { @@ -403,9 +367,7 @@ You may have to run ${chalk.greenBright( // If path to query engine doesn't exist, throw if (!(await exists(prismaPath))) { const pinnedStr = this.incorrectlyPinnedBinaryTarget - ? `\nYou incorrectly pinned it to ${chalk.redBright.bold( - `${this.incorrectlyPinnedBinaryTarget}`, - )}\n` + ? `\nYou incorrectly pinned it to ${chalk.redBright.bold(`${this.incorrectlyPinnedBinaryTarget}`)}\n` : '' let errorText = `Query engine binary for current platform "${chalk.bold( @@ -419,34 +381,23 @@ Searched Locations: ${searchedLocations .map((f) => { let msg = ` ${f}` - if ( - process.env.DEBUG === 'node-engine-search-locations' && - fs.existsSync(f) - ) { + if (process.env.DEBUG === 'node-engine-search-locations' && fs.existsSync(f)) { const dir = fs.readdirSync(f) msg += dir.map((d) => ` ${d}`).join('\n') } return msg }) - .join( - '\n' + (process.env.DEBUG === 'node-engine-search-locations' ? '\n' : ''), - )}\n` + .join('\n' + (process.env.DEBUG === 'node-engine-search-locations' ? '\n' : ''))}\n` // The generator should always be there during normal usage if (this.generator) { // The user already added it, but it still doesn't work šŸ¤·ā€ā™€ļø // That means, that some build system just deleted the files šŸ¤” if ( - this.generator.binaryTargets.find( - (object) => object.value === this.platform!, - ) || - this.generator.binaryTargets.find( - (object) => object.value === 'native', - ) + this.generator.binaryTargets.find((object) => object.value === this.platform!) || + this.generator.binaryTargets.find((object) => object.value === 'native') ) { errorText += ` -You already added the platform${ - this.generator.binaryTargets.length > 1 ? 's' : '' - } ${this.generator.binaryTargets +You already added the platform${this.generator.binaryTargets.length > 1 ? 's' : ''} ${this.generator.binaryTargets .map((t) => `"${chalk.bold(t.value)}"`) .join(', ')} to the "${chalk.underline('generator')}" block in the "schema.prisma" file as described in https://pris.ly/d/client-generator, @@ -457,18 +408,12 @@ Please create an issue at https://github.com/prisma/prisma/issues/new` } else { // If they didn't even have the current running platform in the schema.prisma file, it's easy // Just add it - errorText += `\n\nTo solve this problem, add the platform "${ - this.platform - }" to the "${chalk.underline( + errorText += `\n\nTo solve this problem, add the platform "${this.platform}" to the "${chalk.underline( 'binaryTargets', - )}" attribute in the "${chalk.underline( - 'generator', - )}" block in the "schema.prisma" file: + )}" attribute in the "${chalk.underline('generator')}" block in the "schema.prisma" file: ${chalk.greenBright(this.getFixedGenerator())} -Then run "${chalk.greenBright( - 'prisma generate', - )}" for your changes to take effect. +Then run "${chalk.greenBright('prisma generate')}" for your changes to take effect. Read more about deploying Prisma Client: https://pris.ly/d/client-generator` } } else { @@ -479,14 +424,10 @@ Read more about deploying Prisma Client: https://pris.ly/d/client-generator` } if (this.incorrectlyPinnedBinaryTarget) { - console.error(`${chalk.yellow( - 'Warning:', - )} You pinned the platform ${chalk.bold( + console.error(`${chalk.yellow('Warning:')} You pinned the platform ${chalk.bold( this.incorrectlyPinnedBinaryTarget, )}, but Prisma Client detects ${chalk.bold(await this.getPlatform())}. -This means you should very likely pin the platform ${chalk.greenBright( - await this.getPlatform(), - )} instead. +This means you should very likely pin the platform ${chalk.greenBright(await this.getPlatform())} instead. ${chalk.dim("In case we're mistaken, please report this to us šŸ™.")}`) } @@ -500,10 +441,7 @@ ${chalk.dim("In case we're mistaken, please report this to us šŸ™.")}`) private getFixedGenerator(): string { const fixedGenerator = { ...this.generator!, - binaryTargets: fixBinaryTargets( - this.generator!.binaryTargets, - this.platform!, - ), + binaryTargets: fixBinaryTargets(this.generator!.binaryTargets, this.platform!), } return printGeneratorConfig(fixedGenerator) @@ -641,18 +579,12 @@ ${chalk.dim("In case we're mistaken, please report this to us šŸ™.")}`) debug(json) this.setError(json) if (this.engineStartDeferred) { - const err = new PrismaClientInitializationError( - json.message, - this.clientVersion!, - ) + const err = new PrismaClientInitializationError(json.message, this.clientVersion!) this.engineStartDeferred.reject(err) } } } catch (e) { - if ( - !data.includes('Printing to stderr') && - !data.includes('Listening on ') - ) { + if (!data.includes('Printing to stderr') && !data.includes('Listening on ')) { this.stderrLogs += '\n' + data } } @@ -730,10 +662,7 @@ Make sure that the engine binary at ${prismaPath} is not corrupt.\n` + msg, this.clientVersion!, ) } else { - err = new PrismaClientInitializationError( - msg, - this.clientVersion!, - ) + err = new PrismaClientInitializationError(msg, this.clientVersion!) } this.engineStartDeferred.reject(err) @@ -770,9 +699,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. this.connection.close() if (code === null && signal === 'SIGABRT' && this.child) { const error = new PrismaClientRustPanicError( - this.getErrorMessageWithLink( - 'Panic in Query Engine with SIGABRT signal', - ), + this.getErrorMessageWithLink('Panic in Query Engine with SIGABRT signal'), this.clientVersion!, ) this.logEmitter.emit('error', error) @@ -795,21 +722,11 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. }) if (this.lastRustError) { - return reject( - new PrismaClientInitializationError( - getMessage(this.lastRustError), - this.clientVersion!, - ), - ) + return reject(new PrismaClientInitializationError(getMessage(this.lastRustError), this.clientVersion!)) } if (this.lastErrorLog) { - return reject( - new PrismaClientInitializationError( - getMessage(this.lastErrorLog), - this.clientVersion!, - ), - ) + return reject(new PrismaClientInitializationError(getMessage(this.lastErrorLog), this.clientVersion!)) } try { @@ -906,10 +823,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. server.on('error', reject) server.listen(0, () => { const address = server.address() - const port = - typeof address === 'string' - ? parseInt(address.split(':').slice(-1)[0], 10) - : address!.port + const port = typeof address === 'string' ? parseInt(address.split(':').slice(-1)[0], 10) : address!.port server.close((e) => { if (e) { reject(e) @@ -957,18 +871,10 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. return this.lastVersion } - async request( - query: string, - headers: QueryEngineRequestHeaders = {}, - numTry = 1, - ): Promise> { + async request(query: string, headers: QueryEngineRequestHeaders = {}, numTry = 1): Promise> { await this.start() - this.currentRequestPromise = this.connection.post( - '/', - stringifyQuery(query), - runtimeHeadersToHttpHeaders(headers), - ) + this.currentRequestPromise = this.connection.post('/', stringifyQuery(query), runtimeHeadersToHttpHeaders(headers)) this.lastQuery = query try { @@ -978,10 +884,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. throw this.graphQLToJSError(data.errors[0]) } // this case should not happen, as the query engine only returns one error - throw new PrismaClientUnknownRequestError( - JSON.stringify(data.errors), - this.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(JSON.stringify(data.errors), this.clientVersion!) } // Rust engine returns time in microseconds and we want it in miliseconds @@ -1025,11 +928,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. } this.lastQuery = JSON.stringify(request) - this.currentRequestPromise = this.connection.post( - '/', - this.lastQuery, - runtimeHeadersToHttpHeaders(headers), - ) + this.currentRequestPromise = this.connection.post('/', this.lastQuery, runtimeHeadersToHttpHeaders(headers)) return this.currentRequestPromise .then(({ data, headers }) => { @@ -1089,10 +988,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. return result.data } else if (action === 'commit') { - await Connection.onHttpError( - this.connection.post(`/transaction/${arg.id}/commit`), - transactionHttpErrorHandler, - ) + await Connection.onHttpError(this.connection.post(`/transaction/${arg.id}/commit`), transactionHttpErrorHandler) } else if (action === 'rollback') { await Connection.onHttpError( this.connection.post(`/transaction/${arg.id}/rollback`), @@ -1157,10 +1053,7 @@ You very likely have the wrong "binaryTarget" defined in the schema.prisma file. }) } - private handleRequestError = async ( - error: Error & { code?: string }, - graceful = false, - ) => { + private handleRequestError = async (error: Error & { code?: string }, graceful = false) => { debug({ error }) // if we are starting, wait for it before we handle any error if (this.startPromise) { @@ -1218,9 +1111,7 @@ Please look into the logs or turn on the env var DEBUG=* to debug the constantly return false } - private graphQLToJSError( - error: RequestError, - ): PrismaClientKnownRequestError | PrismaClientUnknownRequestError { + private graphQLToJSError(error: RequestError): PrismaClientKnownRequestError | PrismaClientUnknownRequestError { if (error.user_facing_error.error_code) { return new PrismaClientKnownRequestError( error.user_facing_error.message, @@ -1230,10 +1121,7 @@ Please look into the logs or turn on the env var DEBUG=* to debug the constantly ) } - return new PrismaClientUnknownRequestError( - error.user_facing_error.message, - this.clientVersion!, - ) + return new PrismaClientUnknownRequestError(error.user_facing_error.message, this.clientVersion!) } } @@ -1294,9 +1182,7 @@ function transactionHttpErrorHandler(result: Result): never { * @param headers to transform * @returns */ -function runtimeHeadersToHttpHeaders( - headers: QueryEngineRequestHeaders, -): IncomingHttpHeaders { +function runtimeHeadersToHttpHeaders(headers: QueryEngineRequestHeaders): IncomingHttpHeaders { return Object.keys(headers).reduce((acc, runtimeHeaderKey) => { let httpHeaderKey = runtimeHeaderKey diff --git a/packages/engine-core/src/binary/Connection.ts b/packages/engine-core/src/binary/Connection.ts index 9956fc16554a..e88e1dbdcb47 100644 --- a/packages/engine-core/src/binary/Connection.ts +++ b/packages/engine-core/src/binary/Connection.ts @@ -34,10 +34,7 @@ export class Connection { * @param handler to execute * @returns */ - static async onHttpError( - response: Promise>, - handler: (result: Result) => HR, - ) { + static async onHttpError(response: Promise>, handler: (result: Result) => HR) { const _response = await response if (_response.statusCode >= 400) { @@ -108,11 +105,7 @@ export class Connection { * @param headers * @returns */ - post( - endpoint: string, - body?: Client.DispatchOptions['body'], - headers?: Client.DispatchOptions['headers'], - ) { + post(endpoint: string, body?: Client.DispatchOptions['body'], headers?: Client.DispatchOptions['headers']) { return this.raw('POST', endpoint, headers, body) } diff --git a/packages/engine-core/src/common/Engine.ts b/packages/engine-core/src/common/Engine.ts index 355445d0e2bf..4e4f8ae96be0 100644 --- a/packages/engine-core/src/common/Engine.ts +++ b/packages/engine-core/src/common/Engine.ts @@ -1,9 +1,6 @@ import type { DataSource, GeneratorConfig } from '@prisma/generator-helper' import type * as Transaction from './types/Transaction' -import type { - QueryEngineRequestHeaders, - QueryEngineResult, -} from './types/QueryEngine' +import type { QueryEngineRequestHeaders, QueryEngineResult } from './types/QueryEngine' // import type { InlineDatasources } from '../../../client/src/generation/utils/buildInlineDatasources' export interface FilterConstructor { @@ -28,15 +25,9 @@ export abstract class Engine { transaction?: boolean, numTry?: number, ): Promise[]> - abstract transaction( - action: 'start', - options?: Transaction.Options, - ): Promise + abstract transaction(action: 'start', options?: Transaction.Options): Promise abstract transaction(action: 'commit', info: Transaction.Info): Promise - abstract transaction( - action: 'rollback', - info: Transaction.Info, - ): Promise + abstract transaction(action: 'rollback', info: Transaction.Info): Promise } export type EngineEventType = 'query' | 'info' | 'warn' | 'error' | 'beforeExit' diff --git a/packages/engine-core/src/common/errors/PrismaClientKnownRequestError.ts b/packages/engine-core/src/common/errors/PrismaClientKnownRequestError.ts index 1b6919da0b9c..78fb8d1be349 100644 --- a/packages/engine-core/src/common/errors/PrismaClientKnownRequestError.ts +++ b/packages/engine-core/src/common/errors/PrismaClientKnownRequestError.ts @@ -3,12 +3,7 @@ export class PrismaClientKnownRequestError extends Error { meta?: object clientVersion: string - constructor( - message: string, - code: string, - clientVersion: string, - meta?: any, - ) { + constructor(message: string, code: string, clientVersion: string, meta?: any) { super(message) this.code = code diff --git a/packages/engine-core/src/common/errors/utils/getErrorMessageWithLink.ts b/packages/engine-core/src/common/errors/utils/getErrorMessageWithLink.ts index 1f5404ce1ce6..389f1ee59ae9 100644 --- a/packages/engine-core/src/common/errors/utils/getErrorMessageWithLink.ts +++ b/packages/engine-core/src/common/errors/utils/getErrorMessageWithLink.ts @@ -16,9 +16,7 @@ export function getErrorMessageWithLink({ }: ErrorWithLinkInput) { const gotLogs = getLogs(6000 - (query?.length ?? 0)) const logs = normalizeLogs(stripAnsi(gotLogs)) - const moreInfo = description - ? `# Description\n\`\`\`\n${description}\n\`\`\`` - : '' + const moreInfo = description ? `# Description\n\`\`\`\n${description}\n\`\`\`` : '' const body = stripAnsi( `Hi Prisma Team! My Prisma Client just crashed. This is the report: ## Versions diff --git a/packages/engine-core/src/common/errors/utils/log.ts b/packages/engine-core/src/common/errors/utils/log.ts index 7896abf8cedd..3e94be99bad3 100644 --- a/packages/engine-core/src/common/errors/utils/log.ts +++ b/packages/engine-core/src/common/errors/utils/log.ts @@ -69,16 +69,11 @@ export function getBacktraceFromRustError(err: RustError): string { } export function isRustLog(e: any): e is RustLog { - return ( - e.timestamp && typeof e.level === 'string' && typeof e.target === 'string' - ) + return e.timestamp && typeof e.level === 'string' && typeof e.target === 'string' } export function isRustErrorLog(e: any): e is RustLog { - return ( - isRustLog(e) && - (e.level === 'error' || e.fields?.message?.includes('fatal error')) - ) + return isRustLog(e) && (e.level === 'error' || e.fields?.message?.includes('fatal error')) } export function isRustError(e: any): e is RustError { @@ -120,9 +115,7 @@ export interface Log { export function convertLog(rustLog: RawRustLog): RustLog { const isQuery = isQueryLog(rustLog.fields) - const level: LogLevel = isQuery - ? 'query' - : (rustLog.level.toLowerCase() as LogLevel) + const level: LogLevel = isQuery ? 'query' : (rustLog.level.toLowerCase() as LogLevel) return { ...rustLog, level, diff --git a/packages/engine-core/src/common/errors/utils/normalizeLogs.ts b/packages/engine-core/src/common/errors/utils/normalizeLogs.ts index a96f0c36958a..b4f9e9877219 100644 --- a/packages/engine-core/src/common/errors/utils/normalizeLogs.ts +++ b/packages/engine-core/src/common/errors/utils/normalizeLogs.ts @@ -7,10 +7,7 @@ export function normalizeLogs(logs: string): string { .split('\n') .map((l) => { return l - .replace( - /^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)\s*/, - '', - ) + .replace(/^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)\s*/, '') .replace(/\+\d+\s*ms$/, '') }) .join('\n') diff --git a/packages/engine-core/src/common/types/QueryEngine.ts b/packages/engine-core/src/common/types/QueryEngine.ts index 39fc18edd771..27fe66d2df39 100644 --- a/packages/engine-core/src/common/types/QueryEngine.ts +++ b/packages/engine-core/src/common/types/QueryEngine.ts @@ -1,10 +1,7 @@ import type { DataSource, GeneratorConfig } from '@prisma/generator-helper' // Events -export type QueryEngineEvent = - | QueryEngineLogEvent - | QueryEngineQueryEvent - | QueryEnginePanicEvent +export type QueryEngineEvent = QueryEngineLogEvent | QueryEngineQueryEvent | QueryEnginePanicEvent export type QueryEngineLogEvent = { level: string @@ -33,13 +30,7 @@ export type QueryEnginePanicEvent = { } // Configuration -export type QueryEngineLogLevel = - | 'trace' - | 'debug' - | 'info' - | 'warn' - | 'error' - | 'off' +export type QueryEngineLogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'off' export type QueryEngineConfig = { // TODO rename datamodel here and other places diff --git a/packages/engine-core/src/common/utils/getInternalDatamodelJson.ts b/packages/engine-core/src/common/utils/getInternalDatamodelJson.ts index 9a3f940a1ba9..9aac6187d0f1 100644 --- a/packages/engine-core/src/common/utils/getInternalDatamodelJson.ts +++ b/packages/engine-core/src/common/utils/getInternalDatamodelJson.ts @@ -18,11 +18,7 @@ export function getInternalDatamodelJson( proc.on('exit', function (code, signal) { if (code !== 0) { - console.error( - '[schema-inferrer-bin] exit: code=%s signal=%s', - code, - signal, - ) + console.error('[schema-inferrer-bin] exit: code=%s signal=%s', code, signal) } reject() }) diff --git a/packages/engine-core/src/common/utils/printGeneratorConfig.ts b/packages/engine-core/src/common/utils/printGeneratorConfig.ts index b0f846cc1109..9dd7e53de797 100644 --- a/packages/engine-core/src/common/utils/printGeneratorConfig.ts +++ b/packages/engine-core/src/common/utils/printGeneratorConfig.ts @@ -1,7 +1,4 @@ -import type { - GeneratorConfig, - BinaryTargetsEnvValue, -} from '@prisma/generator-helper' +import type { GeneratorConfig, BinaryTargetsEnvValue } from '@prisma/generator-helper' import indent from 'indent-string' export function printGeneratorConfig(config: GeneratorConfig): string { @@ -14,9 +11,7 @@ export class GeneratorConfigClass { const { config } = this // parse & stringify trims out all the undefined values - const provider = config.provider.fromEnvVar - ? `env("${config.provider.fromEnvVar}")` - : config.provider.value + const provider = config.provider.fromEnvVar ? `env("${config.provider.fromEnvVar}")` : config.provider.value const obj = JSON.parse( JSON.stringify({ @@ -31,14 +26,10 @@ ${indent(printDatamodelObject(obj), 2)} } } -export function getOriginalBinaryTargetsValue( - binaryTargets: BinaryTargetsEnvValue[], -) { +export function getOriginalBinaryTargetsValue(binaryTargets: BinaryTargetsEnvValue[]) { let value: string | string[] | undefined if (binaryTargets.length > 0) { - const binaryTargetsFromEnvVar = binaryTargets.find( - (object) => object.fromEnvVar !== null, - ) + const binaryTargetsFromEnvVar = binaryTargets.find((object) => object.fromEnvVar !== null) if (binaryTargetsFromEnvVar) { value = `env("${binaryTargetsFromEnvVar.fromEnvVar}")` } else { @@ -52,10 +43,7 @@ export function getOriginalBinaryTargetsValue( } export function printDatamodelObject(obj): string { - const maxLength = Object.keys(obj).reduce( - (max, curr) => Math.max(max, curr.length), - 0, - ) + const maxLength = Object.keys(obj).reduce((max, curr) => Math.max(max, curr.length), 0) return Object.entries(obj) .map(([key, value]) => `${key.padEnd(maxLength)} = ${niceStringify(value)}`) .join('\n') diff --git a/packages/engine-core/src/common/utils/util.ts b/packages/engine-core/src/common/utils/util.ts index 98435d042d1c..46d2fe53f0a4 100644 --- a/packages/engine-core/src/common/utils/util.ts +++ b/packages/engine-core/src/common/utils/util.ts @@ -21,9 +21,7 @@ export function plusX(file): void { fs.chmodSync(file, base8) } -function transformPlatformToEnvValue( - platform: Platform | string, -): BinaryTargetsEnvValue { +function transformPlatformToEnvValue(platform: Platform | string): BinaryTargetsEnvValue { return { fromEnvVar: null, value: platform } } diff --git a/packages/engine-core/src/data-proxy/DataProxyEngine.ts b/packages/engine-core/src/data-proxy/DataProxyEngine.ts index 5a31923994dc..e1cdd01c18eb 100644 --- a/packages/engine-core/src/data-proxy/DataProxyEngine.ts +++ b/packages/engine-core/src/data-proxy/DataProxyEngine.ts @@ -1,11 +1,7 @@ /// import { Engine } from '../common/Engine' -import type { - EngineConfig, - EngineEventType, - GetConfigResult, -} from '../common/Engine' +import type { EngineConfig, EngineEventType, GetConfigResult } from '../common/Engine' import { request } from './utils/request' import EventEmitter from 'events' import { createSchemaHash } from './utils/createSchemaHash' @@ -120,16 +116,9 @@ export class DataProxyEngine extends Engine { return this.requestInternal({ query, variables: {} }, headers, attempt) } - async requestBatch( - queries: string[], - headers: Record, - isTransaction = false, - attempt = 0, - ) { + async requestBatch(queries: string[], headers: Record, isTransaction = false, attempt = 0) { this.logEmitter.emit('query', { - query: `Batch${isTransaction ? ' in transaction' : ''} (${ - queries.length - }):\n${queries.join('\n')}`, + query: `Batch${isTransaction ? ' in transaction' : ''} (${queries.length}):\n${queries.join('\n')}`, }) const body = { @@ -137,20 +126,12 @@ export class DataProxyEngine extends Engine { transaction: isTransaction, } - const { batchResult } = await this.requestInternal( - body, - headers, - attempt, - ) + const { batchResult } = await this.requestInternal(body, headers, attempt) return batchResult } - private async requestInternal( - body: Record, - headers: Record, - attempt: number, - ) { + private async requestInternal(body: Record, headers: Record, attempt: number) { await this.initPromise try { diff --git a/packages/engine-core/src/data-proxy/utils/request.ts b/packages/engine-core/src/data-proxy/utils/request.ts index 48d57e09558c..aeb80bb43d59 100644 --- a/packages/engine-core/src/data-proxy/utils/request.ts +++ b/packages/engine-core/src/data-proxy/utils/request.ts @@ -13,10 +13,7 @@ export type RequestOptions = O.Patch< > // our implementation handles less -export type RequestResponse = O.Required< - O.Optional, - 'json' | 'url' | 'ok' | 'status' -> +export type RequestResponse = O.Required, 'json' | 'url' | 'ok' | 'status'> /** * Isomorphic `fetch` that imitates `fetch` via `http` when for Node.js. @@ -24,10 +21,7 @@ export type RequestResponse = O.Required< * @param options * @returns */ -export async function request( - url: string, - options: RequestOptions = {}, -): Promise { +export async function request(url: string, options: RequestOptions = {}): Promise { const jsRuntimeName = getJSRuntimeName() if (jsRuntimeName === 'browser') { @@ -68,10 +62,7 @@ function buildOptions(options: RequestOptions): _https.RequestOptions { * @param response * @returns */ -function buildResponse( - incomingData: Buffer[], - response: IncomingMessage, -): RequestResponse { +function buildResponse(incomingData: Buffer[], response: IncomingMessage): RequestResponse { return { json: () => JSON.parse(Buffer.concat(incomingData).toString()), ok: response.statusCode! >= 200 && response.statusCode! < 300, @@ -88,10 +79,7 @@ function buildResponse( * @param options * @returns */ -function nodeFetch( - url: string, - options: RequestOptions = {}, -): Promise { +function nodeFetch(url: string, options: RequestOptions = {}): Promise { const httpsOptions = buildOptions(options) const incomingData = [] as Buffer[] diff --git a/packages/engine-core/src/index.ts b/packages/engine-core/src/index.ts index f2fd99a3dd53..32e072d46fae 100644 --- a/packages/engine-core/src/index.ts +++ b/packages/engine-core/src/index.ts @@ -12,10 +12,7 @@ export { BinaryEngine } from './binary/BinaryEngine' export { DataProxyEngine } from './data-proxy/DataProxyEngine' export * as NodeAPILibraryTypes from './library/types/Library' -export { - printGeneratorConfig, - getOriginalBinaryTargetsValue, -} from './common/utils/printGeneratorConfig' +export { printGeneratorConfig, getOriginalBinaryTargetsValue } from './common/utils/printGeneratorConfig' export { getInternalDatamodelJson } from './common/utils/getInternalDatamodelJson' export { fixBinaryTargets } from './common/utils/util' export { plusX } from './common/utils/util' diff --git a/packages/engine-core/src/library/LibraryEngine.ts b/packages/engine-core/src/library/LibraryEngine.ts index 0321efedfbf2..bb24da8934a1 100644 --- a/packages/engine-core/src/library/LibraryEngine.ts +++ b/packages/engine-core/src/library/LibraryEngine.ts @@ -1,21 +1,12 @@ import Debug from '@prisma/debug' import { getEnginesPath } from '@prisma/engines' import type { Platform } from '@prisma/get-platform' -import { - getNodeAPIName, - getPlatform, - isNodeAPISupported, - platforms, -} from '@prisma/get-platform' +import { getNodeAPIName, getPlatform, isNodeAPISupported, platforms } from '@prisma/get-platform' import chalk from 'chalk' import EventEmitter from 'events' import fs from 'fs' import path from 'path' -import type { - DatasourceOverwrite, - EngineConfig, - EngineEventType, -} from '../common/Engine' +import type { DatasourceOverwrite, EngineConfig, EngineEventType } from '../common/Engine' import { Engine } from '../common/Engine' import { PrismaClientInitializationError } from '../common/errors/PrismaClientInitializationError' import { PrismaClientKnownRequestError } from '../common/errors/PrismaClientKnownRequestError' @@ -39,11 +30,7 @@ import type { import type * as Tx from '../common/types/Transaction' import { printGeneratorConfig } from '../common/utils/printGeneratorConfig' import { fixBinaryTargets } from '../common/utils/util' -import type { - Library, - QueryEngineConstructor, - QueryEngineInstance, -} from './types/Library' +import type { Library, QueryEngineConstructor, QueryEngineInstance } from './types/Library' const debug = Debug('prisma:client:libraryEngine') @@ -95,9 +82,7 @@ export class LibraryEngine extends Engine { this.logEmitter.on('error', (e) => { // to prevent unhandled error events }) - this.datasourceOverrides = config.datasources - ? this.convertDatasources(config.datasources) - : {} + this.datasourceOverrides = config.datasources ? this.convertDatasources(config.datasources) : {} if (config.enableDebugLogs) { this.logLevel = 'debug' // Debug.enable('*') @@ -112,11 +97,7 @@ export class LibraryEngine extends Engine { if (engines.length >= 10) { const runningEngines = engines.filter((e) => e.engine) if (runningEngines.length === 10) { - console.warn( - `${chalk.yellow( - 'warn(prisma-client)', - )} Already 10 Prisma Clients are actively running.`, - ) + console.warn(`${chalk.yellow('warn(prisma-client)')} Already 10 Prisma Clients are actively running.`) } } } @@ -160,16 +141,12 @@ export class LibraryEngine extends Engine { const platform = await getPlatform() if (!knownPlatforms.includes(platform)) { throw new PrismaClientInitializationError( - `Unknown ${chalk.red( - 'PRISMA_QUERY_ENGINE_LIBRARY', - )} ${chalk.redBright.bold( + `Unknown ${chalk.red('PRISMA_QUERY_ENGINE_LIBRARY')} ${chalk.redBright.bold( this.platform, )}. Possible binaryTargets: ${chalk.greenBright( knownPlatforms.join(', '), )} or a path to the query engine library. -You may have to run ${chalk.greenBright( - 'prisma generate', - )} for your changes to take effect.`, +You may have to run ${chalk.greenBright('prisma generate')} for your changes to take effect.`, this.config.clientVersion!, ) } @@ -178,25 +155,17 @@ You may have to run ${chalk.greenBright( private parseEngineResponse(response?: string): T { if (!response) { - throw new PrismaClientUnknownRequestError( - `Response from the Engine was empty`, - this.config.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(`Response from the Engine was empty`, this.config.clientVersion!) } try { const config = JSON.parse(response) return config as T } catch (err) { - throw new PrismaClientUnknownRequestError( - `Unable to JSON.parse response from engine`, - this.config.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(`Unable to JSON.parse response from engine`, this.config.clientVersion!) } } - private convertDatasources( - datasources: DatasourceOverwrite[], - ): Record { + private convertDatasources(datasources: DatasourceOverwrite[]): Record { const obj = Object.create(null) for (const { name, url } of datasources) { obj[name] = url @@ -219,24 +188,18 @@ You may have to run ${chalk.greenBright( if (fs.existsSync(this.libQueryEnginePath)) { if (this.libQueryEnginePath.endsWith('.node')) { throw new PrismaClientInitializationError( - `Unable to load Node-API Library from ${chalk.dim( - this.libQueryEnginePath, - )}, Library may be corrupt`, + `Unable to load Node-API Library from ${chalk.dim(this.libQueryEnginePath)}, Library may be corrupt`, this.config.clientVersion!, ) } else { throw new PrismaClientInitializationError( - `Expected an Node-API Library but received ${chalk.dim( - this.libQueryEnginePath, - )}`, + `Expected an Node-API Library but received ${chalk.dim(this.libQueryEnginePath)}`, this.config.clientVersion!, ) } } else { throw new PrismaClientInitializationError( - `Unable to load Node-API Library from ${chalk.dim( - this.libQueryEnginePath, - )}, It does not exist`, + `Unable to load Node-API Library from ${chalk.dim(this.libQueryEnginePath)}, It does not exist`, this.config.clientVersion!, ) } @@ -262,11 +225,7 @@ You may have to run ${chalk.greenBright( if (typeof error === 'string') { throw e } else { - throw new PrismaClientInitializationError( - error.message, - this.config.clientVersion!, - error.error_code, - ) + throw new PrismaClientInitializationError(error.message, this.config.clientVersion!, error.error_code) } } } @@ -356,9 +315,7 @@ You may have to run ${chalk.greenBright( await this.libraryInstantiationPromise await this.libraryStoppingPromise if (this.libraryStartingPromise) { - debug( - `library already starting, this.libraryStarted: ${this.libraryStarted}`, - ) + debug(`library already starting, this.libraryStarted: ${this.libraryStarted}`) return this.libraryStartingPromise } if (!this.libraryStarted) { @@ -379,13 +336,7 @@ You may have to run ${chalk.greenBright( if (typeof error === 'string') { reject(err) } else { - reject( - new PrismaClientInitializationError( - error.message, - this.config.clientVersion!, - error.error_code, - ), - ) + reject(new PrismaClientInitializationError(error.message, this.config.clientVersion!, error.error_code)) } }) }) @@ -434,9 +385,7 @@ You may have to run ${chalk.greenBright( return this.versionInfo?.version ?? 'unknown' } - private prismaGraphQLToJSError( - error: RequestError, - ): PrismaClientKnownRequestError | PrismaClientUnknownRequestError { + private prismaGraphQLToJSError(error: RequestError): PrismaClientKnownRequestError | PrismaClientUnknownRequestError { debug('graphQLToJSError') if (error.user_facing_error.error_code) { @@ -448,10 +397,7 @@ You may have to run ${chalk.greenBright( ) } - return new PrismaClientUnknownRequestError( - error.error, - this.config.clientVersion!, - ) + return new PrismaClientUnknownRequestError(error.error, this.config.clientVersion!) } async request( @@ -466,26 +412,17 @@ You may have to run ${chalk.greenBright( try { await this.start() - this.executingQueryPromise = this.engine?.query( - queryStr, - headerStr, - headers.transactionId, - ) + this.executingQueryPromise = this.engine?.query(queryStr, headerStr, headers.transactionId) this.lastQuery = queryStr - const data = this.parseEngineResponse( - await this.executingQueryPromise, - ) + const data = this.parseEngineResponse(await this.executingQueryPromise) if (data.errors) { if (data.errors.length === 1) { throw this.prismaGraphQLToJSError(data.errors[0]) } // this case should not happen, as the query engine only returns one error - throw new PrismaClientUnknownRequestError( - JSON.stringify(data.errors), - this.config.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(JSON.stringify(data.errors), this.config.clientVersion!) } else if (this.loggerRustPanic) { throw this.loggerRustPanic } @@ -499,10 +436,7 @@ You may have to run ${chalk.greenBright( if (typeof error === 'string') { throw e } else { - throw new PrismaClientUnknownRequestError( - `${error.message}\n${error.backtrace}`, - this.config.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(`${error.message}\n${error.backtrace}`, this.config.clientVersion!) } } } @@ -534,20 +468,14 @@ You may have to run ${chalk.greenBright( throw this.prismaGraphQLToJSError(data.errors[0]) } // this case should not happen, as the query engine only returns one error - throw new PrismaClientUnknownRequestError( - JSON.stringify(data.errors), - this.config.clientVersion!, - ) + throw new PrismaClientUnknownRequestError(JSON.stringify(data.errors), this.config.clientVersion!) } const { batchResult, errors } = data if (Array.isArray(batchResult)) { return batchResult.map((result) => { if (result.errors) { - return ( - this.loggerRustPanic ?? - this.prismaGraphQLToJSError(result.errors[0]) - ) + return this.loggerRustPanic ?? this.prismaGraphQLToJSError(result.errors[0]) } return { data: result, @@ -575,10 +503,7 @@ You may have to run ${chalk.greenBright( this.platform = this.platform ?? (await getPlatform()) if (__filename.includes('LibraryEngine')) { - enginePath = path.join( - getEnginesPath(), - getNodeAPIName(this.platform, 'fs'), - ) + enginePath = path.join(getEnginesPath(), getNodeAPIName(this.platform, 'fs')) return { enginePath, searchedLocations } } const searchLocations: string[] = [ @@ -609,8 +534,7 @@ You may have to run ${chalk.greenBright( private async getLibQueryEnginePath(): Promise { // TODO Document ENV VAR - const libPath = - process.env.PRISMA_QUERY_ENGINE_LIBRARY ?? this.config.prismaPath + const libPath = process.env.PRISMA_QUERY_ENGINE_LIBRARY ?? this.config.prismaPath if (libPath && fs.existsSync(libPath) && libPath.endsWith('.node')) { return libPath } @@ -619,9 +543,7 @@ You may have to run ${chalk.greenBright( // If path to query engine doesn't exist, throw if (!fs.existsSync(enginePath)) { const incorrectPinnedPlatformErrorStr = this.platform - ? `\nYou incorrectly pinned it to ${chalk.redBright.bold( - `${this.platform}`, - )}\n` + ? `\nYou incorrectly pinned it to ${chalk.redBright.bold(`${this.platform}`)}\n` : '' // TODO Improve search engine logic possibly using findSync let errorText = `Query engine library for current platform "${chalk.bold( @@ -635,30 +557,21 @@ Searched Locations: ${searchedLocations .map((f) => { let msg = ` ${f}` - if ( - process.env.DEBUG === 'node-engine-search-locations' && - fs.existsSync(f) - ) { + if (process.env.DEBUG === 'node-engine-search-locations' && fs.existsSync(f)) { const dir = fs.readdirSync(f) msg += dir.map((d) => ` ${d}`).join('\n') } return msg }) - .join( - '\n' + (process.env.DEBUG === 'node-engine-search-locations' ? '\n' : ''), - )}\n` + .join('\n' + (process.env.DEBUG === 'node-engine-search-locations' ? '\n' : ''))}\n` // The generator should always be there during normal usage if (this.config.generator) { // The user already added it, but it still doesn't work šŸ¤·ā€ā™€ļø // That means, that some build system just deleted the files šŸ¤” this.platform = this.platform ?? (await getPlatform()) if ( - this.config.generator.binaryTargets.find( - (object) => object.value === this.platform!, - ) || - this.config.generator.binaryTargets.find( - (object) => object.value === 'native', - ) + this.config.generator.binaryTargets.find((object) => object.value === this.platform!) || + this.config.generator.binaryTargets.find((object) => object.value === 'native') ) { errorText += ` You already added the platform${ @@ -674,28 +587,19 @@ Please create an issue at https://github.com/prisma/prisma/issues/new` } else { // If they didn't even have the current running platform in the schema.prisma file, it's easy // Just add it - errorText += `\n\nTo solve this problem, add the platform "${ - this.platform - }" to the "${chalk.underline( + errorText += `\n\nTo solve this problem, add the platform "${this.platform}" to the "${chalk.underline( 'binaryTargets', - )}" attribute in the "${chalk.underline( - 'generator', - )}" block in the "schema.prisma" file: + )}" attribute in the "${chalk.underline('generator')}" block in the "schema.prisma" file: ${chalk.greenBright(this.getFixedGenerator())} -Then run "${chalk.greenBright( - 'prisma generate', - )}" for your changes to take effect. +Then run "${chalk.greenBright('prisma generate')}" for your changes to take effect. Read more about deploying Prisma Client: https://pris.ly/d/client-generator` } } else { errorText += `\n\nRead more about deploying Prisma Client: https://pris.ly/d/client-generator\n` } - throw new PrismaClientInitializationError( - errorText, - this.config.clientVersion!, - ) + throw new PrismaClientInitializationError(errorText, this.config.clientVersion!) } this.platform = this.platform ?? (await getPlatform()) return enginePath @@ -704,10 +608,7 @@ Read more about deploying Prisma Client: https://pris.ly/d/client-generator` private getFixedGenerator(): string { const fixedGenerator = { ...this.config.generator!, - binaryTargets: fixBinaryTargets( - this.config.generator!.binaryTargets, - this.platform!, - ), + binaryTargets: fixBinaryTargets(this.config.generator!.binaryTargets, this.platform!), } return printGeneratorConfig(fixedGenerator) diff --git a/packages/engine-core/src/library/types/Library.ts b/packages/engine-core/src/library/types/Library.ts index 8f4a4681759a..c110427df692 100644 --- a/packages/engine-core/src/library/types/Library.ts +++ b/packages/engine-core/src/library/types/Library.ts @@ -1,8 +1,4 @@ -import type { - GetConfigOptions, - ConfigMetaFormat, - QueryEngineConfig, -} from '../../common/types/QueryEngine' +import type { GetConfigOptions, ConfigMetaFormat, QueryEngineConfig } from '../../common/types/QueryEngine' export type ConnectArgs = { enableRawQueries: boolean @@ -15,11 +11,7 @@ export type QueryEngineInstance = { * @param requestStr JSON.stringified `QueryEngineRequest | QueryEngineBatchRequest` * @param headersStr JSON.stringified `QueryEngineRequestHeaders` */ - query( - requestStr: string, - headersStr: string, - transactionId?: string, - ): Promise + query(requestStr: string, headersStr: string, transactionId?: string): Promise sdlSchema(): Promise startTransaction(options: string, trace: string): Promise commitTransaction(id: string, trace: string): Promise @@ -27,10 +19,7 @@ export type QueryEngineInstance = { } export interface QueryEngineConstructor { - new ( - config: QueryEngineConfig, - logger: (err: string, log: string) => void, - ): QueryEngineInstance + new (config: QueryEngineConfig, logger: (err: string, log: string) => void): QueryEngineInstance } // Main diff --git a/packages/generator-helper/.prettierrc.yml b/packages/generator-helper/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/generator-helper/.prettierrc.yml +++ b/packages/generator-helper/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/generator-helper/src/GeneratorProcess.ts b/packages/generator-helper/src/GeneratorProcess.ts index 2f8e794d9bdb..a13a23ed0eaa 100644 --- a/packages/generator-helper/src/GeneratorProcess.ts +++ b/packages/generator-helper/src/GeneratorProcess.ts @@ -2,12 +2,7 @@ import type { ChildProcessByStdio } from 'child_process' import { fork } from 'child_process' import { spawn } from 'cross-spawn' import byline from './byline' -import type { - GeneratorConfig, - GeneratorManifest, - GeneratorOptions, - JsonRPC, -} from './types' +import type { GeneratorConfig, GeneratorManifest, GeneratorOptions, JsonRPC } from './types' import chalk from 'chalk' import Debug from '@prisma/debug' @@ -70,9 +65,7 @@ export class GeneratorProcess { this.exitCode = code if (code && code > 0 && this.currentGenerateDeferred) { // print last 5 lines of stderr - this.currentGenerateDeferred.reject( - new Error(this.stderrLogs.split('\n').slice(-5).join('\n')), - ) + this.currentGenerateDeferred.reject(new Error(this.stderrLogs.split('\n').slice(-5).join('\n'))) } }) @@ -81,9 +74,7 @@ export class GeneratorProcess { if (err.message.includes('EACCES')) { reject( new Error( - `The executable at ${ - this.executablePath - } lacks the right chmod. Please use ${chalk.bold( + `The executable at ${this.executablePath} lacks the right chmod. Please use ${chalk.bold( `chmod +x ${this.executablePath}`, )}`, ), @@ -109,11 +100,7 @@ export class GeneratorProcess { // wait 200ms for the binary to fail setTimeout(() => { if (this.exitCode && this.exitCode > 0) { - reject( - new Error( - `Generator at ${this.executablePath} could not start:\n\n${this.stderrLogs}`, - ), - ) + reject(new Error(`Generator at ${this.executablePath} could not start:\n\n${this.stderrLogs}`)) } else { resolve() } @@ -130,11 +117,7 @@ export class GeneratorProcess { } if (this.listeners[data.id]) { if (data.error) { - const error = new GeneratorError( - data.error.message, - data.error.code, - data.error.data, - ) + const error = new GeneratorError(data.error.message, data.error.code, data.error.data) this.listeners[data.id](null, error) } else { this.listeners[data.id](data.result) @@ -143,10 +126,7 @@ export class GeneratorProcess { } } } - private registerListener( - messageId: number, - cb: (result: any, err?: Error) => void, - ): void { + private registerListener(messageId: number, cb: (result: any, err?: Error) => void): void { this.listeners[messageId] = cb } private sendMessage(message: JsonRPC.Request): void { diff --git a/packages/generator-helper/src/__tests__/generatorHandler.test.ts b/packages/generator-helper/src/__tests__/generatorHandler.test.ts index 34a03bcb129d..f92428addff2 100644 --- a/packages/generator-helper/src/__tests__/generatorHandler.test.ts +++ b/packages/generator-helper/src/__tests__/generatorHandler.test.ts @@ -48,9 +48,7 @@ const stubOptions: GeneratorOptions = { describe('generatorHandler', () => { test('exiting', async () => { - const generator = new GeneratorProcess( - path.join(__dirname, 'exiting-executable'), - ) + const generator = new GeneratorProcess(path.join(__dirname, 'exiting-executable')) await generator.init() try { await generator.generate(stubOptions) @@ -60,17 +58,11 @@ describe('generatorHandler', () => { } }) test('parsing error', async () => { - const generator = new GeneratorProcess( - path.join(__dirname, 'invalid-executable'), - ) - await expect(() => generator.init()).rejects.toThrow( - `Cannot find module 'ms-node/register'`, - ) + const generator = new GeneratorProcess(path.join(__dirname, 'invalid-executable')) + await expect(() => generator.init()).rejects.toThrow(`Cannot find module 'ms-node/register'`) }) test('minimal-executable', async () => { - const generator = new GeneratorProcess( - path.join(__dirname, 'minimal-executable'), - ) + const generator = new GeneratorProcess(path.join(__dirname, 'minimal-executable')) await generator.init() const manifest = await generator.getManifest(stubOptions.generator) expect(manifest).toMatchInlineSnapshot(` @@ -96,18 +88,14 @@ describe('generatorHandler', () => { generator.stop() }) test('failing-executable', async () => { - const generator = new GeneratorProcess( - path.join(__dirname, 'failing-executable'), - ) + const generator = new GeneratorProcess(path.join(__dirname, 'failing-executable')) await generator.init() await expect(generator.getManifest(stubOptions.generator)).rejects.toThrow() await expect(generator.generate(stubOptions)).rejects.toThrow() generator.stop() }) test('non existent executable', async () => { - const generator = new GeneratorProcess( - path.join(__dirname, 'random path that doesnt exist'), - ) + const generator = new GeneratorProcess(path.join(__dirname, 'random path that doesnt exist')) await expect(() => generator.init()).rejects.toThrow() }) }) diff --git a/packages/generator-helper/src/dmmf.ts b/packages/generator-helper/src/dmmf.ts index 3aec245fe142..cf5b5cfa8513 100644 --- a/packages/generator-helper/src/dmmf.ts +++ b/packages/generator-helper/src/dmmf.ts @@ -65,11 +65,7 @@ export namespace DMMF { export type FieldKind = 'scalar' | 'object' | 'enum' | 'unsupported' export type FieldNamespace = 'model' | 'prisma' - export type FieldLocation = - | 'scalar' - | 'inputObjectTypes' - | 'outputObjectTypes' - | 'enumTypes' + export type FieldLocation = 'scalar' | 'inputObjectTypes' | 'outputObjectTypes' | 'enumTypes' export interface Field { kind: FieldKind diff --git a/packages/generator-helper/src/generatorHandler.ts b/packages/generator-helper/src/generatorHandler.ts index 1168c0d9a6b9..e2f5be98af3e 100644 --- a/packages/generator-helper/src/generatorHandler.ts +++ b/packages/generator-helper/src/generatorHandler.ts @@ -1,9 +1,4 @@ -import type { - GeneratorOptions, - GeneratorManifest, - JsonRPC, - GeneratorConfig, -} from './types' +import type { GeneratorOptions, GeneratorManifest, JsonRPC, GeneratorConfig } from './types' import byline from './byline' export interface Handler { diff --git a/packages/generator-helper/src/types.ts b/packages/generator-helper/src/types.ts index 34ee1a9e741e..2b80feb32fbf 100644 --- a/packages/generator-helper/src/types.ts +++ b/packages/generator-helper/src/types.ts @@ -51,12 +51,7 @@ export interface BinaryTargetsEnvValue { value: string } -export type ConnectorType = - | 'mysql' - | 'mongodb' - | 'sqlite' - | 'postgresql' - | 'sqlserver' +export type ConnectorType = 'mysql' | 'mongodb' | 'sqlite' | 'postgresql' | 'sqlserver' export interface DataSource { name: string @@ -88,12 +83,7 @@ export type GeneratorOptions = { binaryPaths?: BinaryPaths } -export type EngineType = - | 'queryEngine' - | 'libqueryEngine' - | 'migrationEngine' - | 'introspectionEngine' - | 'prismaFmt' +export type EngineType = 'queryEngine' | 'libqueryEngine' | 'migrationEngine' | 'introspectionEngine' | 'prismaFmt' export type GeneratorManifest = { prettyName?: string diff --git a/packages/integration-tests/.prettierrc.yml b/packages/integration-tests/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/integration-tests/.prettierrc.yml +++ b/packages/integration-tests/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/integration-tests/src/__tests__/__helpers__/context.ts b/packages/integration-tests/src/__tests__/__helpers__/context.ts index 0f3f12d63fc5..b9cd3c490b3b 100644 --- a/packages/integration-tests/src/__tests__/__helpers__/context.ts +++ b/packages/integration-tests/src/__tests__/__helpers__/context.ts @@ -51,14 +51,10 @@ export const Context = { c.mocked = c.mocked ?? {} c.mocked.cwd = process.cwd() c.cli = (...input) => { - return execa.node( - path.join(__dirname, '../../../build/index.js'), - input, - { - cwd: c.fs.cwd(), - stdio: 'pipe', - }, - ) + return execa.node(path.join(__dirname, '../../../build/index.js'), input, { + cwd: c.fs.cwd(), + stdio: 'pipe', + }) } process.chdir(c.tmpDir) }) @@ -74,10 +70,9 @@ export const Context = { /** * Factory for creating a context contributor possibly configured in some special way. */ -type ContextContributorFactory = - Settings extends {} - ? () => ContextContributor - : (settings: Settings) => ContextContributor +type ContextContributorFactory = Settings extends {} + ? () => ContextContributor + : (settings: Settings) => ContextContributor /** * A function that provides additonal test context. @@ -89,9 +84,7 @@ type ContextContributor = (ctx: Context) => NewContext */ function factory(ctx: Context) { return { - add( - contextContributor: ContextContributor, - ) { + add(contextContributor: ContextContributor) { contextContributor(ctx) return factory(ctx as any) }, @@ -115,12 +108,8 @@ export const consoleContext: ContextContributorFactory< } > = () => (ctx) => { beforeEach(() => { - ctx.mocked['console.error'] = jest - .spyOn(console, 'error') - .mockImplementation(() => {}) - ctx.mocked['console.log'] = jest - .spyOn(console, 'log') - .mockImplementation(() => {}) + ctx.mocked['console.error'] = jest.spyOn(console, 'error').mockImplementation(() => {}) + ctx.mocked['console.log'] = jest.spyOn(console, 'log').mockImplementation(() => {}) }) afterEach(() => { diff --git a/packages/integration-tests/src/__tests__/__helpers__/integrationTest.ts b/packages/integration-tests/src/__tests__/__helpers__/integrationTest.ts index dda82355c139..0170d2c6bc3c 100644 --- a/packages/integration-tests/src/__tests__/__helpers__/integrationTest.ts +++ b/packages/integration-tests/src/__tests__/__helpers__/integrationTest.ts @@ -87,11 +87,7 @@ type Database = { /** * Run logic before each scenario. Typically used to run scenario SQL setup against the database. */ - beforeEach: ( - db: Client, - sqlScenario: string, - ctx: Context, - ) => MaybePromise + beforeEach: (db: Client, sqlScenario: string, ctx: Context) => MaybePromise /** * At the end of _each_ test run logic */ @@ -208,11 +204,7 @@ export function introspectionIntegrationTest(input: Input) { it.each(filterTestScenarios(input.scenarios))( `${kind}: %s`, async (_, scenario) => { - const { state, introspectionResult } = await setupScenario( - kind, - input, - scenario, - ) + const { state, introspectionResult } = await setupScenario(kind, input, scenario) states[scenario.name] = state expect(introspectionResult.datamodel).toMatchSnapshot(`datamodel`) @@ -260,10 +252,7 @@ export function runtimeIntegrationTest(input: Input) { ) } -function afterAllScenarios( - kind: string, - states: Record, -) { +function afterAllScenarios(kind: string, states: Record) { engine.stop() Object.values(states).forEach(async (state) => { // props might be missing if test errors out before they are set. @@ -344,10 +333,7 @@ async function teardownScenario(state: ScenarioState) { } if (errors.length) { - throw new VError( - new MultiError(errors), - 'Got Errors while running scenario teardown', - ) + throw new VError(new MultiError(errors), 'Got Errors while running scenario teardown') } } @@ -361,23 +347,14 @@ function filterTestScenarios(scenarios: Scenario[]): [string, Scenario][] { return onlys.map((scenario) => [scenario.name, scenario]) } - return scenarios - .filter((scenario) => scenario.todo !== true) - .map((scenario) => [scenario.name, scenario]) + return scenarios.filter((scenario) => scenario.todo !== true).map((scenario) => [scenario.name, scenario]) } /** * Get the temporary directory for the scenario */ -function getScenarioDir( - databaseName: string, - testKind: string, - scenarioName: string, -) { - return path.join( - getScenariosDir(databaseName, testKind), - slugify(scenarioName), - ) +function getScenarioDir(databaseName: string, testKind: string, scenarioName: string) { + return path.join(getScenariosDir(databaseName, testKind), slugify(scenarioName)) } /** @@ -385,10 +362,7 @@ function getScenarioDir( */ function getScenariosDir(databaseName: string, testKind: string) { // use tmp dir instead, as that often times is ramdisk - return path.join( - '/tmp/prisma-tests', - `integration-test-${databaseName}-${testKind}`, - ) + return path.join('/tmp/prisma-tests', `integration-test-${databaseName}-${testKind}`) } /** @@ -408,9 +382,7 @@ function makeDatasourceBlock(providerName: string, url: string) { */ function renderPreviewFeatures(featureMatrix: PreviewFeature[] | undefined) { if (featureMatrix) { - return `previewFeatures = [${featureMatrix.map( - (feature) => `"` + feature + `"`, - )}]` + return `previewFeatures = [${featureMatrix.map((feature) => `"` + feature + `"`)}]` } return '' } diff --git a/packages/integration-tests/src/__tests__/__helpers__/snapshotSerializer.ts b/packages/integration-tests/src/__tests__/__helpers__/snapshotSerializer.ts index 37267b5af3bb..c392c2ccd51c 100644 --- a/packages/integration-tests/src/__tests__/__helpers__/snapshotSerializer.ts +++ b/packages/integration-tests/src/__tests__/__helpers__/snapshotSerializer.ts @@ -18,16 +18,11 @@ function removePlatforms(str) { } function normalizeGithubLinks(str) { - return str.replace( - /https:\/\/github.com\/prisma\/prisma-client-js\/issues\/\S+/, - 'TEST_GITHUB_LINK', - ) + return str.replace(/https:\/\/github.com\/prisma\/prisma-client-js\/issues\/\S+/, 'TEST_GITHUB_LINK') } function normalizeRustError(str) { - return str - .replace(/\/rustc\/(.+)\//g, '/rustc/hash/') - .replace(/(\[.*)(:\d*:\d*)(\])/g, '[/some/rust/path:0:0$3') + return str.replace(/\/rustc\/(.+)\//g, '/rustc/hash/').replace(/(\[.*)(:\d*:\d*)(\])/g, '[/some/rust/path:0:0$3') } function normalizeTmpDir(str) { @@ -61,21 +56,12 @@ export function test(value) { } export function serialize(value) { - const message = - typeof value === 'string' - ? value - : value instanceof Error - ? value.message - : '' + const message = typeof value === 'string' ? value : value instanceof Error ? value.message : '' return prepareSchemaForSnapshot( normalizeGithubLinks( normalizeRustError( normalizeTmpDir( - normalizeGithubLinks( - normalizeToUnixPaths( - removePlatforms(trimErrorPaths(stripAnsi(message))), - ), - ), + normalizeGithubLinks(normalizeToUnixPaths(removePlatforms(trimErrorPaths(stripAnsi(message))))), ), ), ), diff --git a/packages/integration-tests/src/__tests__/integration/mariadb/__database.ts b/packages/integration-tests/src/__tests__/integration/mariadb/__database.ts index 25d85aaa850e..321747323bb6 100644 --- a/packages/integration-tests/src/__tests__/integration/mariadb/__database.ts +++ b/packages/integration-tests/src/__tests__/integration/mariadb/__database.ts @@ -29,8 +29,7 @@ export const database = { } as Input['database'] function getConnectionInfo(ctx: Context) { - const serviceConnectionString = - process.env.TEST_MARIADB_BASE_URI || 'mysql://root:root@localhost:4306' + const serviceConnectionString = process.env.TEST_MARIADB_BASE_URI || 'mysql://root:root@localhost:4306' const connectionString = `${serviceConnectionString}/${ctx.id}` const credentials = uriToCredentials(connectionString) diff --git a/packages/integration-tests/src/__tests__/integration/mariadb/__scenarios.ts b/packages/integration-tests/src/__tests__/integration/mariadb/__scenarios.ts index d3dbe0dd369b..43606196a1f9 100644 --- a/packages/integration-tests/src/__tests__/integration/mariadb/__scenarios.ts +++ b/packages/integration-tests/src/__tests__/integration/mariadb/__scenarios.ts @@ -462,9 +462,7 @@ export const scenarios = [ `, do: (client) => { - return client.users - .findUnique({ where: { email: 'ada@prisma.io' } }) - .posts() + return client.users.findUnique({ where: { email: 'ada@prisma.io' } }).posts() }, expect: [ { diff --git a/packages/integration-tests/src/__tests__/integration/mssql/__database.ts b/packages/integration-tests/src/__tests__/integration/mssql/__database.ts index 94f15eab1e2c..490e0641e9b5 100644 --- a/packages/integration-tests/src/__tests__/integration/mssql/__database.ts +++ b/packages/integration-tests/src/__tests__/integration/mssql/__database.ts @@ -31,9 +31,7 @@ export const database = { function getConnectionInfo(ctx: Context) { const { URL } = url - const serviceConnectionString = - process.env.TEST_MSSQL_URI || - 'mssql://SA:Pr1sm4_Pr1sm4@localhost:1433/master' + const serviceConnectionString = process.env.TEST_MSSQL_URI || 'mssql://SA:Pr1sm4_Pr1sm4@localhost:1433/master' const connectionUrl = new URL(serviceConnectionString) const connectionString = `sqlserver://${connectionUrl.host};database=master_${ctx.id};user=SA;password=Pr1sm4_Pr1sm4;trustServerCertificate=true;` const credentials = { diff --git a/packages/integration-tests/src/__tests__/integration/mssql/__scenarios.ts b/packages/integration-tests/src/__tests__/integration/mssql/__scenarios.ts index 6fee9df271fd..666654f8a58a 100644 --- a/packages/integration-tests/src/__tests__/integration/mssql/__scenarios.ts +++ b/packages/integration-tests/src/__tests__/integration/mssql/__scenarios.ts @@ -440,9 +440,7 @@ export const scenarios = [ insert into posts ("user_id", "title") values (2, 'C'); `, do: (client) => { - return client.users - .findUnique({ where: { email: 'ada@prisma.io' } }) - .posts() + return client.users.findUnique({ where: { email: 'ada@prisma.io' } }).posts() }, expect: [ { diff --git a/packages/integration-tests/src/__tests__/integration/mssql/introspection.test.ts b/packages/integration-tests/src/__tests__/integration/mssql/introspection.test.ts index b53a633c1e76..982436d9d582 100644 --- a/packages/integration-tests/src/__tests__/integration/mssql/introspection.test.ts +++ b/packages/integration-tests/src/__tests__/integration/mssql/introspection.test.ts @@ -1,7 +1,4 @@ -import { - introspectionIntegrationTest, - Input, -} from '../../__helpers__/integrationTest' +import { introspectionIntegrationTest, Input } from '../../__helpers__/integrationTest' import { database } from './__database' import { scenarios } from './__scenarios' diff --git a/packages/integration-tests/src/__tests__/integration/mysql/__database.ts b/packages/integration-tests/src/__tests__/integration/mysql/__database.ts index 4587ea999757..fdae3ec50f4d 100644 --- a/packages/integration-tests/src/__tests__/integration/mysql/__database.ts +++ b/packages/integration-tests/src/__tests__/integration/mysql/__database.ts @@ -28,8 +28,7 @@ export const database = { } as Input['database'] function getConnectionInfo(ctx: Context) { - const serviceConnectionString = - process.env.TEST_MYSQL_BASE_URI || 'mysql://root:root@localhost:3306' + const serviceConnectionString = process.env.TEST_MYSQL_BASE_URI || 'mysql://root:root@localhost:3306' const connectionString = `${serviceConnectionString}/${ctx.id}` const credentials = uriToCredentials(connectionString) diff --git a/packages/integration-tests/src/__tests__/integration/mysql/__scenarios.ts b/packages/integration-tests/src/__tests__/integration/mysql/__scenarios.ts index ab6c1fe04220..120c2967f073 100644 --- a/packages/integration-tests/src/__tests__/integration/mysql/__scenarios.ts +++ b/packages/integration-tests/src/__tests__/integration/mysql/__scenarios.ts @@ -439,9 +439,7 @@ export const scenarios = [ insert into posts (user_id, title) values (2, 'C'); `, do: (client) => { - return client.users - .findUnique({ where: { email: 'ada@prisma.io' } }) - .posts() + return client.users.findUnique({ where: { email: 'ada@prisma.io' } }).posts() }, expect: [ { diff --git a/packages/integration-tests/src/__tests__/integration/postgresql/__database.ts b/packages/integration-tests/src/__tests__/integration/postgresql/__database.ts index c432125bb20d..510bd650fce6 100644 --- a/packages/integration-tests/src/__tests__/integration/postgresql/__database.ts +++ b/packages/integration-tests/src/__tests__/integration/postgresql/__database.ts @@ -23,9 +23,7 @@ export const database = { } as Input['database'] function getConnectionString(ctx: Context) { - const serviceConnectionString = - process.env.TEST_POSTGRES_BASE_URI || - 'postgres://prisma:prisma@localhost:5432' + const serviceConnectionString = process.env.TEST_POSTGRES_BASE_URI || 'postgres://prisma:prisma@localhost:5432' const connectionString = `${serviceConnectionString}/tests?schema=${ctx.id}&connection_limit=1` return connectionString } diff --git a/packages/integration-tests/src/__tests__/integration/postgresql/__scenarios.ts b/packages/integration-tests/src/__tests__/integration/postgresql/__scenarios.ts index 3b7781c1ce68..49a0992f14d7 100644 --- a/packages/integration-tests/src/__tests__/integration/postgresql/__scenarios.ts +++ b/packages/integration-tests/src/__tests__/integration/postgresql/__scenarios.ts @@ -437,9 +437,7 @@ export const scenarios = [ insert into posts ("user_id", "title") values (2, 'C'); `, do: (client) => { - return client.users - .findUnique({ where: { email: 'ada@prisma.io' } }) - .posts() + return client.users.findUnique({ where: { email: 'ada@prisma.io' } }).posts() }, expect: [ { diff --git a/packages/integration-tests/src/__tests__/integration/sqlite/__scenarios.ts b/packages/integration-tests/src/__tests__/integration/sqlite/__scenarios.ts index bf1bc65a1c83..be755eca5ad7 100644 --- a/packages/integration-tests/src/__tests__/integration/sqlite/__scenarios.ts +++ b/packages/integration-tests/src/__tests__/integration/sqlite/__scenarios.ts @@ -444,9 +444,7 @@ export const scenarios = [ insert into posts ("user_id", "title") values (2, 'C'); `, do: (client) => { - return client.users - .findUnique({ where: { email: 'ada@prisma.io' } }) - .posts() + return client.users.findUnique({ where: { email: 'ada@prisma.io' } }).posts() }, expect: [ { diff --git a/packages/migrate/.prettierrc.yml b/packages/migrate/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/migrate/.prettierrc.yml +++ b/packages/migrate/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/migrate/src/Migrate.ts b/packages/migrate/src/Migrate.ts index b156819ef5bf..3dbfd50192ae 100644 --- a/packages/migrate/src/Migrate.ts +++ b/packages/migrate/src/Migrate.ts @@ -23,10 +23,7 @@ export class Migrate { public migrationsDirectoryPath: string constructor(schemaPath?: string, enabledPreviewFeatures?: string[]) { this.schemaPath = this.getSchemaPath(schemaPath) - this.migrationsDirectoryPath = path.join( - path.dirname(this.schemaPath), - 'migrations', - ) + this.migrationsDirectoryPath = path.join(path.dirname(this.schemaPath), 'migrations') this.engine = new MigrateEngine({ projectDir: path.dirname(this.schemaPath), schemaPath: this.schemaPath, @@ -56,9 +53,7 @@ export class Migrate { return this.engine.reset() } - public createMigration( - params: EngineArgs.CreateMigrationInput, - ): Promise { + public createMigration(params: EngineArgs.CreateMigrationInput): Promise { return this.engine.createMigration(params) } @@ -85,22 +80,14 @@ export class Migrate { }) } - public async markMigrationApplied({ - migrationId, - }: { - migrationId: string - }): Promise { + public async markMigrationApplied({ migrationId }: { migrationId: string }): Promise { return await this.engine.markMigrationApplied({ migrationsDirectoryPath: this.migrationsDirectoryPath, migrationName: migrationId, }) } - public markMigrationRolledBack({ - migrationId, - }: { - migrationId: string - }): Promise { + public markMigrationRolledBack({ migrationId }: { migrationId: string }): Promise { return this.engine.markMigrationRolledBack({ migrationName: migrationId, }) @@ -121,18 +108,13 @@ export class Migrate { }) } - public async push({ - force = false, - }: { - force?: boolean - }): Promise { + public async push({ force = false }: { force?: boolean }): Promise { const datamodel = this.getDatamodel() - const { warnings, unexecutable, executedSteps } = - await this.engine.schemaPush({ - force, - schema: datamodel, - }) + const { warnings, unexecutable, executedSteps } = await this.engine.schemaPush({ + force, + schema: datamodel, + }) return { executedSteps, @@ -145,11 +127,7 @@ export class Migrate { const message: string[] = [] console.info() // empty line - logUpdate( - `Running generate... ${chalk.dim( - '(Use --skip-generate to skip the generators)', - )}`, - ) + logUpdate(`Running generate... ${chalk.dim('(Use --skip-generate to skip the generators)')}`) const generators = await getGenerators({ schemaPath: this.schemaPath, @@ -161,10 +139,7 @@ export class Migrate { for (const generator of generators) { const toStr = generator.options!.generator.output! ? chalk.dim( - ` to .${path.sep}${path.relative( - process.cwd(), - parseEnvValue(generator.options!.generator.output), - )}`, + ` to .${path.sep}${path.relative(process.cwd(), parseEnvValue(generator.options!.generator.output))}`, ) : '' const name = generator.manifest @@ -179,9 +154,7 @@ export class Migrate { const after = Date.now() const version = generator.manifest?.version message.push( - `āœ” Generated ${chalk.bold(name!)}${ - version ? ` (${version})` : '' - }${toStr} in ${formatms(after - before)}`, + `āœ” Generated ${chalk.bold(name!)}${version ? ` (${version})` : ''}${toStr} in ${formatms(after - before)}`, ) generator.stop() } catch (e: any) { diff --git a/packages/migrate/src/MigrateEngine.ts b/packages/migrate/src/MigrateEngine.ts index 9463bd9e934b..3745c917e13d 100644 --- a/packages/migrate/src/MigrateEngine.ts +++ b/packages/migrate/src/MigrateEngine.ts @@ -1,12 +1,6 @@ import Debug from '@prisma/debug' import type { MigrateEngineLogLine } from '@prisma/sdk' -import { - BinaryType, - ErrorArea, - resolveBinary, - RustPanic, - MigrateEngineExitCode, -} from '@prisma/sdk' +import { BinaryType, ErrorArea, resolveBinary, RustPanic, MigrateEngineExitCode } from '@prisma/sdk' import chalk from 'chalk' import type { ChildProcess } from 'child_process' import { spawn } from 'child_process' @@ -54,12 +48,7 @@ export class MigrateEngine { private lastError: MigrateEngineLogLine['fields'] | null = null private initPromise?: Promise private enabledPreviewFeatures?: string[] - constructor({ - projectDir, - debug = false, - schemaPath, - enabledPreviewFeatures, - }: MigrateEngineOptions) { + constructor({ projectDir, debug = false, schemaPath, enabledPreviewFeatures }: MigrateEngineOptions) { this.projectDir = projectDir this.schemaPath = schemaPath if (debug) { @@ -74,9 +63,7 @@ export class MigrateEngine { /* eslint-disable @typescript-eslint/no-unsafe-return */ // Runs dev diagnostic - public devDiagnostic( - args: EngineArgs.DevDiagnosticInput, - ): Promise { + public devDiagnostic(args: EngineArgs.DevDiagnosticInput): Promise { return this.runCommand(this.getRPCPayload('devDiagnostic', args)) } // List migrations in migration directory. @@ -89,15 +76,11 @@ export class MigrateEngine { // - The migration is already in the table, but in a failed state. In this case, we will mark it as rolled back, then create a new entry. // - The migration is not in the table. We will create a new entry in the migrations table. The `started_at` and `finished_at` will be the same. // - If it is already applied, we return a user-facing error. - public markMigrationApplied( - args: EngineArgs.MarkMigrationAppliedInput, - ): Promise { + public markMigrationApplied(args: EngineArgs.MarkMigrationAppliedInput): Promise { return this.runCommand(this.getRPCPayload('markMigrationApplied', args)) } // Mark an existing failed migration as rolled back in the migrations table. It will still be there, but ignored for all purposes except as audit trail. - public markMigrationRolledBack( - args: EngineArgs.MarkMigrationRolledBackInput, - ): Promise { + public markMigrationRolledBack(args: EngineArgs.MarkMigrationRolledBackInput): Promise { return this.runCommand(this.getRPCPayload('markMigrationRolledBack', args)) } public diagnoseMigrationHistory( @@ -105,24 +88,16 @@ export class MigrateEngine { ): Promise { return this.runCommand(this.getRPCPayload('diagnoseMigrationHistory', args)) } - public planMigration( - args: EngineArgs.PlanMigrationInput, - ): Promise { + public planMigration(args: EngineArgs.PlanMigrationInput): Promise { return this.runCommand(this.getRPCPayload('planMigration', args)) } - public evaluateDataLoss( - args: EngineArgs.EvaluateDataLossInput, - ): Promise { + public evaluateDataLoss(args: EngineArgs.EvaluateDataLossInput): Promise { return this.runCommand(this.getRPCPayload('evaluateDataLoss', args)) } - public createMigration( - args: EngineArgs.CreateMigrationInput, - ): Promise { + public createMigration(args: EngineArgs.CreateMigrationInput): Promise { return this.runCommand(this.getRPCPayload('createMigration', args)) } - public applyMigrations( - args: EngineArgs.ApplyMigrationsInput, - ): Promise { + public applyMigrations(args: EngineArgs.ApplyMigrationsInput): Promise { return this.runCommand(this.getRPCPayload('applyMigrations', args)) } public reset(): Promise { @@ -131,9 +106,7 @@ export class MigrateEngine { public getDatabaseVersion(): Promise { return this.runCommand(this.getRPCPayload('getDatabaseVersion', undefined)) } - public schemaPush( - args: EngineArgs.SchemaPush, - ): Promise { + public schemaPush(args: EngineArgs.SchemaPush): Promise { return this.runCommand(this.getRPCPayload('schemaPush', args)) } public debugPanic(): Promise { @@ -147,10 +120,7 @@ export class MigrateEngine { delete this.listeners[id] }) } - private registerCallback( - id: number, - callback: (result: any, err?: Error) => any, - ): void { + private registerCallback(id: number, callback: (result: any, err?: Error) => any): void { this.listeners[id] = callback } private handleResponse(response: any): void { @@ -158,9 +128,7 @@ export class MigrateEngine { try { result = JSON.parse(response) } catch (e) { - console.error( - `Could not parse migration engine response: ${response.slice(0, 200)}`, - ) + console.error(`Could not parse migration engine response: ${response.slice(0, 200)}`) } if (result) { if (result.id) { @@ -204,12 +172,7 @@ export class MigrateEngine { Array.isArray(this.enabledPreviewFeatures) && this.enabledPreviewFeatures.length > 0 ) { - args.push( - ...[ - '--enabled-preview-features', - this.enabledPreviewFeatures.join(','), - ], - ) + args.push(...['--enabled-preview-features', this.enabledPreviewFeatures.join(',')]) } this.child = spawn(binaryPath, args, { cwd: this.projectDir, @@ -233,8 +196,7 @@ export class MigrateEngine { this.rejectAll(err) reject(err) } - const engineMessage = - this.lastError?.message || this.messages.join('\n') + const engineMessage = this.lastError?.message || this.messages.join('\n') const handlePanic = () => { const stackTrace = this.messages.join('\n') exitWithErr( @@ -252,9 +214,7 @@ export class MigrateEngine { case MigrateEngineExitCode.Success: break case MigrateEngineExitCode.Error: - exitWithErr( - new Error(`Error in migration engine: ${engineMessage}`), - ) + exitWithErr(new Error(`Error in migration engine: ${engineMessage}`)) break case MigrateEngineExitCode.Panic: handlePanic() @@ -308,11 +268,7 @@ export class MigrateEngine { } await this.init() if (this.child?.killed) { - throw new Error( - `Can't execute ${JSON.stringify( - request, - )} because migration engine already exited.`, - ) + throw new Error(`Can't execute ${JSON.stringify(request)} because migration engine already exited.`) } return new Promise((resolve, reject) => { this.registerCallback(request.id, (response, err) => { @@ -327,8 +283,7 @@ export class MigrateEngine { debugRpc(response) if (response.error.data?.is_panic) { // if (response.error.data && response.error.data.message) { - const message = - response.error.data?.error?.message ?? response.error.message + const message = response.error.data?.error?.message ?? response.error.message reject( // Handle error and displays the interactive dialog to send panic error new RustPanic( @@ -344,9 +299,7 @@ export class MigrateEngine { // See known errors at https://github.com/prisma/specs/tree/master/errors#prisma-sdk let message = `${chalk.redBright(response.error.data.message)}\n` if (response.error.data?.error_code) { - message = - chalk.redBright(`${response.error.data.error_code}\n\n`) + - message + message = chalk.redBright(`${response.error.data.error_code}\n\n`) + message reject(new EngineError(message, response.error.data.error_code)) } else { reject(new Error(message)) @@ -354,35 +307,21 @@ export class MigrateEngine { } else { reject( new Error( - `${chalk.redBright( - 'Error in RPC', - )}\n Request: ${JSON.stringify( + `${chalk.redBright('Error in RPC')}\n Request: ${JSON.stringify( request, null, 2, - )}\nResponse: ${JSON.stringify(response, null, 2)}\n${ - response.error.message - }\n`, + )}\nResponse: ${JSON.stringify(response, null, 2)}\n${response.error.message}\n`, ), ) } } else { - reject( - new Error( - `Got invalid RPC response without .result property: ${JSON.stringify( - response, - )}`, - ), - ) + reject(new Error(`Got invalid RPC response without .result property: ${JSON.stringify(response)}`)) } } }) if (this.child!.stdin!.destroyed) { - throw new Error( - `Can't execute ${JSON.stringify( - request, - )} because migration engine is destroyed.`, - ) + throw new Error(`Can't execute ${JSON.stringify(request)} because migration engine is destroyed.`) } debugRpc('SENDING RPC CALL', JSON.stringify(request)) this.child!.stdin!.write(JSON.stringify(request) + '\n') diff --git a/packages/migrate/src/__tests__/__helpers__/context.ts b/packages/migrate/src/__tests__/__helpers__/context.ts index c00d7d1b8686..edd57927cc23 100644 --- a/packages/migrate/src/__tests__/__helpers__/context.ts +++ b/packages/migrate/src/__tests__/__helpers__/context.ts @@ -51,14 +51,10 @@ export const Context = { c.mocked = c.mocked ?? {} c.mocked.cwd = process.cwd() c.cli = (...input) => { - return execa.node( - Path.join(__dirname, '../../../build/index.js'), - input, - { - cwd: c.fs.cwd(), - stdio: 'pipe', - }, - ) + return execa.node(Path.join(__dirname, '../../../build/index.js'), input, { + cwd: c.fs.cwd(), + stdio: 'pipe', + }) } process.chdir(c.tmpDir) }) @@ -74,10 +70,9 @@ export const Context = { /** * Factory for creating a context contributor possibly configured in some special way. */ -type ContextContributorFactory = - Settings extends {} - ? () => ContextContributor - : (settings: Settings) => ContextContributor +type ContextContributorFactory = Settings extends {} + ? () => ContextContributor + : (settings: Settings) => ContextContributor /** * A function that provides additonal test context. @@ -89,9 +84,7 @@ type ContextContributor = (ctx: Context) => NewContext */ function factory(ctx: Context) { return { - add( - contextContributor: ContextContributor, - ) { + add(contextContributor: ContextContributor) { contextContributor(ctx) return factory(ctx as any) }, @@ -117,18 +110,10 @@ export const consoleContext: ContextContributorFactory< } > = () => (ctx) => { beforeEach(() => { - ctx.mocked['console.error'] = jest - .spyOn(console, 'error') - .mockImplementation(() => {}) - ctx.mocked['console.log'] = jest - .spyOn(console, 'log') - .mockImplementation(() => {}) - ctx.mocked['console.info'] = jest - .spyOn(console, 'info') - .mockImplementation(() => {}) - ctx.mocked['console.warn'] = jest - .spyOn(console, 'warn') - .mockImplementation(() => {}) + ctx.mocked['console.error'] = jest.spyOn(console, 'error').mockImplementation(() => {}) + ctx.mocked['console.log'] = jest.spyOn(console, 'log').mockImplementation(() => {}) + ctx.mocked['console.info'] = jest.spyOn(console, 'info').mockImplementation(() => {}) + ctx.mocked['console.warn'] = jest.spyOn(console, 'warn').mockImplementation(() => {}) }) afterEach(() => { diff --git a/packages/migrate/src/__tests__/__helpers__/snapshotSerializer.ts b/packages/migrate/src/__tests__/__helpers__/snapshotSerializer.ts index 10d92d3a91b9..d87644f12d6d 100644 --- a/packages/migrate/src/__tests__/__helpers__/snapshotSerializer.ts +++ b/packages/migrate/src/__tests__/__helpers__/snapshotSerializer.ts @@ -9,9 +9,7 @@ function normalizeDbUrl(str) { } function normalizeRustError(str) { - return str - .replace(/\/rustc\/(.+)\//g, '/rustc/hash/') - .replace(/(\[.*)(:\d*:\d*)(\])/g, '[/some/rust/path:0:0$3') + return str.replace(/\/rustc\/(.+)\//g, '/rustc/hash/').replace(/(\[.*)(:\d*:\d*)(\])/g, '[/some/rust/path:0:0$3') } function normalizeTime(str: string): string { @@ -24,15 +22,6 @@ export function test(value) { } export function serialize(value) { - const message = - typeof value === 'string' - ? value - : value instanceof Error - ? value.message - : '' - return normalizeDbUrl( - normalizeTime( - normalizeRustError(normalizeMigrateTimestamps(stripAnsi(message))), - ), - ) + const message = typeof value === 'string' ? value : value instanceof Error ? value.message : '' + return normalizeDbUrl(normalizeTime(normalizeRustError(normalizeMigrateTimestamps(stripAnsi(message))))) } diff --git a/packages/migrate/src/bin.ts b/packages/migrate/src/bin.ts index b7662ac56403..9237d305a314 100755 --- a/packages/migrate/src/bin.ts +++ b/packages/migrate/src/bin.ts @@ -104,12 +104,7 @@ main() }) .catch((error) => { if (error.rustStack) { - handlePanic( - error, - packageJson.version, - enginesVersion, - commandArray.join(' '), - ) + handlePanic(error, packageJson.version, enginesVersion, commandArray.join(' ')) .catch((e) => { if (Debug.enabled('migrate')) { console.error(chalk.redBright.bold('Error: ') + e.stack) diff --git a/packages/migrate/src/commands/DbCommand.ts b/packages/migrate/src/commands/DbCommand.ts index c5d945402e76..63d877cd6e5d 100644 --- a/packages/migrate/src/commands/DbCommand.ts +++ b/packages/migrate/src/commands/DbCommand.ts @@ -8,9 +8,7 @@ export class DbCommand implements Command { } private static help = format(` -${ - process.platform === 'win32' ? '' : chalk.bold('šŸ‹ļø ') -}Manage your database schema and lifecycle during development. +${process.platform === 'win32' ? '' : chalk.bold('šŸ‹ļø ')}Manage your database schema and lifecycle during development. ${chalk.bold('Usage')} @@ -61,9 +59,7 @@ ${chalk.bold('Examples')} // check if we have that subcommand const cmd = this.cmds[args._[0]] if (cmd) { - const argsForCmd = args['--preview-feature'] - ? [...args._.slice(1), `--preview-feature`] - : args._.slice(1) + const argsForCmd = args['--preview-feature'] ? [...args._.slice(1), `--preview-feature`] : args._.slice(1) return cmd.parse(argsForCmd) } @@ -72,9 +68,7 @@ ${chalk.bold('Examples')} public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${DbCommand.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${DbCommand.help}`) } return DbCommand.help } diff --git a/packages/migrate/src/commands/DbDrop.ts b/packages/migrate/src/commands/DbDrop.ts index a619175e5175..6e8b855fea33 100644 --- a/packages/migrate/src/commands/DbDrop.ts +++ b/packages/migrate/src/commands/DbDrop.ts @@ -1,15 +1,5 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getSchemaPath, - getSchemaDir, - HelpError, - isError, - isCi, - dropDatabase, - link, -} from '@prisma/sdk' +import { arg, format, getSchemaPath, getSchemaDir, HelpError, isError, isCi, dropDatabase, link } from '@prisma/sdk' import path from 'path' import chalk from 'chalk' import prompt from 'prompts' @@ -27,14 +17,10 @@ export class DbDrop implements Command { ${process.platform === 'win32' ? '' : chalk.bold('šŸ’£ ')}Drop the database ${chalk.bold.yellow('WARNING')} ${chalk.bold( - `Prisma db drop is currently in Preview (${link( - 'https://pris.ly/d/preview', - )}). + `Prisma db drop is currently in Preview (${link('https://pris.ly/d/preview')}). There may be bugs and it's not recommended to use it in production environments.`, )} -${chalk.dim( - 'When using any of the subcommands below you need to explicitly opt-in via the --preview-feature flag.', -)} +${chalk.dim('When using any of the subcommands below you need to explicitly opt-in via the --preview-feature flag.')} ${chalk.bold('Usage')} @@ -87,11 +73,7 @@ ${chalk.bold('Examples')} throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -110,11 +92,9 @@ ${chalk.bold('Examples')} const confirmation = await prompt({ type: 'text', name: 'value', - message: `Enter the ${dbInfo.dbType} ${dbInfo.schemaWord} name "${ - dbInfo.dbName - }" to drop it.\nLocation: "${dbInfo.dbLocation}".\n${chalk.red( - 'All data will be lost', - )}.`, + message: `Enter the ${dbInfo.dbType} ${dbInfo.schemaWord} name "${dbInfo.dbName}" to drop it.\nLocation: "${ + dbInfo.dbLocation + }".\n${chalk.red('All data will be lost')}.`, }) console.info() // empty line @@ -122,18 +102,14 @@ ${chalk.bold('Examples')} console.info('Drop cancelled.') process.exit(0) } else if (confirmation.value !== dbInfo.dbName) { - throw Error( - `The ${dbInfo.schemaWord} name entered "${confirmation.value}" doesn't match "${dbInfo.dbName}".`, - ) + throw Error(`The ${dbInfo.schemaWord} name entered "${confirmation.value}" doesn't match "${dbInfo.dbName}".`) } } if (await dropDatabase(dbInfo.url, schemaDir)) { - return `${process.platform === 'win32' ? '' : 'šŸš€ '}The ${ - dbInfo.dbType - } ${dbInfo.schemaWord} "${dbInfo.dbName}" from "${ - dbInfo.dbLocation - }" was successfully dropped.\n` + return `${process.platform === 'win32' ? '' : 'šŸš€ '}The ${dbInfo.dbType} ${dbInfo.schemaWord} "${ + dbInfo.dbName + }" from "${dbInfo.dbLocation}" was successfully dropped.\n` } else { return '' } diff --git a/packages/migrate/src/commands/DbPull.ts b/packages/migrate/src/commands/DbPull.ts index f83d4b3c89f5..ac61a68095f2 100644 --- a/packages/migrate/src/commands/DbPull.ts +++ b/packages/migrate/src/commands/DbPull.ts @@ -12,10 +12,7 @@ import { } from '@prisma/sdk' import chalk from 'chalk' import path from 'path' -import type { - IntrospectionWarnings, - IntrospectionSchemaVersion, -} from '@prisma/sdk' +import type { IntrospectionWarnings, IntrospectionSchemaVersion } from '@prisma/sdk' import { IntrospectionEngine } from '@prisma/sdk' import { formatms } from '../utils/formatms' import fs from 'fs' @@ -103,17 +100,13 @@ Instead of saving the result to the filesystem, you can also print it to stdout renamedMessages.push( `The ${chalk.redBright( '--experimental-reintrospection', - )} flag has been removed and is now the default behavior of ${chalk.greenBright( - 'prisma db pull', - )}.`, + )} flag has been removed and is now the default behavior of ${chalk.greenBright('prisma db pull')}.`, ) } if (args['--clean']) { renamedMessages.push( - `The ${chalk.redBright( - '--clean', - )} flag has been renamed to ${chalk.greenBright('--force')}.`, + `The ${chalk.redBright('--clean')} flag has been renamed to ${chalk.greenBright('--force')}.`, ) } @@ -126,14 +119,7 @@ Instead of saving the result to the filesystem, you can also print it to stdout // Do not print if --print is passed to only have the schema in stdout if (schemaPath && !args['--print']) { - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative( - process.cwd(), - schemaPath, - )}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) } @@ -162,9 +148,7 @@ Instead of saving the result to the filesystem, you can also print it to stdout const basedOn = !args['--url'] && schemaPath - ? ` based on datasource defined in ${chalk.underline( - path.relative(process.cwd(), schemaPath), - )}` + ? ` based on datasource defined in ${chalk.underline(path.relative(process.cwd(), schemaPath))}` : '' log(`\nIntrospecting${basedOn} ā€¦`) @@ -173,10 +157,7 @@ Instead of saving the result to the filesystem, you can also print it to stdout let introspectionWarnings: IntrospectionWarnings[] let introspectionSchemaVersion: IntrospectionSchemaVersion try { - const introspectionResult = await engine.introspect( - schema, - args['--force'], - ) + const introspectionResult = await engine.introspect(schema, args['--force']) introspectionSchema = introspectionResult.datamodel introspectionWarnings = introspectionResult.warnings @@ -184,13 +165,11 @@ Instead of saving the result to the filesystem, you can also print it to stdout } catch (e: any) { if (e.code === 'P4001') { if (introspectionSchema.trim() === '') { - throw new Error(`\n${chalk.red.bold('P4001 ')}${chalk.red( - 'The introspected database was empty:', - )} ${url ? chalk.underline(url) : ''} + throw new Error(`\n${chalk.red.bold('P4001 ')}${chalk.red('The introspected database was empty:')} ${ + url ? chalk.underline(url) : '' + } -${chalk.bold( - 'prisma db pull', -)} could not create any models in your ${chalk.bold( +${chalk.bold('prisma db pull')} could not create any models in your ${chalk.bold( 'schema.prisma', )} file and you will not be able to generate Prisma Client with the ${chalk.bold( getCommandWithExecutor('prisma generate'), @@ -199,23 +178,17 @@ ${chalk.bold( ${chalk.bold('To fix this, you have two options:')} - manually create a table in your database. -- make sure the database connection URL inside the ${chalk.bold( - 'datasource', - )} block in ${chalk.bold( +- make sure the database connection URL inside the ${chalk.bold('datasource')} block in ${chalk.bold( 'schema.prisma', )} points to a database that is not empty (it must contain at least one table). -Then you can run ${chalk.green( - getCommandWithExecutor('prisma db pull'), - )} again. +Then you can run ${chalk.green(getCommandWithExecutor('prisma db pull'))} again. `) } } else if (e.code === 'P1012') { // Schema Parsing Error console.info() // empty line - throw new Error(`${chalk.red( - `${e.code}`, - )} Introspection failed as your current Prisma schema file is invalid + throw new Error(`${chalk.red(`${e.code}`)} Introspection failed as your current Prisma schema file is invalid Please fix your current schema manually, use ${chalk.green( getCommandWithExecutor('prisma validate'), @@ -229,9 +202,7 @@ Or run this command with the ${chalk.green( throw e } - function getWarningMessage( - warnings: IntrospectionWarnings[], - ): string | undefined { + function getWarningMessage(warnings: IntrospectionWarnings[]): string | undefined { if (warnings.length > 0) { let message = `\n*** WARNING ***\n` @@ -241,9 +212,7 @@ Or run this command with the ${chalk.green( if (warning.code === 0) { // affected === null } else if (warning.code === 1) { - message += warning.affected - .map((it) => `- "${it.model}"`) - .join('\n') + message += warning.affected.map((it) => `- "${it.model}"`).join('\n') } else if (warning.code === 2) { const modelsGrouped: { [key: string]: string[] @@ -255,48 +224,27 @@ Or run this command with the ${chalk.green( return acc }, {}) message += Object.entries(modelsGrouped) - .map( - ([model, fields]) => - `- Model: "${model}"\n Field(s): "${fields.join('", "')}"`, - ) + .map(([model, fields]) => `- Model: "${model}"\n Field(s): "${fields.join('", "')}"`) .join('\n') } else if (warning.code === 3) { message += warning.affected - .map( - (it) => - `- Model "${it.model}", field: "${it.field}", original data type: "${it.tpe}"`, - ) + .map((it) => `- Model "${it.model}", field: "${it.field}", original data type: "${it.tpe}"`) .join('\n') } else if (warning.code === 4) { - message += warning.affected - .map((it) => `- Enum "${it.enm}", value: "${it.value}"`) - .join('\n') + message += warning.affected.map((it) => `- Enum "${it.enm}", value: "${it.value}"`).join('\n') } else if ([5, 6, 8, 11, 12, 13].includes(warning.code)) { - message += warning.affected - .map((it) => `- Model "${it.model}", field: "${it.field}"`) - .join('\n') + message += warning.affected.map((it) => `- Model "${it.model}", field: "${it.field}"`).join('\n') } else if (warning.code === 7) { - message += warning.affected - .map((it) => `- Model "${it.model}"`) - .join('\n') + message += warning.affected.map((it) => `- Model "${it.model}"`).join('\n') } else if ([9, 10].includes(warning.code)) { - message += warning.affected - .map((it) => `- Enum "${it.enm}"`) - .join('\n') + message += warning.affected.map((it) => `- Enum "${it.enm}"`).join('\n') } else if (warning.code === 101) { message += warning.affected.name - .map( - (it) => - `- Model "${it.model}", field: "${it.field}", chosen data type: "${it.tpe}"`, - ) + .map((it) => `- Model "${it.model}", field: "${it.field}", chosen data type: "${it.tpe}"`) .join('\n') } else if (warning.affected) { // Output unhandled warning - message += `Code ${warning.code}\n${JSON.stringify( - warning.affected, - null, - 2, - )}` + message += `Code ${warning.code}\n${JSON.stringify(warning.affected, null, 2)}` } message += `\n` @@ -307,23 +255,18 @@ Or run this command with the ${chalk.green( return undefined } - const introspectionWarningsMessage = - getWarningMessage(introspectionWarnings) || '' + const introspectionWarningsMessage = getWarningMessage(introspectionWarnings) || '' const prisma1UpgradeMessage = introspectionSchemaVersion.includes('Prisma1') ? `\n${chalk.bold('Upgrading from Prisma 1 to Prisma 2?')} \nThe database you introspected could belong to a Prisma 1 project. Please run the following command to upgrade to Prisma 2.0: -${chalk.green( - 'npx prisma-upgrade [path-to-prisma-yml] [path-to-schema-prisma]', -)} +${chalk.green('npx prisma-upgrade [path-to-prisma-yml] [path-to-schema-prisma]')} Note: \`prisma.yml\` and \`schema.prisma\` paths are optional. -Learn more about the upgrade process in the docs:\n${link( - 'https://pris.ly/d/upgrading-to-prisma2', - )} +Learn more about the upgrade process in the docs:\n${link('https://pris.ly/d/upgrading-to-prisma2')} ` : '' @@ -350,11 +293,7 @@ Learn more about the upgrade process in the docs:\n${link( const modelMatch = modelRegex.exec(schema) const isReintrospection = modelMatch - if ( - isReintrospection && - !args['--force'] && - config.datasources[0].provider === 'mongodb' - ) { + if (isReintrospection && !args['--force'] && config.datasources[0].provider === 'mongodb') { engine.stop() throw new Error(`Iterating on one schema using re-introspection with db pull is currently not supported with MongoDB provider (Preview). You can explicitely ignore and override your current local schema file with ${chalk.green( @@ -368,8 +307,7 @@ Some information will be lost (relations, comments, mapped fields, @ignore...), schemaPath = schemaPath || 'schema.prisma' fs.writeFileSync(schemaPath, introspectionSchema) - const modelsCount = (introspectionSchema.match(/^model\s+/gm) || []) - .length + const modelsCount = (introspectionSchema.match(/^model\s+/gm) || []).length const prisma1UpgradeMessageBox = prisma1UpgradeMessage ? '\n\n' + @@ -385,15 +323,11 @@ Some information will be lost (relations, comments, mapped fields, @ignore...), log(`\nāœ” Introspected ${modelsCount} ${ modelsCount > 1 ? 'models and wrote them' : 'model and wrote it' - } into ${chalk.underline( - path.relative(process.cwd(), schemaPath), - )} in ${chalk.bold( + } into ${chalk.underline(path.relative(process.cwd(), schemaPath))} in ${chalk.bold( formatms(Date.now() - before), )}${prisma1UpgradeMessageBox} ${chalk.keyword('orange')(introspectionWarningsMessage)} -${`Run ${chalk.green( - getCommandWithExecutor('prisma generate'), -)} to generate Prisma Client.`}`) +${`Run ${chalk.green(getCommandWithExecutor('prisma generate'))} to generate Prisma Client.`}`) } engine.stop() diff --git a/packages/migrate/src/commands/DbPush.ts b/packages/migrate/src/commands/DbPush.ts index 8db4ab75ca87..49e81fd1e66a 100644 --- a/packages/migrate/src/commands/DbPush.ts +++ b/packages/migrate/src/commands/DbPush.ts @@ -1,25 +1,12 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - HelpError, - isError, - getSchemaPath, - logger, - isCi, - getCommandWithExecutor, -} from '@prisma/sdk' +import { arg, format, HelpError, isError, getSchemaPath, logger, isCi, getCommandWithExecutor } from '@prisma/sdk' import path from 'path' import chalk from 'chalk' import prompt from 'prompts' import { Migrate } from '../Migrate' import { ensureDatabaseExists, getDbInfo } from '../utils/ensureDatabaseExists' import { formatms } from '../utils/formatms' -import { - DbPushIgnoreWarningsWithFlagError, - DbPushForceFlagRenamedError, - NoSchemaFoundError, -} from '../utils/errors' +import { DbPushIgnoreWarningsWithFlagError, DbPushForceFlagRenamedError, NoSchemaFoundError } from '../utils/errors' import { printDatasource } from '../utils/printDatasource' import type { EngineResults } from '../types' @@ -29,9 +16,7 @@ export class DbPush implements Command { } private static help = format(` -${ - process.platform === 'win32' ? '' : chalk.bold('šŸ™Œ ') -}Push the state from your Prisma schema to your database +${process.platform === 'win32' ? '' : chalk.bold('šŸ™Œ ')}Push the state from your Prisma schema to your database ${chalk.bold('Usage')} @@ -100,11 +85,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -138,9 +119,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) `The ${dbInfo.dbType} ${dbInfo.schemaWord} "${dbInfo.dbName}" from "${dbInfo.dbLocation}" was successfully reset.`, ) } else { - console.info( - `The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`, - ) + console.info(`The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`) } wasDatabaseReset = true } @@ -158,9 +137,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) if (migration.unexecutable && migration.unexecutable.length > 0) { const messages: string[] = [] - messages.push( - `${chalk.bold.red('\nāš ļø We found changes that cannot be executed:\n')}`, - ) + messages.push(`${chalk.bold.red('\nāš ļø We found changes that cannot be executed:\n')}`) for (const item of migration.unexecutable) { messages.push(`${chalk(` ā€¢ ${item}`)}`) } @@ -204,9 +181,7 @@ ${chalk.bold.redBright('All data will be lost.')} `The ${dbInfo.dbType} ${dbInfo.schemaWord} "${dbInfo.dbName}" from "${dbInfo.dbLocation}" was successfully reset.`, ) } else { - console.info( - `The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`, - ) + console.info(`The ${dbInfo.dbType} ${dbInfo.schemaWord} was successfully reset.`) } wasDatabaseReset = true @@ -219,11 +194,7 @@ ${chalk.bold.redBright('All data will be lost.')} } if (migration.warnings && migration.warnings.length > 0) { - console.info( - chalk.bold.yellow( - `\nāš ļø There might be data loss when applying the changes:\n`, - ), - ) + console.info(chalk.bold.yellow(`\nāš ļø There might be data loss when applying the changes:\n`)) for (const warning of migration.warnings) { console.info(chalk(` ā€¢ ${warning}`)) @@ -265,19 +236,13 @@ ${chalk.bold.redBright('All data will be lost.')} migrate.stop() - if ( - !wasDatabaseReset && - migration.warnings.length === 0 && - migration.executedSteps === 0 - ) { + if (!wasDatabaseReset && migration.warnings.length === 0 && migration.executedSteps === 0) { console.info(`\nThe database is already in sync with the Prisma schema.`) } else { console.info( `\n${ process.platform === 'win32' ? '' : 'šŸš€ ' - }Your database is now in sync with your schema. Done in ${formatms( - Date.now() - before, - )}`, + }Your database is now in sync with your schema. Done in ${formatms(Date.now() - before)}`, ) } diff --git a/packages/migrate/src/commands/DbSeed.ts b/packages/migrate/src/commands/DbSeed.ts index 485236f92114..71cdc7b002f1 100644 --- a/packages/migrate/src/commands/DbSeed.ts +++ b/packages/migrate/src/commands/DbSeed.ts @@ -1,12 +1,5 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - HelpError, - isError, - getSchemaPath, - logger, -} from '@prisma/sdk' +import { arg, format, HelpError, isError, getSchemaPath, logger } from '@prisma/sdk' import chalk from 'chalk' import { getSeedCommandFromPackageJson, @@ -70,9 +63,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) ) } - const seedCommandFromPkgJson = await getSeedCommandFromPackageJson( - process.cwd(), - ) + const seedCommandFromPkgJson = await getSeedCommandFromPackageJson(process.cwd()) if (!seedCommandFromPkgJson) { // Only used to help users to setup their seeds from old way to new package.json config @@ -91,9 +82,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) // Execute user seed command const successfulSeeding = await executeSeedCommand(seedCommandFromPkgJson) if (successfulSeeding) { - return `\n${ - process.platform === 'win32' ? '' : 'šŸŒ± ' - }The seed command has been executed.` + return `\n${process.platform === 'win32' ? '' : 'šŸŒ± '}The seed command has been executed.` } else { process.exit(1) // For snapshot test, because exit() is mocked diff --git a/packages/migrate/src/commands/MigrateCommand.ts b/packages/migrate/src/commands/MigrateCommand.ts index 04aebef0e8f1..90463f859492 100644 --- a/packages/migrate/src/commands/MigrateCommand.ts +++ b/packages/migrate/src/commands/MigrateCommand.ts @@ -1,13 +1,5 @@ import type { Command, Commands } from '@prisma/sdk' -import { - arg, - format, - HelpError, - isError, - logger, - link, - unknownCommand, -} from '@prisma/sdk' +import { arg, format, HelpError, isError, logger, link, unknownCommand } from '@prisma/sdk' import chalk from 'chalk' import { ExperimentalFlagWithNewMigrateError } from '../utils/flagErrors' @@ -87,9 +79,7 @@ ${chalk.bold('Examples')} if (['up', 'save', 'down'].includes(args._[0])) { throw new Error( - `The current command "${ - args._[0] - }" doesn't exist in the new version of Prisma Migrate. + `The current command "${args._[0]}" doesn't exist in the new version of Prisma Migrate. Read more about how to upgrade: ${link('https://pris.ly/d/migrate-upgrade')}`, ) } @@ -112,9 +102,7 @@ You can now remove the ${chalk.red('--preview-feature')} flag.`) public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateCommand.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateCommand.help}`) } return MigrateCommand.help } diff --git a/packages/migrate/src/commands/MigrateDeploy.ts b/packages/migrate/src/commands/MigrateDeploy.ts index 65ab0d352f94..6aab257408df 100644 --- a/packages/migrate/src/commands/MigrateDeploy.ts +++ b/packages/migrate/src/commands/MigrateDeploy.ts @@ -1,19 +1,10 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getSchemaPath, - HelpError, - isError, -} from '@prisma/sdk' +import { arg, format, getSchemaPath, HelpError, isError } from '@prisma/sdk' import chalk from 'chalk' import path from 'path' import { Migrate } from '../Migrate' import { ensureDatabaseExists } from '../utils/ensureDatabaseExists' -import { - ExperimentalFlagWithNewMigrateError, - EarlyAccessFeatureFlagWithNewMigrateError, -} from '../utils/flagErrors' +import { ExperimentalFlagWithNewMigrateError, EarlyAccessFeatureFlagWithNewMigrateError } from '../utils/flagErrors' import { NoSchemaFoundError } from '../utils/errors' import { printFilesFromMigrationIds } from '../utils/printFiles' import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate' @@ -85,11 +76,7 @@ ${chalk.bold('Examples')} throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -113,18 +100,13 @@ ${chalk.bold('Examples')} optInToShadowDatabase: false, }) debug({ diagnoseResult: JSON.stringify(diagnoseResult, null, 2) }) - const listMigrationDirectoriesResult = - await migrate.listMigrationDirectories() + const listMigrationDirectoriesResult = await migrate.listMigrationDirectories() debug({ listMigrationDirectoriesResult }) console.info() // empty line if (listMigrationDirectoriesResult.migrations.length > 0) { const migrations = listMigrationDirectoriesResult.migrations - console.info( - `${migrations.length} migration${ - migrations.length > 1 ? 's' : '' - } found in prisma/migrations`, - ) + console.info(`${migrations.length} migration${migrations.length > 1 ? 's' : ''} found in prisma/migrations`) } else { console.info(`No migration found in prisma/migrations`) } @@ -132,9 +114,7 @@ ${chalk.bold('Examples')} const editedMigrationNames = diagnoseResult.editedMigrationNames if (editedMigrationNames.length > 0) { console.info( - `${chalk.yellow( - 'WARNING The following migrations have been modified since they were applied:', - )} + `${chalk.yellow('WARNING The following migrations have been modified since they were applied:')} ${editedMigrationNames.join('\n')}`, ) } @@ -152,9 +132,7 @@ ${editedMigrationNames.join('\n')}`, if (migrationIds.length === 0) { return chalk.greenBright(`No pending migrations to apply.`) } else { - return `The following migration${ - migrationIds.length > 1 ? 's' : '' - } have been applied:\n\n${chalk( + return `The following migration${migrationIds.length > 1 ? 's' : ''} have been applied:\n\n${chalk( printFilesFromMigrationIds('migrations', migrationIds, { 'migration.sql': '', }), @@ -166,9 +144,7 @@ ${chalk.greenBright('All migrations have been successfully applied.')}` public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateDeploy.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateDeploy.help}`) } return MigrateDeploy.help } diff --git a/packages/migrate/src/commands/MigrateDev.ts b/packages/migrate/src/commands/MigrateDev.ts index 58c142f9f659..5f2ceb4c2c66 100644 --- a/packages/migrate/src/commands/MigrateDev.ts +++ b/packages/migrate/src/commands/MigrateDev.ts @@ -19,25 +19,15 @@ import path from 'path' import { Migrate } from '../Migrate' import type { DbType } from '../utils/ensureDatabaseExists' import { ensureDatabaseExists, getDbInfo } from '../utils/ensureDatabaseExists' -import { - ExperimentalFlagWithNewMigrateError, - EarlyAccessFeatureFlagWithNewMigrateError, -} from '../utils/flagErrors' -import { - NoSchemaFoundError, - MigrateDevEnvNonInteractiveError, -} from '../utils/errors' +import { ExperimentalFlagWithNewMigrateError, EarlyAccessFeatureFlagWithNewMigrateError } from '../utils/flagErrors' +import { NoSchemaFoundError, MigrateDevEnvNonInteractiveError } from '../utils/errors' import { printMigrationId } from '../utils/printMigrationId' import { printFilesFromMigrationIds } from '../utils/printFiles' import { handleUnexecutableSteps } from '../utils/handleEvaluateDataloss' import { getMigrationName } from '../utils/promptForMigrationName' import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate' import { printDatasource } from '../utils/printDatasource' -import { - executeSeedCommand, - verifySeedConfigAndReturnMessage, - getSeedCommandFromPackageJson, -} from '../utils/seed' +import { executeSeedCommand, verifySeedConfigAndReturnMessage, getSeedCommandFromPackageJson } from '../utils/seed' import type { EngineResults } from '../types' const debug = Debug('prisma:migrate:dev') @@ -117,11 +107,7 @@ ${chalk.bold('Examples')} throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -167,10 +153,7 @@ ${chalk.bold('Examples')} } const dbInfo = await getDbInfo(schemaPath) - const confirmedReset = await this.confirmReset( - dbInfo, - devDiagnostic.action.reason, - ) + const confirmedReset = await this.confirmReset(dbInfo, devDiagnostic.action.reason) console.info() // empty line @@ -221,21 +204,13 @@ ${chalk.bold('Examples')} // Run seed if 1 or more seed files are present // And catch the error to continue execution try { - const seedCommandFromPkgJson = await getSeedCommandFromPackageJson( - process.cwd(), - ) + const seedCommandFromPkgJson = await getSeedCommandFromPackageJson(process.cwd()) if (seedCommandFromPkgJson) { console.info() // empty line - const successfulSeeding = await executeSeedCommand( - seedCommandFromPkgJson, - ) + const successfulSeeding = await executeSeedCommand(seedCommandFromPkgJson) if (successfulSeeding) { - console.info( - `\n${ - process.platform === 'win32' ? '' : 'šŸŒ± ' - }The seed command has been executed.\n`, - ) + console.info(`\n${process.platform === 'win32' ? '' : 'šŸŒ± '}The seed command has been executed.\n`) } else { console.info() // empty line } @@ -272,10 +247,7 @@ ${chalk.bold('Examples')} } // log warnings and prompt user to continue if needed - if ( - evaluateDataLossResult.warnings && - evaluateDataLossResult.warnings.length > 0 - ) { + if (evaluateDataLossResult.warnings && evaluateDataLossResult.warnings.length > 0) { console.log(chalk.bold(`\nāš ļø Warnings for the current datasource:\n`)) for (const warning of evaluateDataLossResult.warnings) { console.log(chalk(` ā€¢ ${warning.message}`)) @@ -348,13 +320,9 @@ ${chalk.bold('Examples')} if (migrationIds.length === 0) { if (migrationIdsApplied.length > 0) { - console.info( - `${chalk.green('Your database is now in sync with your schema.')}`, - ) + console.info(`${chalk.green('Your database is now in sync with your schema.')}`) } else { - console.info( - `Already in sync, no schema change or pending migration was found.`, - ) + console.info(`Already in sync, no schema change or pending migration was found.`) } } else { console.info() // empty line @@ -411,9 +379,7 @@ Do you want to continue? ${chalk.red('All data will be lost')}.` public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateDev.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateDev.help}`) } return MigrateDev.help } diff --git a/packages/migrate/src/commands/MigrateReset.ts b/packages/migrate/src/commands/MigrateReset.ts index dd17071aebcf..431ef3893957 100644 --- a/packages/migrate/src/commands/MigrateReset.ts +++ b/packages/migrate/src/commands/MigrateReset.ts @@ -1,34 +1,16 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getSchemaPath, - HelpError, - isError, - isCi, - logger, -} from '@prisma/sdk' +import { arg, format, getSchemaPath, HelpError, isError, isCi, logger } from '@prisma/sdk' import chalk from 'chalk' import path from 'path' import prompt from 'prompts' import { Migrate } from '../Migrate' -import { - ExperimentalFlagWithNewMigrateError, - EarlyAccessFeatureFlagWithNewMigrateError, -} from '../utils/flagErrors' -import { - NoSchemaFoundError, - MigrateResetEnvNonInteractiveError, -} from '../utils/errors' +import { ExperimentalFlagWithNewMigrateError, EarlyAccessFeatureFlagWithNewMigrateError } from '../utils/flagErrors' +import { NoSchemaFoundError, MigrateResetEnvNonInteractiveError } from '../utils/errors' import { printFilesFromMigrationIds } from '../utils/printFiles' import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate' import { ensureDatabaseExists } from '../utils/ensureDatabaseExists' import { printDatasource } from '../utils/printDatasource' -import { - executeSeedCommand, - verifySeedConfigAndReturnMessage, - getSeedCommandFromPackageJson, -} from '../utils/seed' +import { executeSeedCommand, verifySeedConfigAndReturnMessage, getSeedCommandFromPackageJson } from '../utils/seed' export class MigrateReset implements Command { public static new(): MigrateReset { @@ -98,11 +80,7 @@ ${chalk.bold('Examples')} throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -125,9 +103,7 @@ ${chalk.bold('Examples')} const confirmation = await prompt({ type: 'confirm', name: 'value', - message: `Are you sure you want to reset your database? ${chalk.red( - 'All data will be lost', - )}.`, + message: `Are you sure you want to reset your database? ${chalk.red('All data will be lost')}.`, }) console.info() // empty line @@ -174,21 +150,13 @@ The following migration(s) have been applied:\n\n${chalk( // Run if not skipped if (!process.env.PRISMA_MIGRATE_SKIP_SEED && !args['--skip-seed']) { - const seedCommandFromPkgJson = await getSeedCommandFromPackageJson( - process.cwd(), - ) + const seedCommandFromPkgJson = await getSeedCommandFromPackageJson(process.cwd()) if (seedCommandFromPkgJson) { console.info() // empty line - const successfulSeeding = await executeSeedCommand( - seedCommandFromPkgJson, - ) + const successfulSeeding = await executeSeedCommand(seedCommandFromPkgJson) if (successfulSeeding) { - console.info( - `\n${ - process.platform === 'win32' ? '' : 'šŸŒ± ' - }The seed command has been executed.`, - ) + console.info(`\n${process.platform === 'win32' ? '' : 'šŸŒ± '}The seed command has been executed.`) } } else { // Only used to help users to setup their seeds from old way to new package.json config @@ -204,9 +172,7 @@ The following migration(s) have been applied:\n\n${chalk( public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateReset.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateReset.help}`) } return MigrateReset.help } diff --git a/packages/migrate/src/commands/MigrateResolve.ts b/packages/migrate/src/commands/MigrateResolve.ts index e10399e1f34c..645a6efa4e16 100644 --- a/packages/migrate/src/commands/MigrateResolve.ts +++ b/packages/migrate/src/commands/MigrateResolve.ts @@ -1,21 +1,10 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getSchemaPath, - HelpError, - isError, - getCommandWithExecutor, - link, -} from '@prisma/sdk' +import { arg, format, getSchemaPath, HelpError, isError, getCommandWithExecutor, link } from '@prisma/sdk' import chalk from 'chalk' import path from 'path' import { ensureCanConnectToDatabase } from '../utils/ensureDatabaseExists' import { Migrate } from '../Migrate' -import { - ExperimentalFlagWithNewMigrateError, - EarlyAccessFeatureFlagWithNewMigrateError, -} from '../utils/flagErrors' +import { ExperimentalFlagWithNewMigrateError, EarlyAccessFeatureFlagWithNewMigrateError } from '../utils/flagErrors' import { NoSchemaFoundError } from '../utils/errors' import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate' import { printDatasource } from '../utils/printDatasource' @@ -32,9 +21,7 @@ Resolve issues with database migrations in deployment databases: Run "prisma migrate status" to identify if you need to use resolve. -Read more about resolving migration history issues: ${link( - 'https://pris.ly/d/migrate-resolve', - )} +Read more about resolving migration history issues: ${link('https://pris.ly/d/migrate-resolve')} ${chalk.bold('Usage')} @@ -50,19 +37,13 @@ ${chalk.bold('Options')} ${chalk.bold('Examples')} Update migrations table, recording a specific migration as applied - ${chalk.dim( - '$', - )} prisma migrate resolve --applied 20201231000000_add_users_table + ${chalk.dim('$')} prisma migrate resolve --applied 20201231000000_add_users_table Update migrations table, recording a specific migration as rolled back - ${chalk.dim( - '$', - )} prisma migrate resolve --rolled-back 20201231000000_add_users_table + ${chalk.dim('$')} prisma migrate resolve --rolled-back 20201231000000_add_users_table Specify a schema - ${chalk.dim( - '$', - )} prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma + ${chalk.dim('$')} prisma migrate resolve --rolled-back 20201231000000_add_users_table --schema=./schema.prisma `) public async parse(argv: string[]): Promise { @@ -103,11 +84,7 @@ ${chalk.bold('Examples')} throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -117,16 +94,8 @@ ${chalk.bold('Examples')} if (!args['--applied'] && !args['--rolled-back']) { throw new Error( `--applied or --rolled-back must be part of the command like: -${chalk.bold.green( - getCommandWithExecutor( - 'prisma migrate resolve --applied 20201231000000_example', - ), -)} -${chalk.bold.green( - getCommandWithExecutor( - 'prisma migrate resolve --rolled-back 20201231000000_example', - ), -)}`, +${chalk.bold.green(getCommandWithExecutor('prisma migrate resolve --applied 20201231000000_example'))} +${chalk.bold.green(getCommandWithExecutor('prisma migrate resolve --rolled-back 20201231000000_example'))}`, ) } // if both are defined @@ -135,15 +104,10 @@ ${chalk.bold.green( } if (args['--applied']) { - if ( - typeof args['--applied'] !== 'string' || - args['--applied'].length === 0 - ) { + if (typeof args['--applied'] !== 'string' || args['--applied'].length === 0) { throw new Error( `--applied value must be a string like ${chalk.bold.green( - getCommandWithExecutor( - 'prisma migrate resolve --applied 20201231000000_example', - ), + getCommandWithExecutor('prisma migrate resolve --applied 20201231000000_example'), )}`, ) } @@ -161,15 +125,10 @@ ${chalk.bold.green( return `Migration ${args['--applied']} marked as applied.` } else { - if ( - typeof args['--rolled-back'] !== 'string' || - args['--rolled-back'].length === 0 - ) { + if (typeof args['--rolled-back'] !== 'string' || args['--rolled-back'].length === 0) { throw new Error( `--rolled-back value must be a string like ${chalk.bold.green( - getCommandWithExecutor( - 'prisma migrate resolve --rolled-back 20201231000000_example', - ), + getCommandWithExecutor('prisma migrate resolve --rolled-back 20201231000000_example'), )}`, ) } @@ -191,9 +150,7 @@ ${chalk.bold.green( public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateResolve.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateResolve.help}`) } return MigrateResolve.help } diff --git a/packages/migrate/src/commands/MigrateStatus.ts b/packages/migrate/src/commands/MigrateStatus.ts index f5f5b20ec4c0..0c3f4ea6710d 100644 --- a/packages/migrate/src/commands/MigrateStatus.ts +++ b/packages/migrate/src/commands/MigrateStatus.ts @@ -1,20 +1,10 @@ import type { Command } from '@prisma/sdk' -import { - arg, - format, - getSchemaPath, - HelpError, - isError, - getCommandWithExecutor, -} from '@prisma/sdk' +import { arg, format, getSchemaPath, HelpError, isError, getCommandWithExecutor } from '@prisma/sdk' import chalk from 'chalk' import path from 'path' import { ensureCanConnectToDatabase } from '../utils/ensureDatabaseExists' import { Migrate } from '../Migrate' -import { - ExperimentalFlagWithNewMigrateError, - EarlyAccessFeatureFlagWithNewMigrateError, -} from '../utils/flagErrors' +import { ExperimentalFlagWithNewMigrateError, EarlyAccessFeatureFlagWithNewMigrateError } from '../utils/flagErrors' import { HowToBaselineError, NoSchemaFoundError } from '../utils/errors' import Debug from '@prisma/debug' import { throwUpgradeErrorIfOldMigrate } from '../utils/detectOldMigrate' @@ -85,11 +75,7 @@ Check the status of your database migrations throw new NoSchemaFoundError() } - console.info( - chalk.dim( - `Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`, - ), - ) + console.info(chalk.dim(`Prisma schema loaded from ${path.relative(process.cwd(), schemaPath)}`)) await printDatasource(schemaPath) @@ -132,11 +118,7 @@ ${e.message}`) if (listMigrationDirectoriesResult.migrations.length > 0) { const migrations = listMigrationDirectoriesResult.migrations - console.info( - `${migrations.length} migration${ - migrations.length > 1 ? 's' : '' - } found in prisma/migrations\n`, - ) + console.info(`${migrations.length} migration${migrations.length > 1 ? 's' : ''} found in prisma/migrations\n`) } else { console.info(`No migration found in prisma/migrations\n`) } @@ -145,26 +127,18 @@ ${e.message}`) if (diagnoseResult.history?.diagnostic === 'databaseIsBehind') { unappliedMigrations = diagnoseResult.history.unappliedMigrationNames console.info( - `Following migration${ - unappliedMigrations.length > 1 ? 's' : '' - } have not yet been applied: + `Following migration${unappliedMigrations.length > 1 ? 's' : ''} have not yet been applied: ${unappliedMigrations.join('\n')} -To apply migrations in development run ${chalk.bold.greenBright( - getCommandWithExecutor(`prisma migrate dev`), - )}. -To apply migrations in production run ${chalk.bold.greenBright( - getCommandWithExecutor(`prisma migrate deploy`), - )}.`, +To apply migrations in development run ${chalk.bold.greenBright(getCommandWithExecutor(`prisma migrate dev`))}. +To apply migrations in production run ${chalk.bold.greenBright(getCommandWithExecutor(`prisma migrate deploy`))}.`, ) } else if (diagnoseResult.history?.diagnostic === 'historiesDiverge') { return `Your local migration history and the migrations table from your database are different: The last common migration is: ${diagnoseResult.history.lastCommonMigrationName} -The migration${ - diagnoseResult.history.unappliedMigrationNames.length > 1 ? 's' : '' - } have not yet been applied: +The migration${diagnoseResult.history.unappliedMigrationNames.length > 1 ? 's' : ''} have not yet been applied: ${diagnoseResult.history.unappliedMigrationNames.join('\n')} The migration${ @@ -186,14 +160,11 @@ ${diagnoseResult.history.unpersistedMigrationNames.join('\n')}` if (listMigrationDirectoriesResult.migrations.length === 0) { return new HowToBaselineError().message } else { - const migrationId = - listMigrationDirectoriesResult.migrations.shift() as string + const migrationId = listMigrationDirectoriesResult.migrations.shift() as string return `The current database is not managed by Prisma Migrate. If you want to keep the current database structure and data and create new migrations, baseline this database with the migration "${migrationId}": -${chalk.bold.greenBright( - getCommandWithExecutor(`prisma migrate resolve --applied "${migrationId}"`), -)} +${chalk.bold.greenBright(getCommandWithExecutor(`prisma migrate resolve --applied "${migrationId}"`))} Read more about how to baseline an existing production database: https://pris.ly/d/migrate-baseline` @@ -206,9 +177,7 @@ https://pris.ly/d/migrate-baseline` const failedMigrations = diagnoseResult.failedMigrationNames console.info( - `Following migration${ - failedMigrations.length > 1 ? 's' : '' - } have failed: + `Following migration${failedMigrations.length > 1 ? 's' : ''} have failed: ${failedMigrations.join('\n')} During development if the failed migration(s) have not been deployed to a production database you can then fix the migration(s) and run ${chalk.bold.greenBright( @@ -219,18 +188,10 @@ During development if the failed migration(s) have not been deployed to a produc return `The failed migration(s) can be marked as rolled back or applied: - If you rolled back the migration(s) manually: -${chalk.bold.greenBright( - getCommandWithExecutor( - `prisma migrate resolve --rolled-back "${failedMigrations[0]}"`, - ), -)} +${chalk.bold.greenBright(getCommandWithExecutor(`prisma migrate resolve --rolled-back "${failedMigrations[0]}"`))} - If you fixed the database manually (hotfix): -${chalk.bold.greenBright( - getCommandWithExecutor( - `prisma migrate resolve --applied "${failedMigrations[0]}"`, - ), -)} +${chalk.bold.greenBright(getCommandWithExecutor(`prisma migrate resolve --applied "${failedMigrations[0]}"`))} Read more about how to resolve migration issues in a production database: https://pris.ly/d/migrate-resolve` @@ -247,9 +208,7 @@ https://pris.ly/d/migrate-resolve` public help(error?: string): string | HelpError { if (error) { - return new HelpError( - `\n${chalk.bold.red(`!`)} ${error}\n${MigrateStatus.help}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${MigrateStatus.help}`) } return MigrateStatus.help } diff --git a/packages/migrate/src/types.ts b/packages/migrate/src/types.ts index 2ff194849a40..610d1d6d3594 100644 --- a/packages/migrate/src/types.ts +++ b/packages/migrate/src/types.ts @@ -46,9 +46,7 @@ export interface MigrationFeedback { stepIndex: number } -export type DevAction = - | { tag: 'reset'; reason: string } - | { tag: 'createMigration' } +export type DevAction = { tag: 'reset'; reason: string } | { tag: 'createMigration' } // eslint-disable-next-line @typescript-eslint/no-namespace export namespace EngineArgs { diff --git a/packages/migrate/src/utils/detectOldMigrate.ts b/packages/migrate/src/utils/detectOldMigrate.ts index f2075d05cfa4..9dcc1aa0774d 100644 --- a/packages/migrate/src/utils/detectOldMigrate.ts +++ b/packages/migrate/src/utils/detectOldMigrate.ts @@ -6,9 +6,7 @@ export function isOldMigrate(migrationDirPath: string): boolean { return fs.existsSync(path.join(migrationDirPath, 'migrate.lock')) } -export function throwUpgradeErrorIfOldMigrate( - schemaPath?: string, -): Error | void { +export function throwUpgradeErrorIfOldMigrate(schemaPath?: string): Error | void { if (!schemaPath) { return } diff --git a/packages/migrate/src/utils/ensureDatabaseExists.ts b/packages/migrate/src/utils/ensureDatabaseExists.ts index 061a88d7d7be..22b88c6bf6a8 100644 --- a/packages/migrate/src/utils/ensureDatabaseExists.ts +++ b/packages/migrate/src/utils/ensureDatabaseExists.ts @@ -2,11 +2,7 @@ import { getSchema, getSchemaDir } from '@prisma/sdk' import { getConfig } from '@prisma/sdk' import chalk from 'chalk' import type { DatabaseCredentials } from '@prisma/sdk' -import { - uriToCredentials, - createDatabase, - canConnectToDatabase, -} from '@prisma/sdk' +import { uriToCredentials, createDatabase, canConnectToDatabase } from '@prisma/sdk' import prompt from 'prompts' import type execa from 'execa' @@ -62,9 +58,7 @@ export async function getDbInfo(schemaPath?: string): Promise<{ } } -export async function ensureCanConnectToDatabase( - schemaPath?: string, -): Promise { +export async function ensureCanConnectToDatabase(schemaPath?: string): Promise { const datamodel = await getSchema(schemaPath) const config = await getConfig({ datamodel }) const activeDatasource = config.datasources[0] @@ -81,10 +75,7 @@ export async function ensureCanConnectToDatabase( const schemaDir = (await getSchemaDir(schemaPath))! - const canConnect = await canConnectToDatabase( - activeDatasource.url.value, - schemaDir, - ) + const canConnect = await canConnectToDatabase(activeDatasource.url.value, schemaDir) if (canConnect === true) { return true @@ -94,11 +85,7 @@ export async function ensureCanConnectToDatabase( } } -export async function ensureDatabaseExists( - action: MigrateAction, - forceCreate = false, - schemaPath?: string, -) { +export async function ensureDatabaseExists(action: MigrateAction, forceCreate = false, schemaPath?: string) { const datamodel = await getSchema(schemaPath) const config = await getConfig({ datamodel }) const activeDatasource = config.datasources[0] @@ -115,10 +102,7 @@ export async function ensureDatabaseExists( const schemaDir = (await getSchemaDir(schemaPath))! - const canConnect = await canConnectToDatabase( - activeDatasource.url.value, - schemaDir, - ) + const canConnect = await canConnectToDatabase(activeDatasource.url.value, schemaDir) if (canConnect === true) { return } @@ -141,22 +125,15 @@ export async function ensureDatabaseExists( } const credentials = uriToCredentials(activeDatasource.url.value) - const { schemaWord, dbType, dbName } = - getDbinfoFromCredentials(credentials) + const { schemaWord, dbType, dbName } = getDbinfoFromCredentials(credentials) if (dbType && dbType !== 'SQL Server') { - return `${dbType} ${schemaWord} ${chalk.bold( - dbName, - )} created at ${chalk.bold(getDbLocation(credentials))}` + return `${dbType} ${schemaWord} ${chalk.bold(dbName)} created at ${chalk.bold(getDbLocation(credentials))}` } else { return `${schemaWord} created.` } } } else { - await interactivelyCreateDatabase( - activeDatasource.url.value, - action, - schemaDir, - ) + await interactivelyCreateDatabase(activeDatasource.url.value, action, schemaDir) } return undefined @@ -183,9 +160,7 @@ export async function askToCreateDb( if (dbName && dbLocation) { message = `You are trying to ${action} a migration for ${dbType} ${schemaWord} ${chalk.bold( dbName, - )}.\nA ${schemaWord} with that name doesn't exist at ${chalk.bold( - dbLocation, - )}.\n` + )}.\nA ${schemaWord} with that name doesn't exist at ${chalk.bold(dbLocation)}.\n` } else { message = `You are trying to ${action} a migration for ${dbType} ${schemaWord}.\nThe ${schemaWord} doesn't exist.\n` } diff --git a/packages/migrate/src/utils/errors.ts b/packages/migrate/src/utils/errors.ts index 115c251bc110..2df35bc29f48 100644 --- a/packages/migrate/src/utils/errors.ts +++ b/packages/migrate/src/utils/errors.ts @@ -69,12 +69,8 @@ export class MigrateResetEnvNonInteractiveError extends Error { super( `Prisma Migrate has detected that the environment is non-interactive. It is recommended to run this command in an interactive environment. -Use ${chalk.bold.greenBright( - `--force`, - )} to run this command without user interaction. -See ${link( - 'https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-reset', - )}`, +Use ${chalk.bold.greenBright(`--force`)} to run this command without user interaction. +See ${link('https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-reset')}`, ) } } @@ -85,12 +81,8 @@ export class MigrateDevEnvNonInteractiveError extends Error { `Prisma Migrate has detected that the environment is non-interactive, which is not supported. \`prisma migrate dev\` is an interactive command designed to create new migrations and evolve the database in development. -To apply existing migrations in deployments, use ${chalk.bold.greenBright( - `prisma migrate deploy`, - )}. -See ${link( - 'https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-deploy', - )}`, +To apply existing migrations in deployments, use ${chalk.bold.greenBright(`prisma migrate deploy`)}. +See ${link('https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-deploy')}`, ) } } @@ -99,9 +91,7 @@ export class DbNeedsForceError extends Error { constructor(subcommand: string) { super( `Use the --force flag to use the ${subcommand} command in an unnattended environment like ${chalk.bold.greenBright( - getCommandWithExecutor( - `prisma db ${subcommand} --force --preview-feature`, - ), + getCommandWithExecutor(`prisma db ${subcommand} --force --preview-feature`), )}`, ) } diff --git a/packages/migrate/src/utils/flagErrors.ts b/packages/migrate/src/utils/flagErrors.ts index fc6f791a25ef..c4c5c94d16e8 100644 --- a/packages/migrate/src/utils/flagErrors.ts +++ b/packages/migrate/src/utils/flagErrors.ts @@ -2,11 +2,7 @@ import chalk from 'chalk' export class ExperimentalFlagError extends Error { constructor() { - super( - `Please provide the ${chalk.green( - '--experimental', - )} flag to use this command.`, - ) + super(`Please provide the ${chalk.green('--experimental')} flag to use this command.`) } } @@ -14,9 +10,7 @@ export class PreviewFlagError extends Error { constructor() { super( `This feature is currently in Preview. There may be bugs and it's not recommended to use it in production environments. -Please provide the ${chalk.green( - '--preview-feature', - )} flag to use this command.`, +Please provide the ${chalk.green('--preview-feature')} flag to use this command.`, ) } } @@ -25,9 +19,7 @@ export class EarlyAcessFlagError extends Error { constructor() { super( `This feature is currently in Early Access. There may be bugs and it's not recommended to use it in production environments. -Please provide the ${chalk.green( - '--early-access-feature', - )} flag to use this command.`, +Please provide the ${chalk.green('--early-access-feature')} flag to use this command.`, ) } } @@ -38,9 +30,7 @@ export class ExperimentalFlagWithNewMigrateError extends Error { `Prisma Migrate was Experimental and is now Generally Available. ${chalk.yellow( 'WARNING this new version has some breaking changes', -)} to use it it's recommended to read the documentation first and remove the ${chalk.red( - '--experimental', - )} flag.`, +)} to use it it's recommended to read the documentation first and remove the ${chalk.red('--experimental')} flag.`, ) } } @@ -49,9 +39,7 @@ export class EarlyAccessFeatureFlagWithNewMigrateError extends Error { constructor() { super( `Prisma Migrate was in Early Access and is now in Preview. -Replace the ${chalk.red('--early-access-feature')} flag with ${chalk.green( - '--preview-feature', - )}.`, +Replace the ${chalk.red('--early-access-feature')} flag with ${chalk.green('--preview-feature')}.`, ) } } diff --git a/packages/migrate/src/utils/handleEvaluateDataloss.ts b/packages/migrate/src/utils/handleEvaluateDataloss.ts index a177c7fa5906..f737f7f80745 100644 --- a/packages/migrate/src/utils/handleEvaluateDataloss.ts +++ b/packages/migrate/src/utils/handleEvaluateDataloss.ts @@ -2,15 +2,10 @@ import chalk from 'chalk' import { getCommandWithExecutor } from '@prisma/sdk' import type { MigrationFeedback } from '../types' -export function handleUnexecutableSteps( - unexecutableSteps: MigrationFeedback[], - createOnly = false, -) { +export function handleUnexecutableSteps(unexecutableSteps: MigrationFeedback[], createOnly = false) { if (unexecutableSteps && unexecutableSteps.length > 0) { const messages: string[] = [] - messages.push( - `${chalk.bold.red('\nāš ļø We found changes that cannot be executed:\n')}`, - ) + messages.push(`${chalk.bold.red('\nāš ļø We found changes that cannot be executed:\n')}`) for (const item of unexecutableSteps) { messages.push(`${chalk(` ā€¢ Step ${item.stepIndex} ${item.message}`)}`) } @@ -26,9 +21,7 @@ export function handleUnexecutableSteps( You can use ${getCommandWithExecutor( 'prisma migrate dev --create-only', )} to create the migration file, and manually modify it to address the underlying issue(s). -Then run ${getCommandWithExecutor( - 'prisma migrate dev', - )} to apply it and verify it works.\n` +Then run ${getCommandWithExecutor('prisma migrate dev')} to apply it and verify it works.\n` } } diff --git a/packages/migrate/src/utils/handlePanic.ts b/packages/migrate/src/utils/handlePanic.ts index 5785d2826039..203aa8f81896 100644 --- a/packages/migrate/src/utils/handlePanic.ts +++ b/packages/migrate/src/utils/handlePanic.ts @@ -18,18 +18,13 @@ export async function handlePanic( } async function panicDialog(error, cliVersion, engineVersion, command) { - const errorMessage = error.message - .split('\n') - .slice(0, Math.max(20, process.stdout.rows)) - .join('\n') + const errorMessage = error.message.split('\n').slice(0, Math.max(20, process.stdout.rows)).join('\n') console.log(`${chalk.red('Oops, an unexpected error occured!')} ${chalk.red(errorMessage)} ${chalk.bold('Please help us improve Prisma by submitting an error report.')} -${chalk.bold( - 'Error reports never contain personal or other sensitive information.', -)} +${chalk.bold('Error reports never contain personal or other sensitive information.')} ${chalk.dim(`Learn more: ${link('https://pris.ly/d/telemetry')}`)} `) @@ -52,9 +47,7 @@ ${chalk.dim(`Learn more: ${link('https://pris.ly/d/telemetry')}`)} ], }) - const reportFailedMessage = `${chalk.bold.red( - 'Oops. We could not send the error report.', - )}` + const reportFailedMessage = `${chalk.bold.red('Oops. We could not send the error report.')}` if (response.value) { let reportId: number | void @@ -66,11 +59,7 @@ ${chalk.dim(`Learn more: ${link('https://pris.ly/d/telemetry')}`)} } if (reportId) { - console.log( - `\n${chalk.bold( - `We successfully received the error report id: ${reportId}`, - )}`, - ) + console.log(`\n${chalk.bold(`We successfully received the error report id: ${reportId}`)}`) console.log(`\n${chalk.bold('Thanks a lot for your help! šŸ™')}`) } } diff --git a/packages/migrate/src/utils/now.ts b/packages/migrate/src/utils/now.ts index aca8f574ca68..b84f1e7a1dc5 100644 --- a/packages/migrate/src/utils/now.ts +++ b/packages/migrate/src/utils/now.ts @@ -1,10 +1,8 @@ export function now(): string { const now = new Date() - return `${now.getUTCFullYear()}${prefixZero( - now.getUTCMonth() + 1, - )}${prefixZero(now.getUTCDate())}${prefixZero(now.getUTCHours())}${prefixZero( - now.getUTCMinutes(), - )}${prefixZero(now.getUTCSeconds())}` + return `${now.getUTCFullYear()}${prefixZero(now.getUTCMonth() + 1)}${prefixZero(now.getUTCDate())}${prefixZero( + now.getUTCHours(), + )}${prefixZero(now.getUTCMinutes())}${prefixZero(now.getUTCSeconds())}` } export function timestampToDate(timestamp: string): Date | undefined { diff --git a/packages/migrate/src/utils/printDatasource.ts b/packages/migrate/src/utils/printDatasource.ts index 178b7843748b..8c6d6bd5f386 100644 --- a/packages/migrate/src/utils/printDatasource.ts +++ b/packages/migrate/src/utils/printDatasource.ts @@ -14,9 +14,7 @@ export async function printDatasource(schemaPath: string): Promise { } else { console.info( chalk.dim( - `Datasource "${dbInfo.name}": ${dbInfo.dbType} ${ - dbInfo.schemaWord - } "${dbInfo.dbName}"${ + `Datasource "${dbInfo.name}": ${dbInfo.dbType} ${dbInfo.schemaWord} "${dbInfo.dbName}"${ dbInfo.schema ? `, schema "${dbInfo.schema}"` : '' } at "${dbInfo.dbLocation}"`, ), diff --git a/packages/migrate/src/utils/printDatasources.ts b/packages/migrate/src/utils/printDatasources.ts index fc9e9037fdf2..e95983629835 100644 --- a/packages/migrate/src/utils/printDatasources.ts +++ b/packages/migrate/src/utils/printDatasources.ts @@ -1,13 +1,7 @@ // This is copied from prisma-client-js/runtime/utils. It needs to be moved into a separate package import indent from 'indent-string' -export type ConnectorType = - | 'mysql' - | 'mongodb' - | 'sqlite' - | 'postgresql' - | 'sqlserver' - | 'jdbc:sqlserver' +export type ConnectorType = 'mysql' | 'mongodb' | 'sqlite' | 'postgresql' | 'sqlserver' | 'jdbc:sqlserver' export interface GeneratorConfig { name: string @@ -30,12 +24,8 @@ export interface InternalDatasource { config: any } -export function printDatasources( - internalDatasources: InternalDatasource[], -): string { - return internalDatasources - .map((d) => String(new InternalDataSourceClass(d))) - .join('\n\n') +export function printDatasources(internalDatasources: InternalDatasource[]): string { + return internalDatasources.map((d) => String(new InternalDataSourceClass(d))).join('\n\n') } const tab = 2 @@ -59,17 +49,12 @@ ${indent(printDatamodelObject(obj), tab)} } export function printDatamodelObject(obj: any): string { - const maxLength = Object.keys(obj).reduce( - (max, curr) => Math.max(max, curr.length), - 0, - ) + const maxLength = Object.keys(obj).reduce((max, curr) => Math.max(max, curr.length), 0) return Object.entries(obj) .map( ([key, value]: [string, any]) => `${key.padEnd(maxLength)} = ${ - typeof value === 'object' && value && value.value - ? JSON.stringify(value.value) - : JSON.stringify(value) + typeof value === 'object' && value && value.value ? JSON.stringify(value.value) : JSON.stringify(value) }`, ) .join('\n') diff --git a/packages/migrate/src/utils/printFiles.ts b/packages/migrate/src/utils/printFiles.ts index f95db37873a7..7441aaaacc99 100644 --- a/packages/migrate/src/utils/printFiles.ts +++ b/packages/migrate/src/utils/printFiles.ts @@ -13,11 +13,7 @@ ${folders[0]}/ ${indent(fileNames.map((f) => `ā””ā”€ ${f}`).join('\n'), 4)}` } -export function printFilesFromMigrationIds( - directory: string, - migrationIds: string[], - files: FileMap, -): string { +export function printFilesFromMigrationIds(directory: string, migrationIds: string[], files: FileMap): string { const fileNames = Object.keys(files) let message = `\ diff --git a/packages/migrate/src/utils/promptForMigrationName.ts b/packages/migrate/src/utils/promptForMigrationName.ts index 3adbfb94e85a..27a8915e0af0 100644 --- a/packages/migrate/src/utils/promptForMigrationName.ts +++ b/packages/migrate/src/utils/promptForMigrationName.ts @@ -7,18 +7,13 @@ type getMigratioNameOutput = { userCancelled?: string } -export async function getMigrationName( - name?: string, -): Promise { +export async function getMigrationName(name?: string): Promise { // Truncate if longer const maxMigrationNameLength = 200 if (name) { return { - name: slugify(name, { separator: '_' }).substring( - 0, - maxMigrationNameLength, - ), + name: slugify(name, { separator: '_' }).substring(0, maxMigrationNameLength), } } // We use prompts.inject() for testing in our CI @@ -41,10 +36,6 @@ export async function getMigrationName( } return { - name: - slugify(response.name, { separator: '_' }).substring( - 0, - maxMigrationNameLength, - ) || '', + name: slugify(response.name, { separator: '_' }).substring(0, maxMigrationNameLength) || '', } } diff --git a/packages/migrate/src/utils/seed.ts b/packages/migrate/src/utils/seed.ts index 43e0eb7d91e1..8fb0d98ec9e1 100644 --- a/packages/migrate/src/utils/seed.ts +++ b/packages/migrate/src/utils/seed.ts @@ -15,9 +15,7 @@ const readFileAsync = promisify(fs.readFile) Checks if user has a prisma/seed.ts or prisma/seed.js or prisma/seed.sh If prisma.seed is not set in package.json it will return the best error message to help the user */ -export async function verifySeedConfigAndReturnMessage( - schemaPath: string | null, -): Promise { +export async function verifySeedConfigAndReturnMessage(schemaPath: string | null): Promise { const cwd = process.cwd() // Detect if seed files are next to prisma.schema file @@ -116,9 +114,7 @@ ${chalk.bold('Bash:')} And run \`chmod +x prisma/seed.sh\` to make it executable.` } - message += `\nMore information in our documentation:\n${link( - 'https://pris.ly/d/seeding', - )}` + message += `\nMore information in our documentation:\n${link('https://pris.ly/d/seeding')}` return message } @@ -166,9 +162,7 @@ export async function executeSeedCommand(command: string): Promise { } catch (_e) { const e = _e as execa.ExecaError debug({ e }) - console.error( - chalk.bold.red(`\nAn error occured while running the seed command:`), - ) + console.error(chalk.bold.red(`\nAn error occured while running the seed command:`)) console.error(chalk.red(e.stderr || e)) return false } diff --git a/packages/react-prisma/.prettierrc.yml b/packages/react-prisma/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/react-prisma/.prettierrc.yml +++ b/packages/react-prisma/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/sdk/.prettierrc.yml b/packages/sdk/.prettierrc.yml index bbaf47227321..f0beb50a2167 100644 --- a/packages/sdk/.prettierrc.yml +++ b/packages/sdk/.prettierrc.yml @@ -2,4 +2,4 @@ tabWidth: 2 trailingComma: all singleQuote: true semi: false -printWidth: 80 +printWidth: 120 diff --git a/packages/sdk/src/Generator.ts b/packages/sdk/src/Generator.ts index 16abab899589..0db9ec7aa297 100644 --- a/packages/sdk/src/Generator.ts +++ b/packages/sdk/src/Generator.ts @@ -1,9 +1,4 @@ -import type { - GeneratorOptions, - GeneratorManifest, - BinaryPaths, - GeneratorConfig, -} from '@prisma/generator-helper' +import type { GeneratorOptions, GeneratorManifest, BinaryPaths, GeneratorConfig } from '@prisma/generator-helper' import { GeneratorProcess } from '@prisma/generator-helper' export class Generator { @@ -11,11 +6,7 @@ export class Generator { public manifest: GeneratorManifest | null = null public config: GeneratorConfig public options?: GeneratorOptions - constructor( - executablePath: string, - config: GeneratorConfig, - isNode?: boolean, - ) { + constructor(executablePath: string, config: GeneratorConfig, isNode?: boolean) { this.config = config this.generatorProcess = new GeneratorProcess(executablePath, isNode) } @@ -28,9 +19,7 @@ export class Generator { } generate(): Promise { if (!this.options) { - throw new Error( - `Please first run .setOptions() on the Generator to initialize the options`, - ) + throw new Error(`Please first run .setOptions() on the Generator to initialize the options`) } return this.generatorProcess.generate(this.options) } @@ -39,9 +28,7 @@ export class Generator { } setBinaryPaths(binaryPaths: BinaryPaths): void { if (!this.options) { - throw new Error( - `Please first run .setOptions() on the Generator to initialize the options`, - ) + throw new Error(`Please first run .setOptions() on the Generator to initialize the options`) } this.options.binaryPaths = binaryPaths } diff --git a/packages/sdk/src/IntrospectionEngine.ts b/packages/sdk/src/IntrospectionEngine.ts index 1e0cc8ec69b6..6edf4ac890e6 100644 --- a/packages/sdk/src/IntrospectionEngine.ts +++ b/packages/sdk/src/IntrospectionEngine.ts @@ -129,8 +129,7 @@ interface IntrospectionWarningsEnumMapReintro extends IntrospectionWarning { code: 9 affected: AffectedEnum } -interface IntrospectionWarningsEnumValueMapReintro - extends IntrospectionWarning { +interface IntrospectionWarningsEnumValueMapReintro extends IntrospectionWarning { code: 10 affected: AffectedEnum } @@ -158,11 +157,7 @@ interface IntrospectionWarningsMongoMultipleTypes extends IntrospectionWarning { // affected: AffectedModelAndFieldAndType } -export type IntrospectionSchemaVersion = - | 'Prisma2' - | 'Prisma1' - | 'Prisma11' - | 'NonPrisma' +export type IntrospectionSchemaVersion = 'Prisma2' | 'Prisma1' | 'Prisma11' | 'NonPrisma' let messageId = 1 @@ -202,16 +197,11 @@ export class IntrospectionEngine { delete this.listeners[id] }) } - private registerCallback( - id: number, - callback: (result: any, err?: Error) => any, - ): void { + private registerCallback(id: number, callback: (result: any, err?: Error) => any): void { this.listeners[id] = callback } public getDatabaseDescription(schema: string): Promise { - return this.runCommand( - this.getRPCPayload('getDatabaseDescription', { schema }), - ) + return this.runCommand(this.getRPCPayload('getDatabaseDescription', { schema })) } public getDatabaseVersion(schema: string): Promise { return this.runCommand(this.getRPCPayload('getDatabaseVersion', { schema })) @@ -234,25 +224,16 @@ export class IntrospectionEngine { this.lastUrl = schema return this.runCommand(this.getRPCPayload('listDatabases', { schema })) } - public getDatabaseMetadata( - schema: string, - ): Promise<{ size_in_bytes: number; table_count: number }> { + public getDatabaseMetadata(schema: string): Promise<{ size_in_bytes: number; table_count: number }> { this.lastUrl = schema - return this.runCommand( - this.getRPCPayload('getDatabaseMetadata', { schema }), - ) + return this.runCommand(this.getRPCPayload('getDatabaseMetadata', { schema })) } private handleResponse(response: any): void { let result try { result = JSON.parse(response) } catch (e) { - console.error( - `Could not parse introspection engine response: ${response.slice( - 0, - 200, - )}`, - ) + console.error(`Could not parse introspection engine response: ${response.slice(0, 200)}`) } if (result) { if (result.backtrace) { @@ -260,11 +241,7 @@ export class IntrospectionEngine { console.log(result) } if (!result.id) { - console.error( - `Response ${JSON.stringify( - result, - )} doesn't have an id and I can't handle that (yet)`, - ) + console.error(`Response ${JSON.stringify(result)} doesn't have an id and I can't handle that (yet)`) } if (!this.listeners[result.id]) { console.error(`Got result for unknown id ${result.id}`) @@ -330,21 +307,12 @@ export class IntrospectionEngine { const messages = this.messages.join('\n') let err: any if (code !== 0 || messages.includes('panicked at')) { - let errorMessage = - chalk.red.bold('Error in introspection engine: ') + messages + let errorMessage = chalk.red.bold('Error in introspection engine: ') + messages if (this.lastError && this.lastError.msg === 'PANIC') { errorMessage = serializePanic(this.lastError) - err = new IntrospectionPanic( - errorMessage, - messages, - this.lastRequest, - ) + err = new IntrospectionPanic(errorMessage, messages, this.lastRequest) } else if (messages.includes('panicked at')) { - err = new IntrospectionPanic( - errorMessage, - messages, - this.lastRequest, - ) + err = new IntrospectionPanic(errorMessage, messages, this.lastRequest) } err = err || new Error(errorMessage) this.rejectAll(err) @@ -394,11 +362,7 @@ export class IntrospectionEngine { } if (this.child?.killed) { - throw new Error( - `Can't execute ${JSON.stringify( - request, - )} because introspection engine already exited.`, - ) + throw new Error(`Can't execute ${JSON.stringify(request)} because introspection engine already exited.`) } return new Promise((resolve, reject) => { this.registerCallback(request.id, (response, err) => { @@ -412,8 +376,7 @@ export class IntrospectionEngine { this.child?.kill() debugRpc(response) if (response.error.data?.is_panic) { - const message = - response.error.data?.error?.message ?? response.error.message + const message = response.error.data?.error?.message ?? response.error.message reject( new RustPanic( message, @@ -429,50 +392,29 @@ export class IntrospectionEngine { // See known errors at https://github.com/prisma/specs/tree/master/errors#prisma-sdk let message = `${response.error.data.message}\n` if (response.error.data?.error_code) { - message = - chalk.redBright(`${response.error.data.error_code}\n\n`) + - message - reject( - new IntrospectionError( - message, - response.error.data.error_code, - ), - ) + message = chalk.redBright(`${response.error.data.error_code}\n\n`) + message + reject(new IntrospectionError(message, response.error.data.error_code)) } else { reject(new Error(message)) } } else { reject( new Error( - `${chalk.redBright( - 'Error in RPC', - )}\n Request: ${JSON.stringify( + `${chalk.redBright('Error in RPC')}\n Request: ${JSON.stringify( request, null, 2, - )}\nResponse: ${JSON.stringify(response, null, 2)}\n${ - response.error.message - }\n`, + )}\nResponse: ${JSON.stringify(response, null, 2)}\n${response.error.message}\n`, ), ) } } else { - reject( - new Error( - `Got invalid RPC response without .result property: ${JSON.stringify( - response, - )}`, - ), - ) + reject(new Error(`Got invalid RPC response without .result property: ${JSON.stringify(response)}`)) } } }) if (this.child!.stdin!.destroyed) { - throw new Error( - `Can't execute ${JSON.stringify( - request, - )} because introspection engine is destroyed.`, - ) + throw new Error(`Can't execute ${JSON.stringify(request)} because introspection engine is destroyed.`) } debugRpc('SENDING RPC CALL', JSON.stringify(request)) this.child!.stdin!.write(JSON.stringify(request) + '\n') diff --git a/packages/sdk/src/__tests__/dotenvExpand.test.ts b/packages/sdk/src/__tests__/dotenvExpand.test.ts index 7b6f386d8998..98bb7e850bfb 100644 --- a/packages/sdk/src/__tests__/dotenvExpand.test.ts +++ b/packages/sdk/src/__tests__/dotenvExpand.test.ts @@ -14,14 +14,10 @@ describe('dotenvExpand', () => { SQLITE6: 'file:dev{$.db', SQLITE7: 'file:${dev.db', SQLITE8: 'file:${dev$.db', - POSTGRES1: - 'postgres://user:password@server.host:5432/database?ssl=1&schema=schema$1234', - POSTGRES2: - 'postgres://$user:password@server.host:5432/database?ssl=1&schema=schema$1234', - POSTGRES3: - 'postgres://u$ser:pass$word@server.host:5432/database?ssl=1&schema=schema$1234', - POSTGRES4: - 'postgres://user:password@serv$er.host:5432/database?ssl=1&schema=schema$1234', + POSTGRES1: 'postgres://user:password@server.host:5432/database?ssl=1&schema=schema$1234', + POSTGRES2: 'postgres://$user:password@server.host:5432/database?ssl=1&schema=schema$1234', + POSTGRES3: 'postgres://u$ser:pass$word@server.host:5432/database?ssl=1&schema=schema$1234', + POSTGRES4: 'postgres://user:password@serv$er.host:5432/database?ssl=1&schema=schema$1234', MYSQL1: 'mysql://user:password@serv$er.host:5432/$database', MYSQL2: 'mysql://user:password@server.host:5432/d$atabase', }, @@ -50,10 +46,8 @@ describe('dotenvExpand', () => { test('should expand', () => { const config = { parsed: { - DOTENV_PRISMA_EXPAND_DATABASE_URL: - 'postgres://user:password@server.host:5432/database', - DOTENV_PRISMA_EXPAND_DATABASE_URL_WITH_SCHEMA: - '${DOTENV_PRISMA_EXPAND_DATABASE_URL}?ssl=1&schema=schema$1234', + DOTENV_PRISMA_EXPAND_DATABASE_URL: 'postgres://user:password@server.host:5432/database', + DOTENV_PRISMA_EXPAND_DATABASE_URL_WITH_SCHEMA: '${DOTENV_PRISMA_EXPAND_DATABASE_URL}?ssl=1&schema=schema$1234', }, } expect(dotenvExpand(config)).toMatchInlineSnapshot(` @@ -197,8 +191,7 @@ describe('dotenvExpand', () => { it('does not expand inline escaped dollar sign 2', () => { const dotenv = { parsed: { - INLINE_ESCAPED_EXPAND_BCRYPT: - '\\$2b\\$10\\$OMZ69gxxsmRgwAt945WHSujpr/u8ZMx.xwtxWOCMkeMW7p3XqKYca', + INLINE_ESCAPED_EXPAND_BCRYPT: '\\$2b\\$10\\$OMZ69gxxsmRgwAt945WHSujpr/u8ZMx.xwtxWOCMkeMW7p3XqKYca', }, } const obj = dotenvExpand(dotenv).parsed @@ -266,17 +259,13 @@ describe('integration', function () { it('multiple expand', () => { const obj = dotenvExpand(dotenv).parsed! - expect(obj['MONGOLAB_URI']).toBe( - 'mongodb://username:password@abcd1234.mongolab.com:12345/heroku_db', - ) + expect(obj['MONGOLAB_URI']).toBe('mongodb://username:password@abcd1234.mongolab.com:12345/heroku_db') }) it('should expand recursively', () => { const obj = dotenvExpand(dotenv).parsed! - expect(obj['MONGOLAB_URI_RECURSIVELY']).toBe( - 'mongodb://username:password@abcd1234.mongolab.com:12345/heroku_db', - ) + expect(obj['MONGOLAB_URI_RECURSIVELY']).toBe('mongodb://username:password@abcd1234.mongolab.com:12345/heroku_db') }) it('multiple expand without curly', () => { diff --git a/packages/sdk/src/__tests__/engine-commands/getConfig.test.ts b/packages/sdk/src/__tests__/engine-commands/getConfig.test.ts index a3f452fdcb17..315935941351 100644 --- a/packages/sdk/src/__tests__/engine-commands/getConfig.test.ts +++ b/packages/sdk/src/__tests__/engine-commands/getConfig.test.ts @@ -77,8 +77,7 @@ describe('getConfig', () => { }) test('datasource with env var', async () => { - process.env.TEST_POSTGRES_URI_FOR_DATASOURCE = - 'postgres://user:password@something:5432/db' + process.env.TEST_POSTGRES_URI_FOR_DATASOURCE = 'postgres://user:password@something:5432/db' const config = await getConfig({ datamodel: ` diff --git a/packages/sdk/src/__tests__/engine-commands/getDmmf.test.ts b/packages/sdk/src/__tests__/engine-commands/getDmmf.test.ts index 703619c789cb..58d8cf95f50f 100644 --- a/packages/sdk/src/__tests__/engine-commands/getDmmf.test.ts +++ b/packages/sdk/src/__tests__/engine-commands/getDmmf.test.ts @@ -241,10 +241,7 @@ describe('getDMMF', () => { }) test('chinook introspected schema', async () => { - const file = fs.readFileSync( - path.join(fixturesPath, 'chinook.prisma'), - 'utf-8', - ) + const file = fs.readFileSync(path.join(fixturesPath, 'chinook.prisma'), 'utf-8') const dmmf = await getDMMF({ datamodel: file, }) @@ -253,10 +250,7 @@ describe('getDMMF', () => { }) test('big schema', async () => { - const file = fs.readFileSync( - path.join(fixturesPath, 'bigschema.prisma'), - 'utf-8', - ) + const file = fs.readFileSync(path.join(fixturesPath, 'bigschema.prisma'), 'utf-8') const dmmf = await getDMMF({ datamodel: file, }) diff --git a/packages/sdk/src/__tests__/engine-commands/getVersion.test.ts b/packages/sdk/src/__tests__/engine-commands/getVersion.test.ts index a92cee748806..17781de4595c 100644 --- a/packages/sdk/src/__tests__/engine-commands/getVersion.test.ts +++ b/packages/sdk/src/__tests__/engine-commands/getVersion.test.ts @@ -7,18 +7,12 @@ const useNodeAPI = getCliQueryEngineBinaryType() === BinaryType.libqueryEngine describe('getVersion', () => { test('Introspection Engine', async () => { - const introspectionEngineVersion = await getVersion( - undefined, - BinaryType.introspectionEngine, - ) + const introspectionEngineVersion = await getVersion(undefined, BinaryType.introspectionEngine) expect(introspectionEngineVersion.split(' ')[1]).toMatch(enginesVersion) }) test('Migration Engine', async () => { - const migrationEngineVersion = await getVersion( - undefined, - BinaryType.migrationEngine, - ) + const migrationEngineVersion = await getVersion(undefined, BinaryType.migrationEngine) expect(migrationEngineVersion.split(' ')[1]).toMatch(enginesVersion) }) @@ -28,17 +22,11 @@ describe('getVersion', () => { }) testIf(!useNodeAPI)('Query Engine', async () => { - const queryEngineVersion = await getVersion( - undefined, - BinaryType.queryEngine, - ) + const queryEngineVersion = await getVersion(undefined, BinaryType.queryEngine) expect(queryEngineVersion.split(' ')[1]).toMatch(enginesVersion) }) testIf(useNodeAPI)('Query Engine (Node-API)', async () => { - const libqueryEngineVersion = await getVersion( - undefined, - BinaryType.libqueryEngine, - ) + const libqueryEngineVersion = await getVersion(undefined, BinaryType.libqueryEngine) expect(libqueryEngineVersion.split(' ')[1]).toMatch(enginesVersion) }) }) diff --git a/packages/sdk/src/__tests__/getGenerators/getGenerators.test.ts b/packages/sdk/src/__tests__/getGenerators/getGenerators.test.ts index ed6b3ae9ebca..986149a82d2e 100644 --- a/packages/sdk/src/__tests__/getGenerators/getGenerators.test.ts +++ b/packages/sdk/src/__tests__/getGenerators/getGenerators.test.ts @@ -42,13 +42,7 @@ describe('getGenerators', () => { ] `) - expect( - pick(generators[0].options!, [ - 'datamodel', - 'datasources', - 'otherGenerators', - ]), - ).toMatchInlineSnapshot(` + expect(pick(generators[0].options!, ['datamodel', 'datasources', 'otherGenerators'])).toMatchInlineSnapshot(` Object { "datamodel": "datasource db { provider = \\"sqlite\\" @@ -80,8 +74,7 @@ describe('getGenerators', () => { } `) - expect(omit(generators[0].options!.generator, ['output'])) - .toMatchInlineSnapshot(` + expect(omit(generators[0].options!.generator, ['output'])).toMatchInlineSnapshot(` Object { "binaryTargets": Array [ Object { @@ -111,10 +104,7 @@ describe('getGenerators', () => { } const generators = await getGenerators({ - schemaPath: path.join( - __dirname, - 'valid-minimal-schema-binaryTargets.prisma', - ), + schemaPath: path.join(__dirname, 'valid-minimal-schema-binaryTargets.prisma'), providerAliases: aliases, }) @@ -134,13 +124,7 @@ describe('getGenerators', () => { ] `) - expect( - pick(generators[0].options!, [ - 'datamodel', - 'datasources', - 'otherGenerators', - ]), - ).toMatchInlineSnapshot(` + expect(pick(generators[0].options!, ['datamodel', 'datasources', 'otherGenerators'])).toMatchInlineSnapshot(` Object { "datamodel": "datasource db { provider = \\"sqlite\\" @@ -205,10 +189,7 @@ describe('getGenerators', () => { } const generators = await getGenerators({ - schemaPath: path.join( - __dirname, - 'valid-minimal-schema-binaryTargets-env-var.prisma', - ), + schemaPath: path.join(__dirname, 'valid-minimal-schema-binaryTargets-env-var.prisma'), providerAliases: aliases, }) @@ -228,13 +209,7 @@ describe('getGenerators', () => { ] `) - expect( - pick(generators[0].options!, [ - 'datamodel', - 'datasources', - 'otherGenerators', - ]), - ).toMatchInlineSnapshot(` + expect(pick(generators[0].options!, ['datamodel', 'datasources', 'otherGenerators'])).toMatchInlineSnapshot(` Object { "datamodel": "datasource db { provider = \\"sqlite\\" @@ -271,9 +246,7 @@ describe('getGenerators', () => { expect(generator.binaryTargets).toHaveLength(1) expect(generator.binaryTargets[0].value).toEqual(platform) - expect(generator.binaryTargets[0].fromEnvVar).toEqual( - 'BINARY_TARGETS_ENV_VAR_TEST', - ) + expect(generator.binaryTargets[0].fromEnvVar).toEqual('BINARY_TARGETS_ENV_VAR_TEST') expect(omit(generator, ['binaryTargets'])).toMatchInlineSnapshot(` Object { @@ -301,10 +274,7 @@ describe('getGenerators', () => { } const generators = await getGenerators({ - schemaPath: path.join( - __dirname, - 'valid-minimal-schema-binaryTargets-env-var.prisma', - ), + schemaPath: path.join(__dirname, 'valid-minimal-schema-binaryTargets-env-var.prisma'), providerAliases: aliases, }) @@ -324,13 +294,7 @@ describe('getGenerators', () => { ] `) - expect( - pick(generators[0].options!, [ - 'datamodel', - 'datasources', - 'otherGenerators', - ]), - ).toMatchInlineSnapshot(` + expect(pick(generators[0].options!, ['datamodel', 'datasources', 'otherGenerators'])).toMatchInlineSnapshot(` Object { "datamodel": "datasource db { provider = \\"sqlite\\" @@ -367,9 +331,7 @@ describe('getGenerators', () => { expect(generator.binaryTargets).toHaveLength(1) expect(generator.binaryTargets[0].value).toEqual(platform) - expect(generator.binaryTargets[0].fromEnvVar).toEqual( - 'BINARY_TARGETS_ENV_VAR_TEST', - ) + expect(generator.binaryTargets[0].fromEnvVar).toEqual('BINARY_TARGETS_ENV_VAR_TEST') expect(omit(generator, ['binaryTargets'])).toMatchInlineSnapshot(` Object { @@ -387,8 +349,7 @@ describe('getGenerators', () => { }) it('basic - binaryTargets as env var - darwin, windows, debian', async () => { - process.env.BINARY_TARGETS_ENV_VAR_TEST = - '["darwin", "windows", "debian-openssl-1.1.x"]' + process.env.BINARY_TARGETS_ENV_VAR_TEST = '["darwin", "windows", "debian-openssl-1.1.x"]' const aliases = { 'predefined-generator': { @@ -398,10 +359,7 @@ describe('getGenerators', () => { } const generators = await getGenerators({ - schemaPath: path.join( - __dirname, - 'valid-minimal-schema-binaryTargets-env-var.prisma', - ), + schemaPath: path.join(__dirname, 'valid-minimal-schema-binaryTargets-env-var.prisma'), providerAliases: aliases, }) @@ -421,13 +379,7 @@ describe('getGenerators', () => { ] `) - expect( - pick(generators[0].options!, [ - 'datamodel', - 'datasources', - 'otherGenerators', - ]), - ).toMatchInlineSnapshot(` + expect(pick(generators[0].options!, ['datamodel', 'datasources', 'otherGenerators'])).toMatchInlineSnapshot(` Object { "datamodel": "datasource db { provider = \\"sqlite\\" @@ -459,8 +411,7 @@ describe('getGenerators', () => { } `) - expect(omit(generators[0].options!.generator, ['output'])) - .toMatchInlineSnapshot(` + expect(omit(generators[0].options!.generator, ['output'])).toMatchInlineSnapshot(` Object { "binaryTargets": Array [ Object { @@ -630,10 +581,7 @@ describe('getGenerators', () => { try { await getGenerators({ - schemaPath: path.join( - __dirname, - 'missing-models-mongodb-schema.prisma', - ), + schemaPath: path.join(__dirname, 'missing-models-mongodb-schema.prisma'), providerAliases: aliases, }) } catch (e) { @@ -666,10 +614,7 @@ describe('getGenerators', () => { try { await getGenerators({ - schemaPath: path.join( - __dirname, - 'missing-mongoDb-from-previewFeatures-client-js.prisma', - ), + schemaPath: path.join(__dirname, 'missing-mongoDb-from-previewFeatures-client-js.prisma'), providerAliases: aliases, skipDownload: true, }) @@ -703,10 +648,7 @@ https://pris.ly/d/prisma-schema try { await getGenerators({ - schemaPath: path.join( - __dirname, - 'missing-mongoDb-from-previewFeatures-client-go.prisma', - ), + schemaPath: path.join(__dirname, 'missing-mongoDb-from-previewFeatures-client-go.prisma'), providerAliases: aliases, skipDownload: true, }) @@ -742,17 +684,12 @@ https://pris.ly/d/prisma-schema try { await getGenerators({ - schemaPath: path.join( - __dirname, - 'mongoDb-from-previewFeatures-client-go.prisma', - ), + schemaPath: path.join(__dirname, 'mongoDb-from-previewFeatures-client-go.prisma'), providerAliases: aliases, skipDownload: true, }) } catch (e) { - expect(stripAnsi(e.message)).toContain( - 'Generator at go run github.com/prisma/prisma-client-go could not start', - ) + expect(stripAnsi(e.message)).toContain('Generator at go run github.com/prisma/prisma-client-go could not start') } }) }) diff --git a/packages/sdk/src/__tests__/getPackedPackage.test.ts b/packages/sdk/src/__tests__/getPackedPackage.test.ts index 9ca5922d04e5..db540ca7420c 100644 --- a/packages/sdk/src/__tests__/getPackedPackage.test.ts +++ b/packages/sdk/src/__tests__/getPackedPackage.test.ts @@ -8,11 +8,7 @@ describe('getPackedPackage', () => { const packageDir = 'foo`touch /tmp/getPackedPackage-exploit`' try { - await getPackedPackage( - '@prisma/client', - path.join(__dirname, outputDir), - packageDir, - ) + await getPackedPackage('@prisma/client', path.join(__dirname, outputDir), packageDir) } catch (e) { // } finally { diff --git a/packages/sdk/src/__tests__/getSchema.test.ts b/packages/sdk/src/__tests__/getSchema.test.ts index bfb901b272b8..76b0c34d8f41 100644 --- a/packages/sdk/src/__tests__/getSchema.test.ts +++ b/packages/sdk/src/__tests__/getSchema.test.ts @@ -1,18 +1,12 @@ import path from 'path' -import { - getSchemaPathInternal, - getSchemaPathSyncInternal, -} from '../cli/getSchema' +import { getSchemaPathInternal, getSchemaPathSyncInternal } from '../cli/getSchema' import { fixturesPath } from './__utils__/fixtures' process.env.npm_config_user_agent = 'yarn/1.22.4 npm/? node/v12.18.3 darwin x64' const FIXTURE_CWD = path.resolve(fixturesPath, 'getSchema') -async function testSchemaPath( - fixtureName: string, - schemaPathFromArgs?: string, -) { +async function testSchemaPath(fixtureName: string, schemaPathFromArgs?: string) { const cwd = path.resolve(FIXTURE_CWD, fixtureName) let syncResult: string | null | Error @@ -85,10 +79,7 @@ Object { }) it('throws if schema args path is invalid', async () => { - const res = await testSchemaPath( - 'pkg-json-with-schema-args', - path.resolve(FIXTURE_CWD, 'wrong_path'), - ) + const res = await testSchemaPath('pkg-json-with-schema-args', path.resolve(FIXTURE_CWD, 'wrong_path')) expect(res).toMatchInlineSnapshot(` Object { diff --git a/packages/sdk/src/__tests__/migrateEngineCommands.test.ts b/packages/sdk/src/__tests__/migrateEngineCommands.test.ts index 26c998e582d2..6398ea5336bf 100644 --- a/packages/sdk/src/__tests__/migrateEngineCommands.test.ts +++ b/packages/sdk/src/__tests__/migrateEngineCommands.test.ts @@ -1,9 +1,4 @@ -import { - execaCommand, - doesSqliteDbExist, - canConnectToDatabase, - createDatabase, -} from '../migrateEngineCommands' +import { execaCommand, doesSqliteDbExist, canConnectToDatabase, createDatabase } from '../migrateEngineCommands' import tempy from 'tempy' describe('execaCommand', () => { @@ -25,46 +20,33 @@ describe('execaCommand', () => { describe('doesSqliteDbExist', () => { test('exist - sqlite:', async () => { - await expect( - doesSqliteDbExist('sqlite:./introspection/blog.db', __dirname), - ).resolves.toEqual(true) + await expect(doesSqliteDbExist('sqlite:./introspection/blog.db', __dirname)).resolves.toEqual(true) }) test('exist - file:', async () => { - await expect( - doesSqliteDbExist('file:./introspection/blog.db', __dirname), - ).resolves.toEqual(true) + await expect(doesSqliteDbExist('file:./introspection/blog.db', __dirname)).resolves.toEqual(true) }) test('does not exist - sqlite:', async () => { - await expect( - doesSqliteDbExist('sqlite:./doesnotexist.db', __dirname), - ).resolves.toEqual(false) + await expect(doesSqliteDbExist('sqlite:./doesnotexist.db', __dirname)).resolves.toEqual(false) }) test('does not exist - file:', async () => { - await expect( - doesSqliteDbExist('file:./doesnotexist.db', __dirname), - ).resolves.toEqual(false) + await expect(doesSqliteDbExist('file:./doesnotexist.db', __dirname)).resolves.toEqual(false) }) test('should error if no schemaDir and no schema found', async () => { - await expect( - doesSqliteDbExist('file:./doesnotexist.db'), - ).rejects.toThrowError() + await expect(doesSqliteDbExist('file:./doesnotexist.db')).rejects.toThrowError() }) }) describe('canConnectToDatabase', () => { test('sqlite - can', async () => { - await expect( - canConnectToDatabase('sqlite:./introspection/blog.db', __dirname), - ).resolves.toEqual(true) + await expect(canConnectToDatabase('sqlite:./introspection/blog.db', __dirname)).resolves.toEqual(true) }) test('sqlite - cannot', async () => { - await expect(canConnectToDatabase('file:./doesnotexist.db')).resolves - .toMatchInlineSnapshot(` + await expect(canConnectToDatabase('file:./doesnotexist.db')).resolves.toMatchInlineSnapshot(` Object { "code": "P1003", "message": "SQLite database file doesn't exist", @@ -74,10 +56,7 @@ describe('canConnectToDatabase', () => { test('postgresql - server does not exist', async () => { await expect( - canConnectToDatabase( - 'postgresql://johndoe:randompassword@doesnotexist:5432/mydb?schema=public', - __dirname, - ), + canConnectToDatabase('postgresql://johndoe:randompassword@doesnotexist:5432/mydb?schema=public', __dirname), ).resolves.toMatchInlineSnapshot(` Object { "code": "P1001", @@ -91,30 +70,22 @@ describe('canConnectToDatabase', () => { describe('createDatabase', () => { test('sqlite - already exist', async () => { - await expect( - createDatabase('sqlite:./introspection/blog.db', __dirname), - ).resolves.toEqual(false) + await expect(createDatabase('sqlite:./introspection/blog.db', __dirname)).resolves.toEqual(false) }) test('sqlite - does not exist', async () => { - await expect( - createDatabase('sqlite:./doesnotexist.db', tempy.directory()), - ).resolves.toEqual(true) + await expect(createDatabase('sqlite:./doesnotexist.db', tempy.directory())).resolves.toEqual(true) }) test('sqlite - invalid cwd (file path instead of directory)', async () => { - await expect( - createDatabase('sqlite:./doesnotexist.db', tempy.file()), - ).rejects.toThrowErrorMatchingInlineSnapshot(`"Migration engine exited."`) + await expect(createDatabase('sqlite:./doesnotexist.db', tempy.file())).rejects.toThrowErrorMatchingInlineSnapshot( + `"Migration engine exited."`, + ) }) test('postgresql - server does not exist', async () => { - await expect( - createDatabase( - 'postgresql://johndoe:randompassword@doesnotexist:5432/mydb?schema=public', - __dirname, - ), - ).rejects.toThrowErrorMatchingInlineSnapshot(` + await expect(createDatabase('postgresql://johndoe:randompassword@doesnotexist:5432/mydb?schema=public', __dirname)) + .rejects.toThrowErrorMatchingInlineSnapshot(` "P1001: Can't reach database server at \`doesnotexist\`:\`5432\` Please make sure your database server is running at \`doesnotexist\`:\`5432\`." @@ -122,9 +93,7 @@ describe('createDatabase', () => { }) test('invalid database type', async () => { - await expect( - createDatabase('invalid:somedburl'), - ).rejects.toThrowErrorMatchingInlineSnapshot( + await expect(createDatabase('invalid:somedburl')).rejects.toThrowErrorMatchingInlineSnapshot( `"Unknown database type invalid:"`, ) }) diff --git a/packages/sdk/src/cli/Help.ts b/packages/sdk/src/cli/Help.ts index 42056f4695f8..4afac6bc3620 100644 --- a/packages/sdk/src/cli/Help.ts +++ b/packages/sdk/src/cli/Help.ts @@ -4,9 +4,7 @@ import chalk from 'chalk' * Unknown command */ export function unknownCommand(helpTemplate: string, cmd: string): HelpError { - return new HelpError( - `\n${chalk.bold.red(`!`)} Unknown command "${cmd}"\n${helpTemplate}`, - ) + return new HelpError(`\n${chalk.bold.red(`!`)} Unknown command "${cmd}"\n${helpTemplate}`) } /** diff --git a/packages/sdk/src/cli/getSchema.ts b/packages/sdk/src/cli/getSchema.ts index 7c98b030be01..b1325b2385d9 100644 --- a/packages/sdk/src/cli/getSchema.ts +++ b/packages/sdk/src/cli/getSchema.ts @@ -32,13 +32,9 @@ export async function getSchemaPathInternal( ): Promise { if (schemaPathFromArgs) { // 1. try the user custom path - const customSchemaPath = await getAbsoluteSchemaPath( - path.resolve(schemaPathFromArgs), - ) + const customSchemaPath = await getAbsoluteSchemaPath(path.resolve(schemaPathFromArgs)) if (!customSchemaPath) { - throw new Error( - `Provided --schema at ${schemaPathFromArgs} doesn't exist.`, - ) + throw new Error(`Provided --schema at ${schemaPathFromArgs} doesn't exist.`) } return customSchemaPath @@ -71,9 +67,7 @@ export type PrismaConfig = { export async function getPrismaConfigFromPackageJson(cwd: string) { const pkgJson = await readPkgUp({ cwd }) - const prismaPropertyFromPkgJson = pkgJson?.packageJson?.prisma as - | PrismaConfig - | undefined + const prismaPropertyFromPkgJson = pkgJson?.packageJson?.prisma as PrismaConfig | undefined if (!pkgJson) { return null @@ -85,9 +79,7 @@ export async function getPrismaConfigFromPackageJson(cwd: string) { } } -export async function getSchemaPathFromPackageJson( - cwd: string, -): Promise { +export async function getSchemaPathFromPackageJson(cwd: string): Promise { const prismaConfig = await getPrismaConfigFromPackageJson(cwd) if (!prismaConfig || !prismaConfig.data?.schema) { @@ -107,17 +99,11 @@ export async function getSchemaPathFromPackageJson( const absoluteSchemaPath = path.isAbsolute(schemaPathFromPkgJson) ? schemaPathFromPkgJson - : path.resolve( - path.dirname(prismaConfig.packagePath), - schemaPathFromPkgJson, - ) + : path.resolve(path.dirname(prismaConfig.packagePath), schemaPathFromPkgJson) if ((await exists(absoluteSchemaPath)) === false) { throw new Error( - `Provided schema path \`${path.relative( - cwd, - absoluteSchemaPath, - )}\` from \`${path.relative( + `Provided schema path \`${path.relative(cwd, absoluteSchemaPath)}\` from \`${path.relative( cwd, prismaConfig.packagePath, )}\` doesn't exist.`, @@ -153,8 +139,7 @@ async function resolveYarnSchema(cwd: string): Promise { for (const workspace of workspaces) { const workspacePath = path.join(workspaceRootDir, workspace.location) const workspaceSchemaPath = - getSchemaPathFromPackageJsonSync(workspacePath) ?? - getRelativeSchemaPathSync(workspacePath) + getSchemaPathFromPackageJsonSync(workspacePath) ?? getRelativeSchemaPathSync(workspacePath) if (workspaceSchemaPath) { return workspaceSchemaPath @@ -162,8 +147,7 @@ async function resolveYarnSchema(cwd: string): Promise { } const workspaceSchemaPathFromRoot = - getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? - getRelativeSchemaPathSync(workspaceRootDir) + getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? getRelativeSchemaPathSync(workspaceRootDir) if (workspaceSchemaPathFromRoot) { return workspaceSchemaPathFromRoot @@ -201,8 +185,7 @@ function resolveYarnSchemaSync(cwd: string): string | null { for (const workspace of workspaces) { const workspacePath = path.join(workspaceRootDir, workspace.location) const workspaceSchemaPath = - getSchemaPathFromPackageJsonSync(workspacePath) ?? - getRelativeSchemaPathSync(workspacePath) + getSchemaPathFromPackageJsonSync(workspacePath) ?? getRelativeSchemaPathSync(workspacePath) if (workspaceSchemaPath) { return workspaceSchemaPath @@ -210,8 +193,7 @@ function resolveYarnSchemaSync(cwd: string): string | null { } const workspaceSchemaPathFromRoot = - getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? - getRelativeSchemaPathSync(workspaceRootDir) + getSchemaPathFromPackageJsonSync(workspaceRootDir) ?? getRelativeSchemaPathSync(workspaceRootDir) if (workspaceSchemaPathFromRoot) { return workspaceSchemaPathFromRoot @@ -223,9 +205,7 @@ function resolveYarnSchemaSync(cwd: string): string | null { return null } -async function getAbsoluteSchemaPath( - schemaPath: string, -): Promise { +async function getAbsoluteSchemaPath(schemaPath: string): Promise { if (await exists(schemaPath)) { return schemaPath } @@ -233,9 +213,7 @@ async function getAbsoluteSchemaPath( return null } -export async function getRelativeSchemaPath( - cwd: string, -): Promise { +export async function getRelativeSchemaPath(cwd: string): Promise { let schemaPath = path.join(cwd, 'schema.prisma') if (await exists(schemaPath)) { return schemaPath @@ -253,9 +231,7 @@ export async function getRelativeSchemaPath( /** * Small helper that returns the directory which contains the `schema.prisma` file */ -export async function getSchemaDir( - schemaPathFromArgs?: string, -): Promise { +export async function getSchemaDir(schemaPathFromArgs?: string): Promise { if (schemaPathFromArgs) { return path.resolve(path.dirname(schemaPathFromArgs)) } @@ -306,13 +282,9 @@ export function getSchemaPathSyncInternal( ): string | null { if (schemaPathFromArgs) { // 1. Try the user custom path - const customSchemaPath = getAbsoluteSchemaPathSync( - path.resolve(schemaPathFromArgs), - ) + const customSchemaPath = getAbsoluteSchemaPathSync(path.resolve(schemaPathFromArgs)) if (!customSchemaPath) { - throw new Error( - `Provided --schema at ${schemaPathFromArgs} doesn't exist.`, - ) + throw new Error(`Provided --schema at ${schemaPathFromArgs} doesn't exist.`) } return customSchemaPath @@ -322,9 +294,7 @@ export function getSchemaPathSyncInternal( // 3. Try the conventional `./schema.prisma` or `./prisma/schema.prisma` paths // 4. Try resolving yarn workspaces and looking for a schema.prisma file there const schemaPath = - getSchemaPathFromPackageJsonSync(opts.cwd) ?? - getRelativeSchemaPathSync(opts.cwd) ?? - resolveYarnSchemaSync(opts.cwd) + getSchemaPathFromPackageJsonSync(opts.cwd) ?? getRelativeSchemaPathSync(opts.cwd) ?? resolveYarnSchemaSync(opts.cwd) if (schemaPath) { return schemaPath @@ -335,8 +305,7 @@ export function getSchemaPathSyncInternal( export function getSchemaPathFromPackageJsonSync(cwd: string): string | null { const pkgJson = readPkgUp.sync({ cwd }) - const schemaPathFromPkgJson: string | undefined = - pkgJson?.packageJson?.prisma?.schema + const schemaPathFromPkgJson: string | undefined = pkgJson?.packageJson?.prisma?.schema if (!schemaPathFromPkgJson || !pkgJson) { return null @@ -357,10 +326,10 @@ export function getSchemaPathFromPackageJsonSync(cwd: string): string | null { if (fs.existsSync(absoluteSchemaPath) === false) { throw new Error( - `Provided schema path \`${path.relative( + `Provided schema path \`${path.relative(cwd, absoluteSchemaPath)}\` from \`${path.relative( cwd, - absoluteSchemaPath, - )}\` from \`${path.relative(cwd, pkgJson.path)}\` doesn't exist.`, + pkgJson.path, + )}\` doesn't exist.`, ) } diff --git a/packages/sdk/src/cli/hashes.ts b/packages/sdk/src/cli/hashes.ts index 750e82337cd6..d5a136bc5167 100644 --- a/packages/sdk/src/cli/hashes.ts +++ b/packages/sdk/src/cli/hashes.ts @@ -12,11 +12,7 @@ export async function getProjectHash(): Promise { let projectPath = await getSchemaPath(args['--schema']) projectPath = projectPath || process.cwd() // Default to cwd if the schema couldn't be found - return crypto - .createHash('sha256') - .update(projectPath) - .digest('hex') - .substring(0, 8) + return crypto.createHash('sha256').update(projectPath).digest('hex').substring(0, 8) } /** @@ -25,9 +21,5 @@ export async function getProjectHash(): Promise { */ export function getCLIPathHash(): string { const cliPath = process.argv[1] - return crypto - .createHash('sha256') - .update(cliPath) - .digest('hex') - .substring(0, 8) + return crypto.createHash('sha256').update(cliPath).digest('hex').substring(0, 8) } diff --git a/packages/sdk/src/convertCredentials.ts b/packages/sdk/src/convertCredentials.ts index 66baa314c32a..ae8d2637ea56 100644 --- a/packages/sdk/src/convertCredentials.ts +++ b/packages/sdk/src/convertCredentials.ts @@ -70,9 +70,7 @@ export function credentialsToUri(credentials: DatabaseCredentials): string { return url.toString() } -export function uriToCredentials( - connectionString: string, -): DatabaseCredentials { +export function uriToCredentials(connectionString: string): DatabaseCredentials { let uri: NodeURL.URL try { uri = new NodeURL.URL(connectionString) diff --git a/packages/sdk/src/dotenvExpand.ts b/packages/sdk/src/dotenvExpand.ts index d2897de992b9..babdfacae14b 100644 --- a/packages/sdk/src/dotenvExpand.ts +++ b/packages/sdk/src/dotenvExpand.ts @@ -30,9 +30,7 @@ import type { DotenvConfigOutput } from 'dotenv' * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -export function dotenvExpand( - config: DotenvConfigOutput & { ignoreProcessEnv?: boolean }, -) { +export function dotenvExpand(config: DotenvConfigOutput & { ignoreProcessEnv?: boolean }) { // if ignoring process.env, use a blank object const environment = config.ignoreProcessEnv ? {} : process.env @@ -56,9 +54,7 @@ export function dotenvExpand( const key = parts[2] replacePart = parts[0].substring(prefix.length) // process.env value 'wins' over .env file's value - value = Object.hasOwnProperty.call(environment, key) - ? environment[key] - : config.parsed![key] || '' + value = Object.hasOwnProperty.call(environment, key) ? environment[key] : config.parsed![key] || '' // Resolve recursive interpolations value = interpolate(value) @@ -69,9 +65,7 @@ export function dotenvExpand( } for (const configKey in config.parsed) { - const value = Object.hasOwnProperty.call(environment, configKey) - ? environment[configKey] - : config.parsed[configKey] + const value = Object.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey] config.parsed[configKey] = interpolate(value!) } diff --git a/packages/sdk/src/drawBox.ts b/packages/sdk/src/drawBox.ts index 538bf3051080..befea63b5fc2 100644 --- a/packages/sdk/src/drawBox.ts +++ b/packages/sdk/src/drawBox.ts @@ -21,19 +21,10 @@ const chars = { } function maxLineLength(str: string): number { - return ( - str.split('\n').reduce((max, curr) => Math.max(max, stringWidth(curr)), 0) + - 2 - ) + return str.split('\n').reduce((max, curr) => Math.max(max, stringWidth(curr)), 0) + 2 } -export function drawBox({ - title, - width, - height, - str, - horizontalPadding, -}: BoxOptions): string { +export function drawBox({ title, width, height, str, horizontalPadding }: BoxOptions): string { horizontalPadding = horizontalPadding || 0 width = width || maxLineLength(str) + horizontalPadding * 2 const topLine = title @@ -41,15 +32,11 @@ export function drawBox({ ' ' + chalk.reset.bold(title) + ' ' + - chalk.grey( - chars.horizontal.repeat(width - title.length - 2 - 3) + chars.topRight, - ) + + chalk.grey(chars.horizontal.repeat(width - title.length - 2 - 3) + chars.topRight) + chalk.reset() - : chalk.grey(chars.topLeft + chars.horizontal) + - chalk.grey(chars.horizontal.repeat(width - 3) + chars.topRight) + : chalk.grey(chars.topLeft + chars.horizontal) + chalk.grey(chars.horizontal.repeat(width - 3) + chars.topRight) - const bottomLine = - chars.bottomLeft + chars.horizontal.repeat(width - 2) + chars.bottomRight + const bottomLine = chars.bottomLeft + chars.horizontal.repeat(width - 2) + chars.bottomRight const lines = str.split('\n') @@ -62,11 +49,9 @@ export function drawBox({ .map((l) => { const lineWidth = Math.min(stringWidth(l), width) const paddingRight = Math.max(width - lineWidth - 2, 0) - return `${chalk.grey(chars.vertical)}${' '.repeat( - horizontalPadding!, - )}${chalk.reset(cliTruncate(l, width - 2))}${' '.repeat( - paddingRight - horizontalPadding!, - )}${chalk.grey(chars.vertical)}` + return `${chalk.grey(chars.vertical)}${' '.repeat(horizontalPadding!)}${chalk.reset( + cliTruncate(l, width - 2), + )}${' '.repeat(paddingRight - horizontalPadding!)}${chalk.grey(chars.vertical)}` }) .join('\n') diff --git a/packages/sdk/src/engine-commands/formatSchema.ts b/packages/sdk/src/engine-commands/formatSchema.ts index ca5c16b0f0ca..86849e9e600d 100644 --- a/packages/sdk/src/engine-commands/formatSchema.ts +++ b/packages/sdk/src/engine-commands/formatSchema.ts @@ -13,13 +13,7 @@ const MAX_BUFFER = 1_000_000_000 // or a path to the schema file export async function formatSchema({ schema }: { schema: string }) export async function formatSchema({ schemaPath }: { schemaPath: string }) -export async function formatSchema({ - schemaPath, - schema, -}: { - schemaPath?: string - schema?: string -}): Promise { +export async function formatSchema({ schemaPath, schema }: { schemaPath?: string; schema?: string }): Promise { if (!schema && !schemaPath) { throw new Error(`Parameter schema or schemaPath must be passed.`) } diff --git a/packages/sdk/src/engine-commands/getConfig.ts b/packages/sdk/src/engine-commands/getConfig.ts index f7bcb3cda08d..b4d0b7f11ede 100644 --- a/packages/sdk/src/engine-commands/getConfig.ts +++ b/packages/sdk/src/engine-commands/getConfig.ts @@ -38,9 +38,7 @@ export class GetConfigError extends Error { } } // TODO add error handling functions -export async function getConfig( - options: GetConfigOptions, -): Promise { +export async function getConfig(options: GetConfigOptions): Promise { const cliEngineBinaryType = getCliQueryEngineBinaryType() let data: ConfigMetaFormat | undefined if (cliEngineBinaryType === BinaryType.libqueryEngine) { @@ -64,19 +62,13 @@ export async function getConfig( return data } -async function getConfigNodeAPI( - options: GetConfigOptions, -): Promise { +async function getConfigNodeAPI(options: GetConfigOptions): Promise { let data: ConfigMetaFormat | undefined - const queryEnginePath = await resolveBinary( - BinaryType.libqueryEngine, - options.prismaPath, - ) + const queryEnginePath = await resolveBinary(BinaryType.libqueryEngine, options.prismaPath) await isNodeAPISupported() debug(`Using CLI Query Engine (Node-API Library) at: ${queryEnginePath}`) try { - const NodeAPIQueryEngineLibrary = - load(queryEnginePath) + const NodeAPIQueryEngineLibrary = load(queryEnginePath) data = await NodeAPIQueryEngineLibrary.getConfig({ datamodel: options.datamodel, datasourceOverrides: {}, @@ -92,10 +84,7 @@ async function getConfigNodeAPI( } let message: string if (error.error_code === 'P1012') { - message = - chalk.redBright(`Schema Parsing ${error.error_code}\n\n`) + - error.message + - '\n' + message = chalk.redBright(`Schema Parsing ${error.error_code}\n\n`) + error.message + '\n' } else { message = chalk.redBright(`${error.error_code}\n\n`) + error } @@ -104,15 +93,10 @@ async function getConfigNodeAPI( return data } -async function getConfigBinary( - options: GetConfigOptions, -): Promise { +async function getConfigBinary(options: GetConfigOptions): Promise { let data: ConfigMetaFormat | undefined - const queryEnginePath = await resolveBinary( - BinaryType.queryEngine, - options.prismaPath, - ) + const queryEnginePath = await resolveBinary(BinaryType.queryEngine, options.prismaPath) debug(`Using CLI Query Engine (Binary) at: ${queryEnginePath}`) try { @@ -128,18 +112,14 @@ async function getConfigBinary( const args = options.ignoreEnvVarErrors ? ['--ignoreEnvVarErrors'] : [] - const result = await execa( - queryEnginePath, - [...engineArgs, 'cli', 'get-config', ...args], - { - cwd: options.cwd, - env: { - PRISMA_DML_PATH: tempDatamodelPath, - RUST_BACKTRACE: '1', - }, - maxBuffer: MAX_BUFFER, + const result = await execa(queryEnginePath, [...engineArgs, 'cli', 'get-config', ...args], { + cwd: options.cwd, + env: { + PRISMA_DML_PATH: tempDatamodelPath, + RUST_BACKTRACE: '1', }, - ) + maxBuffer: MAX_BUFFER, + }) if (!options.datamodelPath) { await unlink(tempDatamodelPath) @@ -155,9 +135,7 @@ async function getConfigBinary( message = `${chalk.redBright(jsonError.message)}\n` if (jsonError.error_code) { if (jsonError.error_code === 'P1012') { - message = - chalk.redBright(`Schema Parsing ${jsonError.error_code}\n\n`) + - message + message = chalk.redBright(`Schema Parsing ${jsonError.error_code}\n\n`) + message } else { message = chalk.redBright(`${jsonError.error_code}\n\n`) + message } diff --git a/packages/sdk/src/engine-commands/getDmmf.ts b/packages/sdk/src/engine-commands/getDmmf.ts index a3db3b1b4035..9e1c32a43dce 100644 --- a/packages/sdk/src/engine-commands/getDmmf.ts +++ b/packages/sdk/src/engine-commands/getDmmf.ts @@ -2,11 +2,7 @@ import Debug from '@prisma/debug' import type { NodeAPILibraryTypes } from '@prisma/engine-core' import { getCliQueryEngineBinaryType } from '@prisma/engines' import { BinaryType } from '@prisma/fetch-engine' -import type { - DataSource, - DMMF, - GeneratorConfig, -} from '@prisma/generator-helper' +import type { DataSource, DMMF, GeneratorConfig } from '@prisma/generator-helper' import { isNodeAPISupported } from '@prisma/get-platform' import chalk from 'chalk' import type { ExecaChildProcess, ExecaReturnValue } from 'execa' @@ -51,22 +47,15 @@ export async function getDMMF(options: GetDMMFOptions): Promise { } async function getDmmfNodeAPI(options: GetDMMFOptions): Promise { - const queryEnginePath = await resolveBinary( - BinaryType.libqueryEngine, - options.prismaPath, - ) + const queryEnginePath = await resolveBinary(BinaryType.libqueryEngine, options.prismaPath) await isNodeAPISupported() debug(`Using CLI Query Engine (Node-API) at: ${queryEnginePath}`) - const NodeAPIQueryEngineLibrary = - load(queryEnginePath) - const datamodel = - options.datamodel ?? fs.readFileSync(options.datamodelPath!, 'utf-8') + const NodeAPIQueryEngineLibrary = load(queryEnginePath) + const datamodel = options.datamodel ?? fs.readFileSync(options.datamodelPath!, 'utf-8') let dmmf: DMMF.Document | undefined try { - dmmf = JSON.parse( - await NodeAPIQueryEngineLibrary.dmmf(datamodel), - ) as DMMF.Document + dmmf = JSON.parse(await NodeAPIQueryEngineLibrary.dmmf(datamodel)) as DMMF.Document } catch (e: any) { const error = JSON.parse(e.message) const message = addMissingOpenSSLInfo(error.message) @@ -77,10 +66,7 @@ async function getDmmfNodeAPI(options: GetDMMFOptions): Promise { async function getDmmfBinary(options: GetDMMFOptions): Promise { let result: ExecaChildProcess | undefined | ExecaReturnValue - const queryEnginePath = await resolveBinary( - BinaryType.queryEngine, - options.prismaPath, - ) + const queryEnginePath = await resolveBinary(BinaryType.queryEngine, options.prismaPath) debug(`Using CLI Query Engine (Binary) at: ${queryEnginePath}`) try { @@ -89,10 +75,7 @@ async function getDmmfBinary(options: GetDMMFOptions): Promise { try { tempDatamodelPath = await tmpWrite(options.datamodel!) } catch (err) { - throw new Error( - chalk.redBright.bold('Get DMMF ') + - 'unable to write temp data model path', - ) + throw new Error(chalk.redBright.bold('Get DMMF ') + 'unable to write temp data model path') } } const execaOptions = { @@ -112,11 +95,7 @@ async function getDmmfBinary(options: GetDMMFOptions): Promise { await unlink(tempDatamodelPath) } - if ( - result.stdout.includes('Please wait until the') && - options.retry && - options.retry > 0 - ) { + if (result.stdout.includes('Please wait until the') && options.retry && options.retry > 0) { debug('Retrying after "Please wait until"') await new Promise((r) => setTimeout(r, 5000)) return getDMMF({ @@ -133,11 +112,7 @@ async function getDmmfBinary(options: GetDMMFOptions): Promise { } catch (e: any) { debug('getDMMF failed', e) // If this unlikely event happens, try it at least once more - if ( - e.message.includes('Command failed with exit code 26 (ETXTBSY)') && - options.retry && - options.retry > 0 - ) { + if (e.message.includes('Command failed with exit code 26 (ETXTBSY)') && options.retry && options.retry > 0) { await new Promise((resolve) => setTimeout(resolve, 500)) debug('Retrying after ETXTBSY') return getDMMF({ diff --git a/packages/sdk/src/engine-commands/getVersion.ts b/packages/sdk/src/engine-commands/getVersion.ts index ff55191548d3..dcb19d9df1af 100644 --- a/packages/sdk/src/engine-commands/getVersion.ts +++ b/packages/sdk/src/engine-commands/getVersion.ts @@ -11,10 +11,7 @@ const debug = Debug('prisma:getVersion') const MAX_BUFFER = 1_000_000_000 -export async function getVersion( - enginePath?: string, - binaryName?: BinaryType, -): Promise { +export async function getVersion(enginePath?: string, binaryName?: BinaryType): Promise { if (!binaryName) { binaryName = getCliQueryEngineBinaryType() } diff --git a/packages/sdk/src/get-generators/getGenerators.ts b/packages/sdk/src/get-generators/getGenerators.ts index 6bcdf5eced19..f7f0cae4bbab 100644 --- a/packages/sdk/src/get-generators/getGenerators.ts +++ b/packages/sdk/src/get-generators/getGenerators.ts @@ -1,18 +1,9 @@ import Debug from '@prisma/debug' -import { - fixBinaryTargets, - getOriginalBinaryTargetsValue, - printGeneratorConfig, -} from '@prisma/engine-core' +import { fixBinaryTargets, getOriginalBinaryTargetsValue, printGeneratorConfig } from '@prisma/engine-core' import { enginesVersion, getCliQueryEngineBinaryType } from '@prisma/engines' import type { DownloadOptions } from '@prisma/fetch-engine' import { download } from '@prisma/fetch-engine' -import type { - BinaryTargetsEnvValue, - EngineType, - GeneratorConfig, - GeneratorOptions, -} from '@prisma/generator-helper' +import type { BinaryTargetsEnvValue, EngineType, GeneratorConfig, GeneratorOptions } from '@prisma/generator-helper' import type { Platform } from '@prisma/get-platform' import { getPlatform, platforms } from '@prisma/get-platform' import chalk from 'chalk' @@ -28,14 +19,8 @@ import { resolveOutput } from '../resolveOutput' import { extractPreviewFeatures } from '../utils/extractPreviewFeatures' import { mapPreviewFeatures } from '../utils/mapPreviewFeatures' import { missingDatasource } from '../utils/missingDatasource' -import { - missingModelMessage, - missingModelMessageMongoDB, -} from '../utils/missingGeneratorMessage' -import { - parseBinaryTargetsEnvValue, - parseEnvValue, -} from '../utils/parseEnvValue' +import { missingModelMessage, missingModelMessageMongoDB } from '../utils/missingGeneratorMessage' +import { parseBinaryTargetsEnvValue, parseEnvValue } from '../utils/parseEnvValue' import { printConfigWarnings } from '../utils/printConfigWarnings' import { getEngineVersionForGenerator } from './utils/getEngineVersionForGenerator' import { binaryTypeToEngineType } from './utils/binaryTypeToEngineType' @@ -84,9 +69,7 @@ export async function getGenerators({ binaryPathsOverride, }: GetGeneratorOptions): Promise { if (!schemaPath) { - throw new Error( - `schemaPath for getGenerators got invalid value ${schemaPath}`, - ) + throw new Error(`schemaPath for getGenerators got invalid value ${schemaPath}`) } if (!fs.existsSync(schemaPath)) { @@ -174,18 +157,11 @@ export async function getGenerators({ generatorPath = aliases[providerValue].generatorPath paths = aliases[providerValue] } else if (predefinedGeneratorResolvers[providerValue]) { - paths = await predefinedGeneratorResolvers[providerValue]( - baseDir, - cliVersion, - ) + paths = await predefinedGeneratorResolvers[providerValue](baseDir, cliVersion) generatorPath = paths.generatorPath } - const generatorInstance = new Generator( - generatorPath, - generator, - paths?.isNode, - ) + const generatorInstance = new Generator(generatorPath, generator, paths?.isNode) await generatorInstance.init() @@ -202,14 +178,11 @@ export async function getGenerators({ fromEnvVar: null, } } else { - if ( - !generatorInstance.manifest || - !generatorInstance.manifest.defaultOutput - ) { + if (!generatorInstance.manifest || !generatorInstance.manifest.defaultOutput) { throw new Error( - `Can't resolve output dir for generator ${chalk.bold( - generator.name, - )} with provider ${chalk.bold(generator.provider)}. + `Can't resolve output dir for generator ${chalk.bold(generator.name)} with provider ${chalk.bold( + generator.provider, + )}. The generator needs to either define the \`defaultOutput\` path in the manifest or you need to define \`output\` in the datamodel.prisma file.`, ) } @@ -249,15 +222,10 @@ The generator needs to either define the \`defaultOutput\` path in the manifest // 2. Check, if all required generators are there. // Generators can say in their "requiresGenerators" property in the manifest, which other generators they depend on // This has mostly been introduced for 3rd party generators, which rely on `prisma-client-js`. - const generatorProviders: string[] = generatorConfigs.map((g) => - parseEnvValue(g.provider), - ) + const generatorProviders: string[] = generatorConfigs.map((g) => parseEnvValue(g.provider)) for (const g of generators) { - if ( - g?.manifest?.requiresGenerators && - g?.manifest?.requiresGenerators.length > 0 - ) { + if (g?.manifest?.requiresGenerators && g?.manifest?.requiresGenerators.length > 0) { for (const neededGenerator of g?.manifest?.requiresGenerators) { if (!generatorProviders.includes(neededGenerator)) { throw new Error( @@ -301,8 +269,7 @@ generator gen { // If set from env var, there is only one item // and we need to read the env var if (binaryTarget0.fromEnvVar !== null) { - const parsedBinaryTargetsEnvValue = - parseBinaryTargetsEnvValue(binaryTarget0) + const parsedBinaryTargetsEnvValue = parseBinaryTargetsEnvValue(binaryTarget0) // remove item and replace with parsed values // value is an array @@ -329,11 +296,7 @@ generator gen { binaryTarget.value = platform } - if ( - !neededVersions[neededVersion].binaryTargets.find( - (object) => object.value === binaryTarget.value, - ) - ) { + if (!neededVersions[neededVersion].binaryTargets.find((object) => object.value === binaryTarget.value)) { neededVersions[neededVersion].binaryTargets.push(binaryTarget) } } @@ -351,16 +314,10 @@ generator gen { }) for (const generator of generators) { if (generator.manifest && generator.manifest.requiresEngines) { - const engineVersion = getEngineVersionForGenerator( - generator.manifest, - version, - ) + const engineVersion = getEngineVersionForGenerator(generator.manifest, version) const binaryPaths = binaryPathsByVersion[engineVersion] // pick only the engines that we need for this generator - const generatorBinaryPaths = pick( - binaryPaths, - generator.manifest.requiresEngines, - ) + const generatorBinaryPaths = pick(binaryPaths, generator.manifest.requiresEngines) debug({ generatorBinaryPaths }) generator.setBinaryPaths(generatorBinaryPaths) @@ -382,10 +339,7 @@ generator gen { const options = { ...generator.options, dmmf: customDmmf } debug('generator.manifest.prettyName', generator.manifest.prettyName) debug('options', options) - debug( - 'options.generator.binaryTargets', - options.generator.binaryTargets, - ) + debug('options.generator.binaryTargets', options.generator.binaryTargets) generator.setOptions(options) } } @@ -422,9 +376,7 @@ export type GetBinaryPathsByVersionInput = { * @param version Version of the binary, commit hash of https://github.com/prisma/prisma-engine/commits/master * @param printDownloadProgress `boolean` to print download progress or not */ -export async function getGenerator( - options: GetGeneratorOptions, -): Promise { +export async function getGenerator(options: GetGeneratorOptions): Promise { const generators = await getGenerators(options) return generators[0] } @@ -441,9 +393,7 @@ const oldToNewBinaryTargetsMapping = { 'linux-glibc-libssl1.1.0': 'debian-openssl1.1.x', } -async function validateGenerators( - generators: GeneratorConfig[], -): Promise { +async function validateGenerators(generators: GeneratorConfig[]): Promise { const platform = await getPlatform() for (const generator of generators) { @@ -452,12 +402,10 @@ async function validateGenerators( 1. Rename ${chalk.red('provider = "photonjs"')} to ${chalk.green( 'provider = "prisma-client-js"', )} in your ${chalk.bold('schema.prisma')} file. - 2. Replace your ${chalk.bold('package.json')}'s ${chalk.red( - '@prisma/photon', - )} dependency to ${chalk.green('@prisma/client')} - 3. Replace ${chalk.red( - "import { Photon } from '@prisma/photon'", - )} with ${chalk.green( + 2. Replace your ${chalk.bold('package.json')}'s ${chalk.red('@prisma/photon')} dependency to ${chalk.green( + '@prisma/client', + )} + 3. Replace ${chalk.red("import { Photon } from '@prisma/photon'")} with ${chalk.green( "import { PrismaClient } from '@prisma/client'", )} in your code. 4. Run ${chalk.green('prisma generate')} again. @@ -490,18 +438,14 @@ Please use the PRISMA_QUERY_ENGINE_BINARY env var instead to pin the binary targ for (const resolvedBinaryTarget of resolvedBinaryTargets) { if (oldToNewBinaryTargetsMapping[resolvedBinaryTarget]) { throw new Error( - `Binary target ${chalk.red.bold( - resolvedBinaryTarget, - )} is deprecated. Please use ${chalk.green.bold( + `Binary target ${chalk.red.bold(resolvedBinaryTarget)} is deprecated. Please use ${chalk.green.bold( oldToNewBinaryTargetsMapping[resolvedBinaryTarget], )} instead.`, ) } if (!knownBinaryTargets.includes(resolvedBinaryTarget as Platform)) { throw new Error( - `Unknown binary target ${chalk.red( - resolvedBinaryTarget, - )} in generator ${chalk.bold(generator.name)}. + `Unknown binary target ${chalk.red(resolvedBinaryTarget)} in generator ${chalk.bold(generator.name)}. Possible binaryTargets: ${chalk.greenBright(knownBinaryTargets.join(', '))}`, ) } @@ -510,14 +454,10 @@ Possible binaryTargets: ${chalk.greenBright(knownBinaryTargets.join(', '))}`, // Only show warning if resolvedBinaryTargets // is missing current platform if (!resolvedBinaryTargets.includes(platform)) { - const originalBinaryTargetsConfig = getOriginalBinaryTargetsValue( - generator.binaryTargets, - ) + const originalBinaryTargetsConfig = getOriginalBinaryTargetsValue(generator.binaryTargets) if (generator) { - console.log(`${chalk.yellow( - 'Warning:', - )} Your current platform \`${chalk.bold( + console.log(`${chalk.yellow('Warning:')} Your current platform \`${chalk.bold( platform, )}\` is not included in your generator's \`binaryTargets\` configuration ${JSON.stringify( originalBinaryTargetsConfig, diff --git a/packages/sdk/src/get-generators/utils/check-feature-flags/checkFeatureFlags.ts b/packages/sdk/src/get-generators/utils/check-feature-flags/checkFeatureFlags.ts index 301bd2838d65..38e91fd67f5d 100644 --- a/packages/sdk/src/get-generators/utils/check-feature-flags/checkFeatureFlags.ts +++ b/packages/sdk/src/get-generators/utils/check-feature-flags/checkFeatureFlags.ts @@ -12,10 +12,7 @@ function checkMongoFeatureFlag(config: ConfigMetaFormat) { if ( config.datasources.some((d) => d.provider === 'mongodb') && !config.generators.some((g) => { - return g.previewFeatures.some( - (previewFeature) => - previewFeature.toLowerCase() === 'mongoDb'.toLowerCase(), - ) + return g.previewFeatures.some((previewFeature) => previewFeature.toLowerCase() === 'mongoDb'.toLowerCase()) }) ) { throw new Error(mongoFeatureFlagMissingMessage) @@ -27,10 +24,7 @@ function checkProxyFeatureFlag(config: ConfigMetaFormat) { (config.generators.some((g) => g.config.engineType === 'dataproxy') || process.env.PRISMA_CLIENT_ENGINE_TYPE === 'dataproxy') && !config.generators.some((g) => { - return g.previewFeatures.some( - (previewFeature) => - previewFeature.toLowerCase() === 'dataProxy'.toLowerCase(), - ) + return g.previewFeatures.some((previewFeature) => previewFeature.toLowerCase() === 'dataProxy'.toLowerCase()) }) ) { throw new Error(proxyFeatureFlagMissingMessage) diff --git a/packages/sdk/src/get-generators/utils/check-feature-flags/mongoFeatureFlagMissingMessage.ts b/packages/sdk/src/get-generators/utils/check-feature-flags/mongoFeatureFlagMissingMessage.ts index dff540edb14e..5cafa47f6137 100644 --- a/packages/sdk/src/get-generators/utils/check-feature-flags/mongoFeatureFlagMissingMessage.ts +++ b/packages/sdk/src/get-generators/utils/check-feature-flags/mongoFeatureFlagMissingMessage.ts @@ -2,9 +2,7 @@ import chalk from 'chalk' import { highlightDatamodel } from '../../../highlight/highlight' import { link } from '../../../link' -export const mongoFeatureFlagMissingMessage = `\nIn order to use the ${chalk.bold( - 'mongodb', -)} provider, +export const mongoFeatureFlagMissingMessage = `\nIn order to use the ${chalk.bold('mongodb')} provider, you need to set the ${chalk.green('mongodb')} feature flag. You can define the feature flag like this: diff --git a/packages/sdk/src/get-generators/utils/check-feature-flags/proxyFeatureFlagMissingMessage.ts b/packages/sdk/src/get-generators/utils/check-feature-flags/proxyFeatureFlagMissingMessage.ts index feeb2a936111..c96394a8c218 100644 --- a/packages/sdk/src/get-generators/utils/check-feature-flags/proxyFeatureFlagMissingMessage.ts +++ b/packages/sdk/src/get-generators/utils/check-feature-flags/proxyFeatureFlagMissingMessage.ts @@ -2,9 +2,7 @@ import chalk from 'chalk' import { highlightDatamodel } from '../../../highlight/highlight' import { link } from '../../../link' -export const proxyFeatureFlagMissingMessage = `\nIn order to use the ${chalk.bold( - 'dataproxy', -)} engine, +export const proxyFeatureFlagMissingMessage = `\nIn order to use the ${chalk.bold('dataproxy')} engine, you need to set the ${chalk.green('dataProxy')} feature flag. You can define the feature flag like this: diff --git a/packages/sdk/src/get-generators/utils/getBinaryPathsByVersion.ts b/packages/sdk/src/get-generators/utils/getBinaryPathsByVersion.ts index 16b87fd8a777..cf34a65a5bee 100644 --- a/packages/sdk/src/get-generators/utils/getBinaryPathsByVersion.ts +++ b/packages/sdk/src/get-generators/utils/getBinaryPathsByVersion.ts @@ -1,13 +1,7 @@ import { enginesVersion } from '@prisma/engines' -import type { - BinaryDownloadConfiguration, - DownloadOptions, -} from '@prisma/fetch-engine' +import type { BinaryDownloadConfiguration, DownloadOptions } from '@prisma/fetch-engine' import { download } from '@prisma/fetch-engine' -import type { - BinaryPaths, - BinaryTargetsEnvValue, -} from '@prisma/generator-helper' +import type { BinaryPaths, BinaryTargetsEnvValue } from '@prisma/generator-helper' import type { Platform } from '@prisma/get-platform' import makeDir from 'make-dir' import path from 'path' @@ -37,12 +31,7 @@ export async function getBinaryPathsByVersion({ neededVersion.binaryTargets = [{ fromEnvVar: null, value: platform }] } - if ( - process.env.NETLIFY && - !neededVersion.binaryTargets.find( - (object) => object.value === 'rhel-openssl-1.0.x', - ) - ) { + if (process.env.NETLIFY && !neededVersion.binaryTargets.find((object) => object.value === 'rhel-openssl-1.0.x')) { neededVersion.binaryTargets.push({ fromEnvVar: null, value: 'rhel-openssl-1.0.x', @@ -53,21 +42,17 @@ export async function getBinaryPathsByVersion({ let binaryTargetBaseDir = eval(`require('path').join(__dirname, '..')`) if (version !== currentVersion) { - binaryTargetBaseDir = path.join( - binaryTargetBaseDir, - `./engines/${currentVersion}/`, - ) + binaryTargetBaseDir = path.join(binaryTargetBaseDir, `./engines/${currentVersion}/`) await makeDir(binaryTargetBaseDir).catch((e) => console.error(e)) } - const binariesConfig: BinaryDownloadConfiguration = - neededVersion.engines.reduce((acc, curr) => { - // only download the binary, of not already covered by the `binaryPathsOverride` - if (!binaryPathsOverride?.[curr]) { - acc[engineTypeToBinaryType(curr)] = binaryTargetBaseDir - } - return acc - }, Object.create(null)) + const binariesConfig: BinaryDownloadConfiguration = neededVersion.engines.reduce((acc, curr) => { + // only download the binary, of not already covered by the `binaryPathsOverride` + if (!binaryPathsOverride?.[curr]) { + acc[engineTypeToBinaryType(curr)] = binaryTargetBaseDir + } + return acc + }, Object.create(null)) if (Object.values(binariesConfig).length > 0) { // Convert BinaryTargetsEnvValue[] to Platform[] @@ -78,30 +63,19 @@ export async function getBinaryPathsByVersion({ const downloadParams: DownloadOptions = { binaries: binariesConfig, binaryTargets: platforms, - showProgress: - typeof printDownloadProgress === 'boolean' - ? printDownloadProgress - : true, - version: - currentVersion && currentVersion !== 'latest' - ? currentVersion - : enginesVersion, + showProgress: typeof printDownloadProgress === 'boolean' ? printDownloadProgress : true, + version: currentVersion && currentVersion !== 'latest' ? currentVersion : enginesVersion, skipDownload, } const binaryPathsWithEngineType = await download(downloadParams) - const binaryPaths: BinaryPaths = mapKeys( - binaryPathsWithEngineType, - binaryTypeToEngineType, - ) + const binaryPaths: BinaryPaths = mapKeys(binaryPathsWithEngineType, binaryTypeToEngineType) binaryPathsByVersion[currentVersion] = binaryPaths } if (binaryPathsOverride) { const overrideEngines = Object.keys(binaryPathsOverride) - const enginesCoveredByOverride = neededVersion.engines.filter((engine) => - overrideEngines.includes(engine), - ) + const enginesCoveredByOverride = neededVersion.engines.filter((engine) => overrideEngines.includes(engine)) if (enginesCoveredByOverride.length > 0) { for (const engine of enginesCoveredByOverride) { const enginePath = binaryPathsOverride[engine]! diff --git a/packages/sdk/src/getPackedPackage.ts b/packages/sdk/src/getPackedPackage.ts index 22efb123d3e0..cb3a08ddc814 100644 --- a/packages/sdk/src/getPackedPackage.ts +++ b/packages/sdk/src/getPackedPackage.ts @@ -17,15 +17,9 @@ const del = promisify(rimraf) const readdir = promisify(fs.readdir) const rename = promisify(fs.rename) -export async function getPackedPackage( - name: string, - target?: string, - packageDir?: string, -): Promise { +export async function getPackedPackage(name: string, target?: string, packageDir?: string): Promise { packageDir = - packageDir || - (await resolvePkg(name, { basedir: process.cwd() })) || - (await resolvePkg(name, { basedir: target })) + packageDir || (await resolvePkg(name, { basedir: process.cwd() })) || (await resolvePkg(name, { basedir: target })) if (!packageDir) { const pkg = await readPkgUp({ @@ -41,9 +35,7 @@ export async function getPackedPackage( } if (!packageDir) { - throw new Error( - `Error in getPackage: Could not resolve package ${name} from ${__dirname}`, - ) + throw new Error(`Error in getPackage: Could not resolve package ${name} from ${__dirname}`) } const tmpDir = tempy.directory() // thanks Sindre const archivePath = path.join(tmpDir, `package.tgz`) @@ -51,9 +43,7 @@ export async function getPackedPackage( // Check if yarn is available. const isYarn = await hasYarn(packageDir) - const packCmd = isYarn - ? ['yarn', 'pack', '-f', archivePath] - : ['npm', 'pack', packageDir] + const packCmd = isYarn ? ['yarn', 'pack', '-f', archivePath] : ['npm', 'pack', packageDir] // shell-quote args const escapedCmd = quote(packCmd) diff --git a/packages/sdk/src/highlight/languages/dml.ts b/packages/sdk/src/highlight/languages/dml.ts index e6be49deb6bb..b1ec2cdd2077 100644 --- a/packages/sdk/src/highlight/languages/dml.ts +++ b/packages/sdk/src/highlight/languages/dml.ts @@ -3,13 +3,7 @@ import type { SyntaxDefinition } from '../types' export const dml: SyntaxDefinition = { string: [/\"(.*)\"/g, /\'(.*)\'/g], directive: { pattern: /(@.*)/g }, - entity: [ - /model\s+\w+/g, - /enum\s+\w+/g, - /datasource\s+\w+/g, - /source\s+\w+/g, - /generator\s+\w+/g, - ], + entity: [/model\s+\w+/g, /enum\s+\w+/g, /datasource\s+\w+/g, /source\s+\w+/g, /generator\s+\w+/g], comment: /#.*/g, value: [/\b\s+(\w+)/g], punctuation: /(\:|}|{|"|=)/g, diff --git a/packages/sdk/src/highlight/languages/sql.ts b/packages/sdk/src/highlight/languages/sql.ts index 94e98a350c54..804471c39b50 100644 --- a/packages/sdk/src/highlight/languages/sql.ts +++ b/packages/sdk/src/highlight/languages/sql.ts @@ -17,8 +17,7 @@ export const sql: SyntaxDefinition = { greedy: true, lookbehind: true, }, - function: - /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too? + function: /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too? keyword: /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i, boolean: /\b(?:TRUE|FALSE|NULL)\b/i, diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 22565c39849a..990a09f8fcfd 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -33,26 +33,15 @@ export { getCommandWithExecutor } from './getCommandWithExecutor' export { getGenerator, getGenerators } from './get-generators/getGenerators' export type { ProviderAliases } from './get-generators/getGenerators' export { getPackedPackage } from './getPackedPackage' -export { - highlightDatamodel, - highlightSql, - highlightTS, -} from './highlight/highlight' +export { highlightDatamodel, highlightSql, highlightTS } from './highlight/highlight' export { IntrospectionEngine } from './IntrospectionEngine' -export type { - IntrospectionSchemaVersion, - IntrospectionWarnings, -} from './IntrospectionEngine' +export type { IntrospectionSchemaVersion, IntrospectionWarnings } from './IntrospectionEngine' export { isCi } from './isCi' export { isCurrentBinInstalledGlobally } from './isCurrentBinInstalledGlobally' export { keyBy } from './keyBy' export { link } from './link' export * as logger from './logger' -export { - canConnectToDatabase, - createDatabase, - dropDatabase, -} from './migrateEngineCommands' +export { canConnectToDatabase, createDatabase, dropDatabase } from './migrateEngineCommands' export { MigrateEngineExitCode } from './migrateEngineCommands' export type { MigrateEngineLogLine } from './migrateEngineCommands' export { ErrorArea, RustPanic } from './panic' @@ -67,10 +56,7 @@ export { getEnvPaths } from './utils/getEnvPaths' export { mapPreviewFeatures } from './utils/mapPreviewFeatures' export { maskSchema } from './utils/maskSchema' export { missingGeneratorMessage } from './utils/missingGeneratorMessage' -export { - parseBinaryTargetsEnvValue, - parseEnvValue, -} from './utils/parseEnvValue' +export { parseBinaryTargetsEnvValue, parseEnvValue } from './utils/parseEnvValue' export { printConfigWarnings } from './utils/printConfigWarnings' export { load } from './utils/load' export { trimBlocksFromSchema, trimNewLine } from './utils/trimBlocksFromSchema' diff --git a/packages/sdk/src/isCurrentBinInstalledGlobally.ts b/packages/sdk/src/isCurrentBinInstalledGlobally.ts index 2535b69455fa..3c1ed0ef0f2a 100644 --- a/packages/sdk/src/isCurrentBinInstalledGlobally.ts +++ b/packages/sdk/src/isCurrentBinInstalledGlobally.ts @@ -5,12 +5,8 @@ import globalDirectories from 'global-dirs' export function isCurrentBinInstalledGlobally(): 'npm' | 'yarn' | false { try { const realPrismaPath = fs.realpathSync(process.argv[1]) - const usingGlobalYarn = - realPrismaPath.indexOf(globalDirectories.yarn.packages) === 0 - const usingGlobalNpm = - realPrismaPath.indexOf( - fs.realpathSync(globalDirectories.npm.packages), - ) === 0 + const usingGlobalYarn = realPrismaPath.indexOf(globalDirectories.yarn.packages) === 0 + const usingGlobalNpm = realPrismaPath.indexOf(fs.realpathSync(globalDirectories.npm.packages)) === 0 if (usingGlobalNpm) { return 'npm' diff --git a/packages/sdk/src/keyBy.ts b/packages/sdk/src/keyBy.ts index 9e33b9ed540c..2316ea533db5 100644 --- a/packages/sdk/src/keyBy.ts +++ b/packages/sdk/src/keyBy.ts @@ -7,10 +7,7 @@ export interface Dictionary { * @param collection Any array-like data structure. * @param iteratee Callback to be called on every element. */ -export const keyBy: ( - collection: T[], - iteratee: (value: T) => string, -) => Dictionary = (collection, iteratee) => { +export const keyBy: (collection: T[], iteratee: (value: T) => string) => Dictionary = (collection, iteratee) => { return collection.reduce((acc, curr) => { acc[iteratee(curr)] = curr return acc diff --git a/packages/sdk/src/migrateEngineCommands.ts b/packages/sdk/src/migrateEngineCommands.ts index ceffad780588..4cdb25588ea2 100644 --- a/packages/sdk/src/migrateEngineCommands.ts +++ b/packages/sdk/src/migrateEngineCommands.ts @@ -44,13 +44,7 @@ interface LogFields { } // https://github.com/prisma/specs/tree/master/errors#common -export type DatabaseErrorCodes = - | 'P1000' - | 'P1001' - | 'P1002' - | 'P1003' - | 'P1009' - | 'P1010' +export type DatabaseErrorCodes = 'P1000' | 'P1001' | 'P1002' | 'P1003' | 'P1009' | 'P1010' export type ConnectionResult = true | ConnectionError @@ -114,10 +108,7 @@ export async function canConnectToDatabase( if (e.stderr) { const logs = parseJsonFromStderr(e.stderr) - const error = logs.find( - (it) => - it.level === 'ERROR' && it.target === 'migration_engine::logger', - ) + const error = logs.find((it) => it.level === 'ERROR' && it.target === 'migration_engine::logger') if (error && error.fields.error_code && error.fields.message) { return { @@ -125,11 +116,7 @@ export async function canConnectToDatabase( message: error.fields.message, } } else { - throw new Error( - `Migration engine error:\n${logs - .map((log) => log.fields.message) - .join('\n')}`, - ) + throw new Error(`Migration engine error:\n${logs.map((log) => log.fields.message).join('\n')}`) } } else { throw new Error(`Migration engine exited.`) @@ -139,16 +126,8 @@ export async function canConnectToDatabase( return true } -export async function createDatabase( - connectionString: string, - cwd = process.cwd(), - migrationEnginePath?: string, -) { - const dbExists = await canConnectToDatabase( - connectionString, - cwd, - migrationEnginePath, - ) +export async function createDatabase(connectionString: string, cwd = process.cwd(), migrationEnginePath?: string) { + const dbExists = await canConnectToDatabase(connectionString, cwd, migrationEnginePath) // If database is already created, stop here, don't create it if (dbExists === true) { @@ -169,19 +148,12 @@ export async function createDatabase( if (e.stderr) { const logs = parseJsonFromStderr(e.stderr) - const error = logs.find( - (it) => - it.level === 'ERROR' && it.target === 'migration_engine::logger', - ) + const error = logs.find((it) => it.level === 'ERROR' && it.target === 'migration_engine::logger') if (error && error.fields.error_code && error.fields.message) { throw new Error(`${error.fields.error_code}: ${error.fields.message}`) } else { - throw new Error( - `Migration engine error:\n${logs - .map((log) => log.fields.message) - .join('\n')}`, - ) + throw new Error(`Migration engine error:\n${logs.map((log) => log.fields.message).join('\n')}`) } } else { throw new Error(`Migration engine exited.`) @@ -189,11 +161,7 @@ export async function createDatabase( } } -export async function dropDatabase( - connectionString: string, - cwd = process.cwd(), - migrationEnginePath?: string, -) { +export async function dropDatabase(connectionString: string, cwd = process.cwd(), migrationEnginePath?: string) { try { const result = await execaCommand({ connectionString, @@ -201,31 +169,17 @@ export async function dropDatabase( migrationEnginePath, engineCommandName: 'drop-database', }) - if ( - result && - result.exitCode === 0 && - result.stderr.includes('The database was successfully dropped') - ) { + if (result && result.exitCode === 0 && result.stderr.includes('The database was successfully dropped')) { return true } else { // We should not arrive here normally - throw Error( - `An error occurred during the drop: ${JSON.stringify( - result, - undefined, - 2, - )}`, - ) + throw Error(`An error occurred during the drop: ${JSON.stringify(result, undefined, 2)}`) } } catch (e: any) { if (e.stderr) { const logs = parseJsonFromStderr(e.stderr) - throw new Error( - `Migration engine error:\n${logs - .map((log) => log.fields.message) - .join('\n')}`, - ) + throw new Error(`Migration engine error:\n${logs.map((log) => log.fields.message).join('\n')}`) } else { throw new Error(`Migration engine exited.`) } @@ -241,26 +195,18 @@ export async function execaCommand({ connectionString: string cwd: string migrationEnginePath?: string - engineCommandName: - | 'create-database' - | 'drop-database' - | 'can-connect-to-database' + engineCommandName: 'create-database' | 'drop-database' | 'can-connect-to-database' }) { - migrationEnginePath = - migrationEnginePath || (await resolveBinary(BinaryType.migrationEngine)) + migrationEnginePath = migrationEnginePath || (await resolveBinary(BinaryType.migrationEngine)) try { - return await execa( - migrationEnginePath, - ['cli', '--datasource', connectionString, engineCommandName], - { - cwd, - env: { - RUST_BACKTRACE: '1', - RUST_LOG: 'info', - }, + return await execa(migrationEnginePath, ['cli', '--datasource', connectionString, engineCommandName], { + cwd, + env: { + RUST_BACKTRACE: '1', + RUST_LOG: 'info', }, - ) + }) } catch (_e) { const e = _e as execa.ExecaError @@ -277,10 +223,7 @@ export async function execaCommand({ } } -export async function doesSqliteDbExist( - connectionString: string, - schemaDir?: string, -): Promise { +export async function doesSqliteDbExist(connectionString: string, schemaDir?: string): Promise { let filePath = connectionString if (filePath.startsWith('file:')) { diff --git a/packages/sdk/src/pick.ts b/packages/sdk/src/pick.ts index 1a37d17c5d4a..4aeb10876f11 100644 --- a/packages/sdk/src/pick.ts +++ b/packages/sdk/src/pick.ts @@ -1,7 +1,4 @@ -export function pick( - obj: T, - keys: U[], -): Pick { +export function pick(obj: T, keys: U[]): Pick { return Object.entries(obj).reduce>((acc, [key, value]) => { if (keys.includes(key as U)) { acc[key] = value diff --git a/packages/sdk/src/predefinedGeneratorResolvers.ts b/packages/sdk/src/predefinedGeneratorResolvers.ts index a8bce3379225..0d693a52e63a 100644 --- a/packages/sdk/src/predefinedGeneratorResolvers.ts +++ b/packages/sdk/src/predefinedGeneratorResolvers.ts @@ -17,10 +17,7 @@ export type GeneratorPaths = { isNode?: boolean } -export type GeneratorResolver = ( - baseDir: string, - version?: string, -) => Promise +export type GeneratorResolver = (baseDir: string, version?: string) => Promise export type PredefinedGeneratorResolvers = { [generatorName: string]: GeneratorResolver @@ -60,12 +57,10 @@ export const predefinedGeneratorResolvers: PredefinedGeneratorResolvers = { 1. Rename ${chalk.red('provider = "photonjs"')} to ${chalk.green( 'provider = "prisma-client-js"', )} in your ${chalk.bold('schema.prisma')} file. - 2. Replace your ${chalk.bold('package.json')}'s ${chalk.red( - '@prisma/photon', - )} dependency to ${chalk.green('@prisma/client')} - 3. Replace ${chalk.red( - "import { Photon } from '@prisma/photon'", - )} with ${chalk.green( + 2. Replace your ${chalk.bold('package.json')}'s ${chalk.red('@prisma/photon')} dependency to ${chalk.green( + '@prisma/client', + )} + 3. Replace ${chalk.red("import { Photon } from '@prisma/photon'")} with ${chalk.green( "import { PrismaClient } from '@prisma/client'", )} in your code. 4. Run ${chalk.green(getCommandWithExecutor('prisma generate'))} again. @@ -98,10 +93,7 @@ export const predefinedGeneratorResolvers: PredefinedGeneratorResolvers = { "license": "ISC" } ` - fs.writeFileSync( - path.join(process.cwd(), 'package.json'), - defaultPackageJson, - ) + fs.writeFileSync(path.join(process.cwd(), 'package.json'), defaultPackageJson) console.info(`āœ” Created ${chalk.bold.green('./package.json')}`) } @@ -114,27 +106,23 @@ export const predefinedGeneratorResolvers: PredefinedGeneratorResolvers = { if (!prismaClientDir) { throw new Error( `Could not resolve @prisma/client despite the installation that we just tried. -Please try to install it by hand with ${chalk.bold.greenBright( - 'npm install @prisma/client', - )} and rerun ${chalk.bold( +Please try to install it by hand with ${chalk.bold.greenBright('npm install @prisma/client')} and rerun ${chalk.bold( getCommandWithExecutor('prisma generate'), )} šŸ™.`, ) } console.info( - `\nāœ” Installed the ${chalk.bold.green( - '@prisma/client', - )} and ${chalk.bold.green('prisma')} packages in your project`, + `\nāœ” Installed the ${chalk.bold.green('@prisma/client')} and ${chalk.bold.green( + 'prisma', + )} packages in your project`, ) } if (!prismaClientDir) { throw new Error( `Could not resolve @prisma/client. -Please try to install it with ${chalk.bold.greenBright( - 'npm install @prisma/client', - )} and rerun ${chalk.bold( +Please try to install it with ${chalk.bold.greenBright('npm install @prisma/client')} and rerun ${chalk.bold( getCommandWithExecutor('prisma generate'), )} šŸ™.`, ) @@ -201,8 +189,7 @@ async function checkTypeScriptVersion() { basedir: process.cwd(), }) debug('typescriptPath', typescriptPath) - const typescriptPkg = - typescriptPath && path.join(typescriptPath, 'package.json') + const typescriptPkg = typescriptPath && path.join(typescriptPath, 'package.json') if (typescriptPkg && fs.existsSync(typescriptPkg)) { const pjson = require(typescriptPkg) const currentVersion = pjson.version @@ -212,9 +199,7 @@ async function checkTypeScriptVersion() { 'TypeScript', )} version ${currentVersion} is outdated. If you want to use Prisma Client with TypeScript please update it to version ${chalk.bold( minVersion, - )} or ${chalk.bold('newer')}. ${chalk.dim( - `TypeScript found in: ${chalk.bold(typescriptPath)}`, - )}`, + )} or ${chalk.bold('newer')}. ${chalk.dim(`TypeScript found in: ${chalk.bold(typescriptPath)}`)}`, ) } } diff --git a/packages/sdk/src/resolveBinary.ts b/packages/sdk/src/resolveBinary.ts index 4b5c2a94f6f6..fc20fe5aab53 100644 --- a/packages/sdk/src/resolveBinary.ts +++ b/packages/sdk/src/resolveBinary.ts @@ -30,15 +30,8 @@ export const engineEnvVarMap = { [BinaryType.prismaFmt]: 'PRISMA_FMT_BINARY', } export { BinaryType } -export async function resolveBinary( - name: BinaryType, - proposedPath?: string, -): Promise { - if ( - proposedPath && - !proposedPath.startsWith('/snapshot/') && - fs.existsSync(proposedPath) - ) { +export async function resolveBinary(name: BinaryType, proposedPath?: string): Promise { + if (proposedPath && !proposedPath.startsWith('/snapshot/') && fs.existsSync(proposedPath)) { return proposedPath } // tslint:disable-next-line @@ -47,9 +40,7 @@ export async function resolveBinary( if (process.env[envVar]) { if (!fs.existsSync(process.env[envVar]!)) { - throw new Error( - `Env var ${envVar} is provided, but provided path ${process.env[envVar]} can't be resolved.`, - ) + throw new Error(`Env var ${envVar} is provided, but provided path ${process.env[envVar]} can't be resolved.`) } return process.env[envVar]! } @@ -80,11 +71,11 @@ export async function resolveBinary( } throw new Error( - `Could not find ${name} binary. Searched in ${path.join( + `Could not find ${name} binary. Searched in ${path.join(dir, '..', binaryName)} and ${path.join( dir, - '..', + '../..', binaryName, - )} and ${path.join(dir, '../..', binaryName)}`, + )}`, ) } diff --git a/packages/sdk/src/resolveOutput.ts b/packages/sdk/src/resolveOutput.ts index e5cb3ad7a99b..d2e51588241f 100644 --- a/packages/sdk/src/resolveOutput.ts +++ b/packages/sdk/src/resolveOutput.ts @@ -7,10 +7,7 @@ async function resolveNodeModulesBase(cwd: string): Promise { if (await exists(path.resolve(process.cwd(), 'prisma/schema.prisma'))) { return process.cwd() } - if ( - path.relative(process.cwd(), cwd) === 'prisma' && - (await exists(path.resolve(process.cwd(), 'package.json'))) - ) { + if (path.relative(process.cwd(), cwd) === 'prisma' && (await exists(path.resolve(process.cwd(), 'package.json')))) { return process.cwd() } if (await exists(path.resolve(cwd, 'node_modules'))) { @@ -33,9 +30,7 @@ export type ResolveOutputOptions = { baseDir: string // normally `schemaDir`, the dir containing the schema.prisma file } -export async function resolveOutput( - options: ResolveOutputOptions, -): Promise { +export async function resolveOutput(options: ResolveOutputOptions): Promise { const defaultOutput = stripRelativePath(options.defaultOutput) if (defaultOutput.startsWith('node_modules')) { const nodeModulesBase = await resolveNodeModulesBase(options.baseDir) diff --git a/packages/sdk/src/sendPanic.ts b/packages/sdk/src/sendPanic.ts index a2b4c762994f..82a2e1fabf7f 100644 --- a/packages/sdk/src/sendPanic.ts +++ b/packages/sdk/src/sendPanic.ts @@ -19,11 +19,7 @@ const debug = Debug('prisma:sendPanic') // cleanup the temporary files even when an uncaught exception occurs tmp.setGracefulCleanup() -export async function sendPanic( - error: RustPanic, - cliVersion: string, - engineVersion: string, -): Promise { +export async function sendPanic(error: RustPanic, cliVersion: string, engineVersion: string): Promise { try { let schema: undefined | string let maskedSchema: undefined | string @@ -144,10 +140,7 @@ async function makeErrorZip(error: RustPanic): Promise { for (const filePath of filePaths) { let file = fs.readFileSync(path.resolve(schemaDir, filePath), 'utf-8') - if ( - filePath.endsWith('schema.prisma') || - filePath.endsWith(path.basename(error.schemaPath)) - ) { + if (filePath.endsWith('schema.prisma') || filePath.endsWith(path.basename(error.schemaPath))) { // Remove credentials from schema datasource url file = maskSchema(file) } @@ -191,9 +184,7 @@ export enum ErrorKind { RUST_PANIC = 'RUST_PANIC', } -export async function createErrorReport( - data: CreateErrorReportInput, -): Promise { +export async function createErrorReport(data: CreateErrorReportInput): Promise { const result = await request( `mutation ($data: CreateErrorReportInput!) { createErrorReport(data: $data) @@ -203,9 +194,7 @@ export async function createErrorReport( return result.createErrorReport } -export async function makeErrorReportCompleted( - signedUrl: string, -): Promise { +export async function makeErrorReportCompleted(signedUrl: string): Promise { const result = await request( `mutation ($signedUrl: String!) { markErrorReportCompleted(signedUrl: $signedUrl) diff --git a/packages/sdk/src/utils/extractPreviewFeatures.ts b/packages/sdk/src/utils/extractPreviewFeatures.ts index ef7bab0c8a53..8b85c2c08079 100644 --- a/packages/sdk/src/utils/extractPreviewFeatures.ts +++ b/packages/sdk/src/utils/extractPreviewFeatures.ts @@ -2,9 +2,5 @@ import type { ConfigMetaFormat } from '../engine-commands' import { parseEnvValue } from './parseEnvValue' export function extractPreviewFeatures(config: ConfigMetaFormat): string[] { - return ( - config.generators.find( - (g) => parseEnvValue(g.provider) === 'prisma-client-js', - )?.previewFeatures || [] - ) + return config.generators.find((g) => parseEnvValue(g.provider) === 'prisma-client-js')?.previewFeatures || [] } diff --git a/packages/sdk/src/utils/getEnvPaths.ts b/packages/sdk/src/utils/getEnvPaths.ts index 387f66bfa763..6e896566a9e0 100644 --- a/packages/sdk/src/utils/getEnvPaths.ts +++ b/packages/sdk/src/utils/getEnvPaths.ts @@ -22,15 +22,10 @@ export type EnvPaths = { * * @returns `{ rootEnvPath, schemaEnvPath }` */ -export function getEnvPaths( - schemaPath?: string | null, - opts: { cwd: string } = { cwd: process.cwd() }, -): EnvPaths { +export function getEnvPaths(schemaPath?: string | null, opts: { cwd: string } = { cwd: process.cwd() }): EnvPaths { const rootEnvPath = getProjectRootEnvPath({ cwd: opts.cwd }) ?? null const schemaEnvPathFromArgs = schemaPathToEnvPath(schemaPath) - const schemaEnvPathFromPkgJson = schemaPathToEnvPath( - readSchemaPathFromPkgJson(), - ) + const schemaEnvPathFromPkgJson = schemaPathToEnvPath(readSchemaPathFromPkgJson()) const schemaEnvPaths = [ schemaEnvPathFromArgs, // 1 - Check --schema directory for .env schemaEnvPathFromPkgJson, // 2 - Check package.json schema directory for .env @@ -49,9 +44,7 @@ function readSchemaPathFromPkgJson(): string | null { } } -function getProjectRootEnvPath( - opts: findUp.Options | undefined, -): string | null { +function getProjectRootEnvPath(opts: findUp.Options | undefined): string | null { const pkgJsonPath = findUp.sync((dir) => { const pkgPath = path.join(dir, 'package.json') if (findUp.sync.exists(pkgPath)) { diff --git a/packages/sdk/src/utils/mapKeys.ts b/packages/sdk/src/utils/mapKeys.ts index 005ff6914da0..3b5856977c16 100644 --- a/packages/sdk/src/utils/mapKeys.ts +++ b/packages/sdk/src/utils/mapKeys.ts @@ -1,7 +1,4 @@ -export function mapKeys( - obj: T, - mapper: (key: keyof T) => string, -): any { +export function mapKeys(obj: T, mapper: (key: keyof T) => string): any { return Object.entries(obj).reduce((acc, [key, value]) => { acc[mapper(key as keyof T)] = value return acc diff --git a/packages/sdk/src/utils/missingDatasource.ts b/packages/sdk/src/utils/missingDatasource.ts index 407f1829d3fe..38194d0b7719 100644 --- a/packages/sdk/src/utils/missingDatasource.ts +++ b/packages/sdk/src/utils/missingDatasource.ts @@ -2,9 +2,9 @@ import chalk from 'chalk' import { highlightDatamodel } from '../highlight/highlight' import { link } from '../link' -export const missingDatasource = `\nYou don't have any ${chalk.bold( - 'datasource', -)} defined in your ${chalk.bold('schema.prisma')}. +export const missingDatasource = `\nYou don't have any ${chalk.bold('datasource')} defined in your ${chalk.bold( + 'schema.prisma', +)}. You can define a datasource like this: ${chalk.bold( diff --git a/packages/sdk/src/utils/missingGeneratorMessage.ts b/packages/sdk/src/utils/missingGeneratorMessage.ts index c2ad5947e37c..73b28c863cc3 100644 --- a/packages/sdk/src/utils/missingGeneratorMessage.ts +++ b/packages/sdk/src/utils/missingGeneratorMessage.ts @@ -4,9 +4,7 @@ import { link } from '../link' export const missingGeneratorMessage = `\n${chalk.blue( 'info', -)} You don't have any generators defined in your ${chalk.bold( - 'schema.prisma', -)}, so nothing will be generated. +)} You don't have any generators defined in your ${chalk.bold('schema.prisma')}, so nothing will be generated. You can define them like this: ${chalk.bold( @@ -15,9 +13,9 @@ ${chalk.bold( }`), )}` -export const missingModelMessage = `\nYou don't have any ${chalk.bold( - 'models', -)} defined in your ${chalk.bold('schema.prisma')}, so nothing will be generated. +export const missingModelMessage = `\nYou don't have any ${chalk.bold('models')} defined in your ${chalk.bold( + 'schema.prisma', +)}, so nothing will be generated. You can define a model like this: ${chalk.bold( @@ -32,9 +30,9 @@ More information in our documentation: ${link('https://pris.ly/d/prisma-schema')} ` -export const missingModelMessageMongoDB = `\nYou don't have any ${chalk.bold( - 'models', -)} defined in your ${chalk.bold('schema.prisma')}, so nothing will be generated. +export const missingModelMessageMongoDB = `\nYou don't have any ${chalk.bold('models')} defined in your ${chalk.bold( + 'schema.prisma', +)}, so nothing will be generated. You can define a model like this: ${chalk.bold( diff --git a/packages/sdk/src/utils/now.ts b/packages/sdk/src/utils/now.ts index 707ed6aa631f..12b43158b620 100644 --- a/packages/sdk/src/utils/now.ts +++ b/packages/sdk/src/utils/now.ts @@ -2,11 +2,9 @@ const prefixZero = (value: number): string => ('0' + value).slice(-2) export function now(): string { const now = new Date() - return `${now.getFullYear()}${prefixZero(now.getMonth() + 1)}${prefixZero( - now.getDate(), - )}${prefixZero(now.getHours())}${prefixZero(now.getMinutes())}${prefixZero( - now.getSeconds(), - )}` + return `${now.getFullYear()}${prefixZero(now.getMonth() + 1)}${prefixZero(now.getDate())}${prefixZero( + now.getHours(), + )}${prefixZero(now.getMinutes())}${prefixZero(now.getSeconds())}` } export function timestampToDate(timestamp: string): Date | undefined { diff --git a/packages/sdk/src/utils/parseEnvValue.ts b/packages/sdk/src/utils/parseEnvValue.ts index 07ecfb71382d..526f9a4ee73f 100644 --- a/packages/sdk/src/utils/parseEnvValue.ts +++ b/packages/sdk/src/utils/parseEnvValue.ts @@ -34,9 +34,7 @@ export function parseEnvValue(object: EnvValue) { * - If there is an env var it will be resolve and returned. * - If there is an env var is present but can't be resolved an error will be thrown */ -export function parseBinaryTargetsEnvValue( - object: BinaryTargetsEnvValue, -): string[] | string { +export function parseBinaryTargetsEnvValue(object: BinaryTargetsEnvValue): string[] | string { if (object.fromEnvVar && object.fromEnvVar != 'null') { const value = process.env[object.fromEnvVar] if (!value) { diff --git a/packages/sdk/src/utils/printConfigWarnings.ts b/packages/sdk/src/utils/printConfigWarnings.ts index 614abe4f4176..27d78b5f4ac6 100644 --- a/packages/sdk/src/utils/printConfigWarnings.ts +++ b/packages/sdk/src/utils/printConfigWarnings.ts @@ -2,9 +2,7 @@ import chalk from 'chalk' export function printConfigWarnings(warnings: string[]) { if (warnings && warnings.length > 0) { - const message = warnings - .map((warning) => `${chalk.yellow('warn')} ${warning}`) - .join('\n') + const message = warnings.map((warning) => `${chalk.yellow('warn')} ${warning}`).join('\n') console.warn(message) } } diff --git a/packages/sdk/src/utils/trimBlocksFromSchema.ts b/packages/sdk/src/utils/trimBlocksFromSchema.ts index 620b7e3334c0..06b734d9a8fd 100644 --- a/packages/sdk/src/utils/trimBlocksFromSchema.ts +++ b/packages/sdk/src/utils/trimBlocksFromSchema.ts @@ -17,10 +17,7 @@ export function trimNewLine(str: string): string { return newStr } -export function trimBlocksFromSchema( - str: string, - blocks = ['model', 'enum', 'datasource', 'generator'], -): string { +export function trimBlocksFromSchema(str: string, blocks = ['model', 'enum', 'datasource', 'generator']): string { const lines = str.split('\n') if (lines.length <= 2) { return str diff --git a/packages/sdk/src/utils/tryLoadEnvs.ts b/packages/sdk/src/utils/tryLoadEnvs.ts index 7dd3cdc5b008..35af57edecb7 100644 --- a/packages/sdk/src/utils/tryLoadEnvs.ts +++ b/packages/sdk/src/utils/tryLoadEnvs.ts @@ -57,14 +57,9 @@ export function tryLoadEnvs( // Print the error if any (if internal dotenv readFileSync throws) if (schemaEnvInfo?.dotenvResult.error) { - return console.error( - chalk.redBright.bold('Schema Env Error: ') + - schemaEnvInfo.dotenvResult.error, - ) as undefined + return console.error(chalk.redBright.bold('Schema Env Error: ') + schemaEnvInfo.dotenvResult.error) as undefined } - const messages = [rootEnvInfo?.message, schemaEnvInfo?.message].filter( - Boolean, - ) + const messages = [rootEnvInfo?.message, schemaEnvInfo?.message].filter(Boolean) return { message: messages.join('\n'), @@ -94,37 +89,24 @@ function checkForConflicts( } if (conflicts.length > 0) { // const message = `You are trying to load env variables which are already present in your project root .env - const relativeRootEnvPath = path.relative( - process.cwd(), - rootEnvInfo!.path, - ) + const relativeRootEnvPath = path.relative(process.cwd(), rootEnvInfo!.path) const relativeEnvPath = path.relative(process.cwd(), envPath) if (type === 'error') { - const message = `There is a conflict between env var${ - conflicts.length > 1 ? 's' : '' - } in ${chalk.underline(relativeRootEnvPath)} and ${chalk.underline( - relativeEnvPath, - )} + const message = `There is a conflict between env var${conflicts.length > 1 ? 's' : ''} in ${chalk.underline( + relativeRootEnvPath, + )} and ${chalk.underline(relativeEnvPath)} Conflicting env vars: ${conflicts.map((conflict) => ` ${chalk.bold(conflict)}`).join('\n')} -We suggest to move the contents of ${chalk.underline( - relativeEnvPath, - )} to ${chalk.underline( +We suggest to move the contents of ${chalk.underline(relativeEnvPath)} to ${chalk.underline( relativeRootEnvPath, )} to consolidate your env vars.\n` throw new Error(message) } else if (type === 'warn') { - const message = `Conflict for env var${ - conflicts.length > 1 ? 's' : '' - } ${conflicts + const message = `Conflict for env var${conflicts.length > 1 ? 's' : ''} ${conflicts .map((c) => chalk.bold(c)) - .join(', ')} in ${chalk.underline( - relativeRootEnvPath, - )} and ${chalk.underline(relativeEnvPath)} -Env vars from ${chalk.underline( - relativeEnvPath, - )} overwrite the ones from ${chalk.underline(relativeRootEnvPath)} + .join(', ')} in ${chalk.underline(relativeRootEnvPath)} and ${chalk.underline(relativeEnvPath)} +Env vars from ${chalk.underline(relativeEnvPath)} overwrite the ones from ${chalk.underline(relativeRootEnvPath)} ` console.warn(`${chalk.yellow('warn(prisma)')} ${message}`) } @@ -132,9 +114,7 @@ Env vars from ${chalk.underline( } } -export function loadEnv( - envPath: string | null | undefined, -): DotenvLoadEnvResult | null { +export function loadEnv(envPath: string | null | undefined): DotenvLoadEnvResult | null { if (exists(envPath)) { debug(`Environment variables loaded from ${envPath}`) @@ -155,12 +135,7 @@ export function loadEnv( debug: enableDebug, }), ), - message: chalk.dim( - `Environment variables loaded from ${path.relative( - process.cwd(), - envPath, - )}`, - ), + message: chalk.dim(`Environment variables loaded from ${path.relative(process.cwd(), envPath)}`), path: envPath, } @@ -169,10 +144,7 @@ export function loadEnv( } return null } -export function pathsEqual( - path1: string | null | undefined, - path2: string | null | undefined, -) { +export function pathsEqual(path1: string | null | undefined, path2: string | null | undefined) { return path1 && path2 && path.resolve(path1) === path.resolve(path2) }