Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server & SQLite

Overview

Prisma

Prisma



Quickstart   •   Website   •   Docs   •   Examples   •   Blog   •   Slack   •   Twitter   •   Prisma 1

What is Prisma?

Prisma is a next-generation ORM that consists of these tools:

  • Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
  • Prisma Migrate: Declarative data modeling & migration system
  • Prisma Studio: GUI to view and edit data in your database

Prisma Client can be used in any Node.js or TypeScript backend application (including serverless applications and microservices). This can be a REST API, a GraphQL API a gRPC API or anything else that needs a database.

Are you looking for Prisma 1? The Prisma 1 repository has been renamed to prisma/prisma1.

Getting started

The fastest way to get started with Prisma is by following the Quickstart (5 min).

The Quickstart is based on a preconfigured SQLite database. You can also get started with your own database (PostgreSQL and MySQL) by following one of these guides:

How does Prisma work

This section provides a high-level overview of how Prisma works and its most important technical components. For a more thorough introduction, visit the Prisma documentation.

The Prisma schema

Every project that uses a tool from the Prisma toolkit starts with a Prisma schema file. The Prisma schema allows developers to define their application models in an intuitive data modeling language. It also contains the connection to a database and defines a generator:

// Data source
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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

// Data model
model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields:  [authorId], references: [id])
  authorId  Int?
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

In this schema, you configure three things:

  • Data source: Specifies your database connection (via an environment variable)
  • Generator: Indicates that you want to generate Prisma Client
  • Data model: Defines your application models

The Prisma data model

On this page, the focus is on the data model. You can learn more about Data sources and Generators on the respective docs pages.

Functions of Prisma models

The data model is a collection of models. A model has two major functions:

  • Represent a table in the underlying database
  • Provide the foundation for the queries in the Prisma Client API

Getting a data model

There are two major workflows for "getting" a data model into your Prisma schema:

  • Generate the data model from introspecting a database
  • Manually writing the data model and mapping it to the database with Prisma Migrate

Once the data model is defined, you can generate Prisma Client which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields).


Accessing your database with Prisma Client

Generating Prisma Client

The first step when using Prisma Client is installing its npm package:

npm install @prisma/client

Note that the installation of this package invokes the prisma generate command which reads your Prisma schema and generates the Prisma Client code. The code will be located in node_modules/.prisma/client, which is exported by node_modules/@prisma/client/index.d.ts.

After you change your data model, you'll need to manually re-generate Prisma Client to ensure the code inside node_modules/.prisma/client get updated:

prisma generate

Refer to the documentation for more information about "generating the Prisma client".

Using Prisma Client to send queries to your database

Once Prisma Client was generated, you can import in your code and send queries to your database. This is what the setup code looks like.

Import and instantiate Prisma Client

You can import and instantiate Prisma Client as follows:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

or

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

const prisma = new PrismaClient()

Now you can start sending queries via the generated Prisma Client API, here are few sample queries. Note that all Prisma Client queries return plain old JavaScript objects.

Learn more about the available operations in the Prisma Client docs or watch this demo video (2 min).

Retrieve all User records from the database
// Run inside `async` function
const allUsers = await prisma.user.findMany()
Include the posts relation on each returned User object
// Run inside `async` function
const allUsers = await prisma.user.findMany({
  include: { posts: true },
})
Filter all Post records that contain "prisma"
// Run inside `async` function
const filteredPosts = await prisma.post.findMany({
  where: {
    OR: [
      { title: { contains: 'prisma' } },
      { content: { contains: 'prisma' } },
    ],
  },
})
Create a new User and a new Post record in the same query
// Run inside `async` function
const user = await prisma.user.create({
  data: {
    name: 'Alice',
    email: '[email protected]',
    posts: {
      create: { title: 'Join us for Prisma Day 2021' },
    },
  },
})
Update an existing Post record
// Run inside `async` function
const post = await prisma.post.update({
  where: { id: 42 },
  data: { published: true },
})

Usage with TypeScript

Note that when using TypeScript, the result of this query will be statically typed so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the Advanced usage of generated types page in the docs.

Community

Prisma has a large and supportive community of enthusiastic application developers. You can join us on Slack and here on GitHub.

Security

If you have a security issue to report, please contact us at [email protected].

Support

