prisma: Node hangs when `console.log(new PrismaClient())`

Bug description

Linux - node process hangs (stuck on prisma:client:libraryEngine internalSetup +0ms) Windows - javascript out of memory error. Any schema. Affected versions of @prisma/client > 4.7.0

How to reproduce

  1. npx prisma init
  2. npx prisma generate (npx prisma db push)
  3. Create index.mjs with:
    import { PrismaClient } from '@prisma/client'
    console.log(new PrismaClient())
    
  4. export DEBUG="*" && node index.mjs -> See error

Expected behavior

No response

Prisma information

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model Session {
  id    Int    @id @default(autoincrement())
  key   String @unique
  value String

  @@map("sessions")
}

Environment & setup

  • OS: Windows 11, Ubuntu 22.04.2
  • Database: MySQL
  • Node.js version: 18.5.0, 19.7.0

Prisma Version

prisma                  : 4.11.0
@prisma/client          : 4.11.0
Current platform        : debian-openssl-3.0.x
Query Engine (Node-API) : libquery-engine 8fde8fef4033376662cad983758335009d522acb (at node_modules/@prisma/engines/libquery_engine-debian-openssl-3.0.x.so.node)
Migration Engine        : migration-engine-cli 8fde8fef4033376662cad983758335009d522acb (at node_modules/@prisma/engines/migration-engine-debian-openssl-3.0.x)
Format Wasm             : @prisma/prisma-fmt-wasm 4.11.0-57.8fde8fef4033376662cad983758335009d522acb
Default Engines Hash    : 8fde8fef4033376662cad983758335009d522acb
Studio                  : 0.483.0

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 13
  • Comments: 37 (13 by maintainers)

Commits related to this issue

Most upvoted comments

I’m running into an issue that may be a different manifestation of this same issue. In Visual Studio Code, whenever I attempt to debug into a class that extends PrismaClient, the node process hangs. Also if I attempt to inspect the instance of this class before stepping into it, the node process hangs. I’m not able to debug any of my classes that extend PrismaClient because of this. I wonder if the debugging issue has something to do with the debugger inspecting the PrismaClient instance for a watch locals or something and this inspecting leads to the same error as logging the PrismaClient instance.

@janpio I’ve just tested and can confirm that the dev version no-longer freezes REPL instance when the command would output anything with prisma instance on it.

With 5.10.2 it does freeze, so the fix must’ve addressed it correcly.

Can’t wait for the release, thanks SevInf and team for the fix 🙌

@llimllib you can work around the issue with this:

const repl = require("node:repl");

const r = repl.start("> ");
r.context.prisma = new (require("@prisma/client").PrismaClient)();
r.context.prisma[Symbol.for('nodejs.util.inspect.custom')] = 'PrismaClient';

as suggested here: https://github.com/prisma/prisma/issues/19648#issuecomment-1680911900

It works with the dev version. Thank you !

Hey everyone that commented in this issue before, could you please try to temporarily install prisma@dev and @prisma/client@dev in your project and see if this fixes the problem? https://github.com/prisma/prisma/pull/23228 should have fixed this and will be included in the next release, but of course a confirmation of it now working as intended would be nice.

This issue prevents me from using prisma in the node REPL; I don’t literally want to log the output of the client, but I do want to use it in a repl.

Here’s a node REPL script that reproduces the issue:

const repl = require("node:repl");

const r = repl.start("> ");
r.context.prisma = new (require("@prisma/client").PrismaClient)();

run that script, type pri, node tries to autocomplete prisma and the process immediately hangs; it’s not even responsive to ctrl+c interrupt at that point.

It’s art 🤣

I can actually log new PrismaClient() fine:

const { PrismaClient } = require('@prisma/client')

async function main() {
    console.log(new PrismaClient())
}

main()
  .catch(async (e) => {
    console.error(e)
    await prisma.$disconnect()
    process.exit(1)
  })