Ask a question about Prisma

You can ask questions and initiate discussions about Prisma-related topics in the prisma repository on GitHub.

👉 Ask a question

Create a bug report for Prisma

If you see an error message or run into an issue, please make sure to create a bug report! You can find best practices for creating bug reports (like including additional debugging output) in the docs.

👉 Create bug report

Submit a feature request

If Prisma currently doesn't have a certain feature, be sure to check out the roadmap to see if this is already planned for the future.

If the feature on the roadmap is linked to a GitHub issue, please make sure to leave a +1 on the issue and ideally a comment with your thoughts about the feature!

👉 Submit feature request

Contributing

Refer to our contribution guidelines and Code of Conduct for contributors.

Build Status

  • Prisma Tests Status:
    Build status
  • E2E Tests Status:
    Actions Status
Comments
  • API for interactive transactions with dependencies between write-operations

    API for interactive transactions with dependencies between write-operations

    There already is a GitHub issue asking for a way to submit multiple mutations within the same HTTP request where all mutations are executed as one transaction.

    However, this feature does not allow for creating a transaction where the mutations depend on each other. Here is an example where the second operation depends on the first:

    prisma.transaction(async tx => {
      const user = await tx.createUser({
        name,
      })
      // compute some stuff
      await tx.updateOrder(user.id)
      await tx.commit()
    })
    

    This is currently not possible with the Prisma API as it would require having a long-running connection where the results of the operations are sent back and forth between Prisma and the database.

    It should be considered whether it is helpful to add such an API to Prisma, or whether abstractions like nested mutations and the requested transactional execution of multiple independent transactions are the better approach for Prisma.

    kind/feature topic: prisma-client topic: transaction team/client 
    opened by nikolasburk 122
  • MongoDB support for Prisma 2+

    MongoDB support for Prisma 2+

    Our team is considering working with Prisma, but as Prisma 1 seems to go out of scope and prisma 2 not mongo ready yet would love to know when is support expected to be released? a week? a month ? 2021 ?

    kind/feature topic: connector team/schema team/client topic: mongodb 
    opened by gotenxds 87
  • Support setting a timeout for SQLite

    Support setting a timeout for SQLite

    Problem

    SQLite queries fail immediately if the DB is locked.

    I blindly tried passing arguments similarly to how the docs show for PostgreSQL, needless to say, it didn't work.

    datasource db {
      provider = "sqlite"
      url      = "file:../db.sqlite?timeout=5000"
    }
    
    bug/2-confirmed kind/bug topic: sqlite tech/engines team/client 
    opened by internalfx 73
  • Prisma CLI installation hangs indefinitely inside of docker (Kernel 5.10)

    Prisma CLI installation hangs indefinitely inside of docker (Kernel 5.10)

    Bug description

    @prisma/cli installation hangs indefinitely inside of docker

    How to reproduce

    REPRO: https://github.com/svelters/prisma-poc

    Expected behavior

    It should install without container discrimination

    Prisma information

    @prisma/cli version: "2.15.0"

    Environment & setup

    • OS: Linux - Docker (alpine, debian etc...)
    • Database: doesn't matter
    • Node.js version: 15.6.0 but it seems to fail on any version we tried
    • Prisma version: doesn't matter as it fails because of the cli
    bug/2-confirmed kind/bug team/client topic: docker topic: kernel 5.10 
    opened by francois-pasquier 68
  • Using Prisma with a PlanetScale database

    Using Prisma with a PlanetScale database

    UPDATE

    As of 27.10.2022, the details in this issue are outdated.

    Refer to https://www.prisma.io/docs/guides/database/using-prisma-with-planetscale for the latest instructions on using Prisma with PlanetScale.

    Outdated Issue content

    PlanetScale is a new and interesting cloud database based on MySQL. It's exciting!

    PlanetScale is a bit different than other MySQL database providers though:

    1. No support for foreign keys. This is challenging for Prisma users, as Prisma by default uses foreign keys to express relations.
    2. No creation of additional databases using CREATE DATABASE but need to use their tooling (web UI or CLI). This can be challenging, as some development commands of Prisma like prisma migrate dev create temporary databases in the background.
    3. No schema changes on your production database (but make them on branches, then merge the schema changes back). This is challenging for Prisma users, as usually they run Migrations against their database directly via prisma migrate deploy or prisma db push.

    Here is how you can use Prisma and PlanetScale together anyway:

    1. No foreign keys / No Prisma Migrate (migrate dev and db push)

      • Problem: PlanetScale does not allow foreign keys in the database schema (ERROR 70100 (1317): foreign key constraints are not allowed, see https://code.openark.org/blog/mysql/the-problem-with-mysql-foreign-key-constraints-in-online-schema-changes), which Prisma relies on for relations.
      • Starting with 2.27.0 Prisma catches the error and outputs a helpful error message (that currently redirects here)
      • Workaround starting with 3.1.1: Use the preview feature referentialIntegrity and the datasource propertly referentialIntegrity = "prisma" to enable a mode that automatically leaves out foreign keys in migrations:
        generator client {
          provider        = "prisma-client-js"
          previewFeatures = ["referentialIntegrity"]
        }
        
        datasource db {
          provider             = "mysql"
          url                  = env("DATABASE_URL")
          shadowDatabaseUrl    = env("SHADOW_DATABASE_URL")
          referentialIntegrity = "prisma"
        }
        
        ...
        

        You can now properly use prisma migrate dev and prisma db push ✅ (Between 2.24.0 and 3.1.1 the setting was called planetScaleMode = true and hidden behind the preview feature flag planetScaleMode)

    2. If you are using migrate dev to migrate: No CREATE DATABASE / No automatic shadow database creation

      • Problem: PlanetScale does not allow creating new databases with CREATE DATABASE, which Prisma Migrate prefers to use for the shadow database of Prisma Migrate.
      • Solution: Create a branch shadow or similar and open put its connection string as shadowDatabase of your datasource in schema.prisma
        datasource db {
          provider             = "mysql"
          url                  = env("DATABASE_URL")
          shadowDatabaseUrl    = env("SHADOW_DATABASE_URL")
          referentialIntegrity = "prisma"
        }
        
      • Potential improvement: Catch error thrown if you try anyway and output better error message with link to documentation.
    3. If you are using migrate dev to migrate: Prisma migration table is not copied to main by default

      • PlanetScale now has a setting "Automatic schema migrations" that enables this behavior: image As you can see Prisma is one of the default options, and enabling this option and choosing Prisma makes sure that the content of the migration table _prisma_migrations is copied from the branch to main with the deploy request. 🥳
    4. No schema changes on production branches

      • Problem: PlanetScale does not allow schema changes on the production branch of the database (ERROR HY000 (1105): direct DDL is disabled), which Prisma Migrate tries to do if you tell it to.
      • Starting with 2.27.0 Prisma catches the error and outputs a helpful error message (that currently redirects here)
      • Solution: Only execute Prisma Migrate on non production branches, then use a PlanetScale "deploy request" to merge the schema changes to your main

    We are very excited for you to try PlanetScale with Prisma. If you hit any bumps, let us know either here or in new issues or discussions in our repository. Thanks!

    topic: database-provider/planetscale topic: foreign keys topic: referentialIntegrity/relationMode 
    opened by janpio 66
  • Generate TEXT fields from String

    Generate TEXT fields from String

    Hi,

    I’m using prisma2 lift to generate my database, but it’s generating all my String fields as VARCHAR with size 191. Unfortunately, when I go to populate these fields, some of my data has more than 191 characters. Is there a way I can get prisma2 lift to generate TEXT fields or specify my desired length of VARCHAR?

    Thanks!

    kind/feature topic: native database types topic: client types team/schema 
    opened by nlarusstone 65
  • Provide precompiled binaries for ARM

    Provide precompiled binaries for ARM

    Currently, we do not have any precompiled binaries for the ARM platform.

    Now that Windows is supported, we should look into compiling for ARM. That would enable users to Prisma 2 on Raspberry Pi and other all sorts of ARM-based devices.

    This will also include adding ARM to the binaries spec: https://github.com/prisma/specs/tree/master/binaries#binary-files

    Ref: https://github.com/prisma/prisma2/issues/132

    kind/feature topic: binary tech/engines team/client topic: arm 
    opened by pantharshit00 61
  • "FATAL: sorry, too many clients already" postgres error in develop mode on

    Bug description

    I use prisma inside an api-route of https://nextjs.org/ (this is by the way an awesome setup) for a graphql-api. After some time you will get this error:

    
    Error in connector: Error querying the database: db error: FATAL: sorry, too many clients already
        at PrismaClientFetcher.request
    

    I guess the hot-reloading or refreshing of nextjs might mess with the connection-pool of prisma. I verified that the prisma-client that is used in the route is a singleton:

    // this is imported in my api route
    import { PrismaClient } from "@prisma/client";
    
    const prisma = new PrismaClient();
    
    export default prisma;
    

    How to reproduce

    Steps to reproduce the behavior:

    1. create a file pages/api/graphql.ts inside that, use prisma client
    2. it probably needs some code changes that result in a rebuilding of this file /api/graphql.ts or its imports
    3. at some point you should get the error

    Expected behavior

    should not throw this error i guess?

    Prisma information

    Environment & setup

    • OS: macOS
    • Database: [PostgreSQL
    • Prisma version: [email protected], binary version: 377df4fe30aa992f13f1ba152cf83d5770bdbc85
    • Node.js version: v12.13.1

    EDIT: Solution

    as many still comment on this thead, I though it would be good to pin the solution here.

    This issue happens because many platforms as nextjs (and probably nestjs as well) do hot reload of parts of your code. Usually you initialize the PrismaClient once in your application (as a singleton). But hot reload results in multiple initializations of this PrismaClient

    so the solution is to kindof "cache" the client in a global variable. See this comment: https://github.com/prisma/prisma/issues/1983#issuecomment-620621213

    bug/0-unknown kind/bug topic: connections 
    opened by macrozone 60
  • Ballooning of Prepared_stmt_count on MYSQL

    Ballooning of Prepared_stmt_count on MYSQL

    Bug description

    Hey guys, I hope you all are doing well!

    I'm running prisma @ 2.14 on MySQL, and after updating to and trying multiple versions (2.18, 2.20.1, 2.21.1), I'm running into issues where my Prepared_stmt_count global MySQL variable is increased by a huge factor compared to 2.14, which leads to me hitting the MAX_PREPARED_STATEMENTS limit. It seems like there is a difference in behavior of these prepared statements from 2.14 and onwards.

    Just to reiterate, this is not a problem on 2.14, and was I wondering if there was anything I could do to get the old behavior back on a newer version.

    Thank you!

    How to reproduce

    I'm running this on a production kube deployment, so I'm unsure what specific queries may be triggering this, but I do know that 2.14 and previous never had this behavior

    1. Be on similar env ?
    2. Use normally (create/update/delete) (many)

    Expected behavior

    Expect the Prepared_stmt_count to stay low, this is the current behavior on 2.14.

    image

    Actual behavior

    Prepared statement count balloons, and stays that way for a long enough time to where my set MAX_PREPARED_STMT_COUNT gets triggered and hangs the db. Note that the actual value in prod gets to 64000+.

    Screen Shot 2021-04-22 at 11 39 35 AM

    Prisma information

    Environment & setup

    • OS: Mac / Ubuntu
    • Database: MySQL 8.0.21
    • Node.js version: 12.16.1
    • Prisma version: Tested on 2.17, 2.18, 2.20.x, 2.21.x
    prisma               : 2.17.0
    @prisma/client       : 2.17.0
    Current platform     : darwin
    Query Engine         : query-engine 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/query-engine-darwin)
    Migration Engine     : migration-engine-cli 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/migration-engine-darwin)
    Introspection Engine : introspection-core 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/introspection-engine-darwin)
    Format Binary        : prisma-fmt 3c463ebd78b1d21d8fdacdd27899e280cf686223 (at node_modules/@prisma/engines/prisma-fmt-darwin)
    Studio               : 0.353.0
    
    bug/2-confirmed kind/bug topic: performance topic: mysql team/client 
    opened by rasberrylasagna 59
  • Preview feature feedback: Prisma Migrate

    Preview feature feedback: Prisma Migrate

    Please share your feedback about the new Preview version of Prisma Migrate that was released in v2.13.0 in this issue.

    • If you encounter a bug, please open a bug report in this repo.
    • If the feature is working well for you, please share this in a comment below or leave a 👍 on this issue.

    If you have any questions, don't hesitate to ask them in the #prisma-migrate channel in the Prisma Slack.

    kind/feedback topic: migrate topic: previewFeatures team/schema 
    opened by 2color 56
  • no such file or directory, open '/path/schema.prisma' since 3.1.1

    no such file or directory, open '/path/schema.prisma' since 3.1.1

    Bug description

    When I call new PrismaClient(), I get the error

    (node:12802) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '/mnt/d/workspace/path/packages/api/src/schema.prisma'
    

    That just happen on 3.1.1

    How to reproduce

    1. Upgrade prisma to 3.1.1
    2. Execute prisma db push command
    3. Call new PrismaClient()

    Expected behavior

    No response

    Prisma information

    Environment & setup

    • OS: Windows(wsl)
    • Database: SQLite
    • Node.js version: v14.17.4

    Prisma Version

    prisma                  : 3.1.1
    @prisma/client          : 3.1.1
    Current platform        : debian-openssl-1.1.x
    Query Engine (Node-API) : libquery-engine c22652b7e418506fab23052d569b85d3aec4883f (at ../../.yarn/unplugged/@prisma-engines-npm-3.1.0-24.c22652b7e418506fab23052d569b85d3aec4883f-4e2ba773cc/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)
    Migration Engine        : migration-engine-cli c22652b7e418506fab23052d569b85d3aec4883f (at ../../.yarn/unplugged/@prisma-engines-npm-3.1.0-24.c22652b7e418506fab23052d569b85d3aec4883f-4e2ba773cc/node_modules/@prisma/engines/migration-engine-debian-openssl-1.1.x)
    Introspection Engine    : introspection-core c22652b7e418506fab23052d569b85d3aec4883f (at ../../.yarn/unplugged/@prisma-engines-npm-3.1.0-24.c22652b7e418506fab23052d569b85d3aec4883f-4e2ba773cc/node_modules/@prisma/engines/introspection-engine-debian-openssl-1.1.x)
    Format Binary           : prisma-fmt c22652b7e418506fab23052d569b85d3aec4883f (at ../../.yarn/unplugged/@prisma-engines-npm-3.1.0-24.c22652b7e418506fab23052d569b85d3aec4883f-4e2ba773cc/node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x)
    Default Engines Hash    : c22652b7e418506fab23052d569b85d3aec4883f
    Studio                  : 0.423.0
    
    bug/2-confirmed kind/regression tech/typescript team/client topic: yarn berry(v2) 
    opened by s97712 52
  •  previewFeatures = [

    previewFeatures = ["multiSchema"] Error

    Hi Prisma Team! The following command just crashed.

    Command

    db pull

    Versions

    | Name | Version | |-------------|--------------------| | Platform | windows | | Node | v16.15.1 | | Prisma CLI | 4.8.1 | | Engine | d6e67a83f971b175a593ccc12e15c4a757f93ffe|

    Error

    Error: [libs\sql-schema-describer\src\mssql.rs:223:96] called `Option::unwrap()` on a `None` value
    
    opened by amarparekh26 1
  • multiSchema issue

    multiSchema issue

    Hi Prisma Team! The following command just crashed.

    Command

    db pull

    Versions

    | Name | Version | |-------------|--------------------| | Platform | windows | | Node | v16.15.1 | | Prisma CLI | 4.8.1 | | Engine | d6e67a83f971b175a593ccc12e15c4a757f93ffe|

    Error

    Error: [libs\sql-schema-describer\src\mssql.rs:223:96] called `Option::unwrap()` on a `None` value
    
    opened by amarparekh26 0
  • Unable to use Prisma in China

    Unable to use Prisma in China

    Bug description

    Stuck forever when I execute Prisma command

    How to reproduce

    • 1 run command:
    yarn
    

    stuck forever:

    [3/4] Linking dependencies...
    [4/4] Building fresh packages...
    [1/4] ⡀ @prisma/engines
    [-/4] ⢀ waiting...
    [-/4] ⢀ waiting...
    [-/4] ⢀ waiting...
    
    • 2 run command:
    npx prisma version 
    

    stuck forever:

    Downloading Prisma engines for Node-API for windows [          ] 0%
    

    -3 try to use VPN

    $ENV:HTTP_PROXY="http://localhost:10809"
    $ENV:HTTPS_PROXY="http://localhost:10809"
    

    run:

    npx prisma version 
    

    got error:

    Downloading Prisma engines for Node-API for windows [                    ] 0%Error: request to https://binaries.prisma.sh/all_commits/0362da9eebca54d94c8ef5edd3b2e90af99ba452/windows/query_engine.dll.node.gz.sha256 failed, reason: connect ECONNREFUSED ::1:10809
    

    -4 test curl

    curl https://binaries.prisma.sh/all_commits/d6e67a83f971b175a593ccc12e15c4a757f93ffe/windows/migration-engine.exe.gz.sha256
    

    it can be accessed normally

    dc7dec961e57b49fa2f8c35b87149063083ebec60e31abdf75232d265d424739  migration-engine.exe.gz
    

    Expected behavior

    When I set the proxy in the shell should be working. Many services cannot access directly on GitHub from China but after I set the proxy they work.

    Environment & setup

    • OS: Win10
    • Database: MongoDB
    • Node.js version: v18.12.1

    Prisma Version

        "prisma": "^4.8.0",
    
    
    kind/bug 
    opened by DaZiYuan 0
  • vercel/pkg into binary failed and throw

    vercel/pkg into binary failed and throw "prebuild-install WARN install No prebuilt binaries found"

    Bug description

    When I compile with pkg I have some problems, I don't know if it's a problem with my code, or with vercel/pkg, or with prisma.

    Errors are prebuild-install WARN install No prebuilt binaries found and Unable to load Node-API Library from /snapshot/tmp/node_modules/.prisma/client/libquery_engine-debian-openssl-3.0.x.so.node, Library may be corrupt: UNEXPECTED-15.

    Here's the package.json:

    {
      "name": "tmp",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "nodemon ."
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@prisma/client": "^4.8.1",
        "prisma": "^4.8.1"
      }
    }
    

    How to reproduce

    1. Run npx prisma generate.
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    
    ✔ Generated Prisma Client (4.8.1 | library) to ./node_modules/@prisma/client in 147ms
    You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
    
    import { PrismaClient } from '@prisma/client'
    const prisma = new PrismaClient()
    
    1. Compile .ts files with tsc.
    2. Run pkg -t node16-linux-x64 index.js -d and output a binary named index.
    /usr/local/lib/node_modules/pkg/node_modules/prebuild-install/util.js:13
        major: opts.pkg.version.split('.')[0],
                                ^
    
    TypeError: Cannot read properties of undefined (reading 'split')
        at Object.getDownloadUrl (/usr/local/lib/node_modules/pkg/node_modules/prebuild-install/util.js:13:29)
        at Object.<anonymous> (/usr/local/lib/node_modules/pkg/node_modules/prebuild-install/bin.js:77:22)
        at Module._compile (node:internal/modules/cjs/loader:1126:14)
        at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
        at Module.load (node:internal/modules/cjs/loader:1004:32)
        at Function.Module._load (node:internal/modules/cjs/loader:839:12)
        at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
        at node:internal/main/run_main_module:17:47
    
    1. Then push the version field into node_modules/.prisma/client/package.json.
    2. Run pkg -t node16-linux-x64 index.js -d again.
    > [debug] prebuild-install failed[/home/geter/data/3-Subject/04-Production/CloudStation/tmp/node_modules/.prisma/client/libquery_engine-debian-openssl-3.0.x.so.node]:
      Command failed: /usr/local/lib/node_modules/pkg/node_modules/.bin/prebuild-install --target v16.16.0 --platform linux --arch x64
    prebuild-install WARN install No prebuilt binaries found (target=v16.16.0 runtime=node arch=x64 libc= platform=linux)
    
    1. Try to specify the asset option into package.json and it looks like:
    "pkg": {
        "assets": [
          "node_modules/.prisma/client/*.node"
        ],
        "targets": [
          "node16-linux-x64"
        ]
    }
    
    1. Run pkg -c package.json index.js, errors show again.
    2. Run ./index.
    /snapshot/tmp/node_modules/@prisma/client/runtime/index.js:35038
          throw new PrismaClientInitializationError(message, this.client._clientVersion);
                ^
    
    PrismaClientInitializationError: 
    Invalid `prisma.visit.findMany()` invocation:
    
    
    Unable to load Node-API Library from /snapshot/tmp/node_modules/.prisma/client/libquery_engine-debian-openssl-3.0.x.so.node, Library may be corrupt: UNEXPECTED-15
        at RequestHandler.handleRequestError (/snapshot/tmp/node_modules/@prisma/client/runtime/index.js:35038:13)
        at RequestHandler.handleAndLogRequestError (/snapshot/tmp/node_modules/@prisma/client/runtime/index.js:34996:12)
        at /snapshot/tmp/node_modules/@prisma/client/runtime/index.js:35542:25
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async PrismaClient._executeRequest (/snapshot/tmp/node_modules/@prisma/client/runtime/index.js:36111:22)
        at async PrismaClient._request (/snapshot/tmp/node_modules/@prisma/client/runtime/index.js:36082:16) {
      clientVersion: '4.8.1',
      errorCode: undefined
    }
    

    Expected behavior

    vercel/pkg should output nothing and the binary file runs correctly.

    Prisma information

    generator client {
        provider      = "prisma-client-js"
        binaryTargets = ["debian-openssl-3.0.x"]
    }
    
    datasource db {
        provider = "sqlite"
        url      = "file:main.db"
    }
    
    model temp {
        ID Int @id @default(autoincrement())
    }
    
    import { PrismaClient } from "@prisma/client";
    
    !async function () {
    	console.log(await new PrismaClient().temp.findMany());
    }();
    

    Environment & setup

    • OS: Ubuntu Server 22.04LTS
    • Database: SQLite
    • Node.js version: v16.17.1

    Prisma Version

    prisma                  : 4.8.1
    @prisma/client          : 4.8.1
    Current platform        : debian-openssl-3.0.x
    Query Engine (Node-API) : libquery-engine d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/libquery_engine-debian-openssl-3.0.x.so.node)
    Migration Engine        : migration-engine-cli d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/migration-engine-debian-openssl-3.0.x)
    Introspection Engine    : introspection-core d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/introspection-engine-debian-openssl-3.0.x)
    Format Binary           : prisma-fmt d6e67a83f971b175a593ccc12e15c4a757f93ffe (at node_modules/@prisma/engines/prisma-fmt-debian-openssl-3.0.x)
    Format Wasm             : @prisma/prisma-fmt-wasm 4.8.0-61.d6e67a83f971b175a593ccc12e15c4a757f93ffe
    Default Engines Hash    : d6e67a83f971b175a593ccc12e15c4a757f93ffe
    Studio                  : 0.479.0
    
    kind/bug 
    opened by tatsuketer 0
  • Possible memory leak when running tests with Jest

    Possible memory leak when running tests with Jest

    Bug description

    We have a memory leak when we run a number of tests (~100) with Jest which eventually leads to a crash. Each test leaks around 40-50 mb of memory. While we can't positively say that Prisma is at fault, we have some data to support that hypothesis.

    When we take a heap snapshot of early in the test run and late in the test run, we find that Code and Strings grow disproportionately larger relative to the other segments.

    Early in the run: Screen Shot 2023-01-05 at 2 24 25 PM

    Late in the run: Screen Shot 2023-01-05 at 2 23 45 PM

    If I sort by shallow size descending and expand the strings segment, we find that the Prisma runtime index.js is near the top and repeated many times (note the repeated 2 444 640 shallow size): Screen Shot 2023-01-05 at 2 25 38 PM

    We find the same if we expand compiled code (note the repeated shallow sizes of 257 312): Screen Shot 2023-01-05 at 2 26 26 PM

    So while we can't positively say Prisma is the reason for our memory leak and eventual crash, it does seem to be the dominator in the segments that grew disproportionately. We use Prisma 4.5.0, NestJS 9.0, and Jest 28.1.2 and set up our prisma client using this recipe. The memory leak occurs whether we run the tests in parallel or in serial.

    Happy to share more information if it would be helpful! Cheers!

    How to reproduce

    • Set up a project in NestJS using Prisma
    • Set up a few tests that inject the Prisma service
    • Run jest while logging heap usage: node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage
    • Watch heap size grow over time

    Expected behavior

    Expect heap size to remain relatively consistent or at least not grow to the point of crashing

    Prisma information

    // Add your schema.prisma
    
    // Add your code using Prisma Client
    

    I can't share the schema. The prisma client is set up using the NestJS recipe here: https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services

    Environment & setup

    • OS: macOS
    • Database: PostgreSQL
    • Node.js version: v18.10.0

    This also occurs on github actions using ubuntu-latest

    Prisma Version

    4.5.0
    
    kind/bug 
    opened by dwayneyuen 0
  • fix: upgrade temp-write to use recent version of uuid

    fix: upgrade temp-write to use recent version of uuid

    Context:

    warning typegraphql-prisma > @prisma/internals > temp-write > [email protected]: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.

    The library "uuid" was used by an older version of temp-write.

    opened by tboutron 1