When I put the output of this into a file, it is 525 MB (551.039.534 bytes) big though - so I would not be surprised if that would crash in some environments.

The output looks recursive to me in 2 places:

{
  _middlewares: MiddlewareHandler { _middlewares: [] },
  _getDmmf: [Function (anonymous)],
  _getProtocolEncoder: [Function (anonymous)],
  '$extends': [Function: $extends],
  _extensions: MergedExtensionsList { head: undefined },
  _previewFeatures: [],
  _rejectOnNotFound: undefined,
  _clientVersion: '4.13.0',
  _activeProvider: 'postgresql',
  _dataProxy: false,
  _tracingConfig: { enabled: [Getter], middleware: [Getter] },
  _clientEngineType: 'library',
  _errorFormat: 'colorless',
  _baseDmmf: {
    datamodel: { enums: [], models: [Array], types: [] },
    datamodelEnumMap: {},
    modelMap: { User: [Object] },
    typeMap: {},
    typeAndModelMap: { User: [Object] },
    mappings: { modelOperations: [Array], otherOperations: [Object] },
    mappingsMap: { User: [Object] }
  },
  _engineConfig: {
    cwd: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\prisma',
    dirname: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\node_modules\\.prisma\\client',
    enableDebugLogs: false,
    allowTriggerPanic: undefined,
    datamodelPath: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\node_modules\\.prisma\\client\\schema.prisma',
    prismaPath: undefined,
    engineEndpoint: undefined,
    datasources: [],
    generator: {
      name: 'client',
      provider: [Object],
      output: [Object],
      config: [Object],
      binaryTargets: [],
      previewFeatures: []
    },
    showColors: false,
    logLevel: undefined,
    logQueries: undefined,
    env: {
      DATABASE_URL: 'postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public'
    },
    flags: [],
    clientVersion: '4.13.0',
    previewFeatures: [],
    activeProvider: 'postgresql',
    inlineSchema: undefined,
    inlineDatasources: undefined,
    inlineSchemaHash: undefined,
    tracingConfig: { enabled: [Getter], middleware: [Getter] },
    logEmitter: EventEmitter {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    },
    engineProtocol: 'graphql'
  },
  _engine: LibraryEngine {
    datamodel: '// This is your Prisma schema file,\n' +
      '// learn more about it in the docs: https://pris.ly/d/prisma-schema\n' +
      '\n' +
      'generator client {\n' +
      '  provider = "prisma-client-js"\n' +
      '}\n' +
      '\n' +
      'datasource db {\n' +
      '  provider = "postgresql"\n' +
      '  url      = env("DATABASE_URL")\n' +
      '}\n' +
      '\n' +
      'model User {\n' +
      '  id    Int     @id @default(autoincrement())\n' +
      '  email String  @unique\n' +
      '  name  String?\n' +
      '}\n',
    config: {
      cwd: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\prisma',
      dirname: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\node_modules\\.prisma\\client',
      enableDebugLogs: false,
      allowTriggerPanic: undefined,
      datamodelPath: 'C:\\Users\\Jan\\Documents\\throwaway\\18292\\node_modules\\.prisma\\client\\schema.prisma',
      prismaPath: undefined,
      engineEndpoint: undefined,
      datasources: [],
      generator: [Object],
      showColors: false,
      logLevel: undefined,
      logQueries: undefined,
      env: [Object],
      flags: [],
      clientVersion: '4.13.0',
      previewFeatures: [],
      activeProvider: 'postgresql',
      inlineSchema: undefined,
      inlineDatasources: undefined,
      inlineSchemaHash: undefined,
      tracingConfig: [Object],
      logEmitter: [EventEmitter],
      engineProtocol: 'graphql'
    },
    libraryStarted: false,
    logQueries: false,
    logLevel: 'error',
    libraryLoader: DefaultLibraryLoader {
      libQueryEnginePath: null,
      platform: null,
      config: [Object]
    },
    logEmitter: EventEmitter {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    },
    engineProtocol: 'graphql',
    datasourceOverrides: [Object: null prototype] {},
    libraryInstantiationPromise: Promise { <pending> }
  },
  _fetcher: RequestHandler {
    logEmitter: EventEmitter {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    },
    client: {
       ... RECURSION 1 HERE ...
    },
    dataloader: DataLoader { options: [Object], tickActive: false, batches: {} }
  },
  _metrics: MetricsClient {
    _engine: LibraryEngine {
      datamodel: '// This is your Prisma schema file,\n' +
        '// learn more about it in the docs: https://pris.ly/d/prisma-schema\n' +
        '\n' +
        'generator client {\n' +
        '  provider = "prisma-client-js"\n' +
        '}\n' +
        '\n' +
        'datasource db {\n' +
        '  provider = "postgresql"\n' +
        '  url      = env("DATABASE_URL")\n' +
        '}\n' +
        '\n' +
        'model User {\n' +
        '  id    Int     @id @default(autoincrement())\n' +
        '  email String  @unique\n' +
        '  name  String?\n' +
        '}\n',
      config: [Object],
      libraryStarted: false,
      logQueries: false,
      logLevel: 'error',
      libraryLoader: [DefaultLibraryLoader],
      logEmitter: [EventEmitter],
      engineProtocol: 'graphql',
      datasourceOverrides: [Object: null prototype] {},
      libraryInstantiationPromise: [Promise]
    }
  },
  user: {
    findUnique: [Function (anonymous)],
    findUniqueOrThrow: [Function (anonymous)],
    findFirst: [Function (anonymous)],
    findFirstOrThrow: [Function (anonymous)],
    findMany: [Function (anonymous)],
    create: [Function (anonymous)],
    createMany: [Function (anonymous)],
    delete: [Function (anonymous)],
    update: [Function (anonymous)],
    deleteMany: [Function (anonymous)],
    updateMany: [Function (anonymous)],
    upsert: [Function (anonymous)],
    aggregate: [Function (anonymous)],
    groupBy: [Function (anonymous)],
    count: [Function (anonymous)],
    name: 'User'
  },
  [Symbol()]: {
      ... RECURSION 2 HERE ...
   }
}

Both cases are roughly 100.000 lines long in my file.

Not optimal.

Thanks for this fix.

I want to add another case where this was problematic. We have a dependency injection container where we store our Prisma client for use in parts of the app that require it. Dependencies are lazily loaded, but we connect the Prisma client on app launch, so it’s always loaded.

There have been moments where we need to inspect other parts of the container, so we’ll console.log the container. This is probably a bad idea, but we would log out the full container to inspect it. This would unfortunately hang the entire process during development and we were never able to figure out why this was happening. So now we know!

So thank you for fixing this bug! Super helpful!

Unfortunately not, we never maintain older versions by backporting changes or fixes.

You would need to do that yourself in a fork and publish it under your own package name. Probably you can achieve something similar using https://www.npmjs.com/package/patch-package

There’s got to be a way around this.

There is, see https://github.com/prisma/prisma/issues/18292#issuecomment-1749123704.

Hello, there is an expression in Spanish that says: “Donde dije digo y donde digo Diego”, basically a way of saying that I was wrong. Yesterday after some more time testing I discovered that the problem only occurs when creating a console.log(“prismaclient instance”). So my apologies, and I encourage you to keep working as you have been doing with this great tool. Regards

This is the behaviour that I see on 4.7.0; warning if you’re sensitive to flashing imagery. Not sure that this is necessarily working as intended, but it doesn’t hang at least

https://github.com/prisma/prisma/assets/29753584/bb02a165-bb98-42b9-a54d-fd39545aeecd

Why do you want to console.log(new PrismaClient())?

fr

Why do you want to console.log(new PrismaClient())?