Releases(4.8.1)
Owner
Prisma
Prisma makes working with databases easy
Prisma
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite datab

MikroORM 5.4k Dec 31, 2022
Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

DbGate 2k Dec 30, 2022
A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud.

Dittorm A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud. Installatio

Waline 21 Dec 25, 2022
An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more

Waterline is a next-generation storage and retrieval engine, and the default ORM used in the Sails framework. It provides a uniform API for accessing

Balderdash 5.4k Jan 4, 2023
Azure Data Studio is a data management tool that enables you to work with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Azure Data Studio is a data management tool that enables working with SQL Server, Azure SQL DB and SQL DW from Windows, macOS and Linux.

Microsoft 7k Dec 31, 2022
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

bookshelf.js Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features both Promise-based and traditional callback i

Bookshelf.js 6.3k Jan 2, 2023
An easy-to-use multi SQL dialect ORM tool for Node.js

Sequelize Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction s

Sequelize 27.3k Jan 4, 2023
An SQL-friendly ORM for Node.js

Objection.js Objection.js is an ORM for Node.js that aims to stay out of your way and make it as easy as possible to use the full power of SQL and the

Vincit 6.9k Jan 5, 2023
just a graphql example created by typescript + fastify + mikro-orm(postgresql) + mercurius(graphql adaptor) + type-graphql

fastify-mikro-orm-mercurius-graphql-example A MikroORM boilerplate for GraphQL made with Fastify, Mercurius, Typescript using TypeGraphQL ?? Packages

Vigen 10 Aug 28, 2022
Validate and auto-generate TypeScript types from raw SQL queries in PostgreSQL.

SafeQL Write SQL Queries With Confidence • Get started Install I would first recommend follow the instructions in the documentation. npm install --sav

null 747 Dec 28, 2022
Ecommerce-backend-nestjs - Ecommerce app with Nestjs + Prisma ORM + GraphQL + SQLite

ECOMMERCE BACKEND NESTJS APP Nestjs + Prisma ORM + GraphQL + SQLite USER Create Account Login Product Create Product Get Products Get Product Search P

Rui Paulo Calei 5 Apr 6, 2022
Connect to private Google Cloud SQL instance through Cloud SQL Auth Proxy running in Kubernetes.

⛅ google-cloud-sql A CLI app which establishes a connection to a private Google Cloud SQL instance and port-forwards it to a local machine. Connection

Dinko Osrecki 10 Oct 16, 2022
A typesafe database ORM that exposes the full power of handwritten sql statements to the developer.

TORM A typesafe database ORM that exposes the full power of handwritten sql statements to the developer. import { torm, z } from 'https://deno.land/x/

Andrew Kaiser 15 Dec 22, 2022
This is a demo sample of linking NODEJS via ORM and MYSQL

Demons(Demo of Nodejs with SQL) This is a demo sample of linking NODEJS with ORM and MYSQL Connecting Node to SQL is a hard task and not much help is

Shivam Sourav Jha 3 Apr 14, 2022
A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for storage and cloud sql proxy.

Simple URL Shorter - Google Cloud - Kubernetes A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for

null 3 Nov 25, 2021
A query builder for PostgreSQL, MySQL and SQLite3, designed to be flexible, portable, and fun to use.

knex.js A SQL query builder that is flexible, portable, and fun to use! A batteries-included, multi-dialect (MSSQL, MySQL, PostgreSQL, SQLite3, Oracle

knex 16.9k Jan 4, 2023
Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

방신우 22 Dec 23, 2022
Database driven code generation for ts-sql-query

ts-sql-codegen This utility generates table mapper classes for ts-sql-query by inspecting a database through tbls. While it is possible to use ts-sql-

Lorefnon 12 Dec 12, 2022