Convert Figma logo to code with AI

prisma logoprisma

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

38,831
1,519
38,831
3,196

Top Related Projects

33,970

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

An SQL-friendly ORM for Node.js

Quick Overview

Prisma is a modern database toolkit for Node.js and TypeScript. It simplifies database access and management with an auto-generated query builder, migrations, and type-safe database access. Prisma supports multiple databases, including PostgreSQL, MySQL, SQLite, and MongoDB.

Pros

  • Type-safe database queries with auto-completion
  • Automatic migrations and schema management
  • Supports multiple databases with a unified API
  • Excellent documentation and developer experience

Cons

  • Learning curve for developers new to ORM concepts
  • Limited support for complex database operations
  • Performance overhead for some operations compared to raw SQL
  • Potential vendor lock-in due to Prisma-specific syntax

Code Examples

  1. Defining a Prisma schema:
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}
  1. Querying data with Prisma Client:
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  const users = await prisma.user.findMany({
    include: { posts: true }
  })
  console.log(users)
}

main()
  .catch(e => console.error(e))
  .finally(async () => await prisma.$disconnect())
  1. Creating a new record:
const newUser = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice',
    posts: {
      create: { title: 'Hello World' }
    }
  }
})

Getting Started

  1. Install Prisma CLI:
npm install prisma --save-dev
  1. Initialize Prisma in your project:
npx prisma init
  1. Define your schema in prisma/schema.prisma

  2. Generate Prisma Client:

npx prisma generate
  1. Use Prisma Client in your code:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

// Now you can use prisma to query your database

Competitor Comparisons

33,970

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • More flexible and customizable, allowing for complex queries and relationships
  • Supports a wider range of databases, including NoSQL options
  • Has a more mature ecosystem with extensive documentation and community support

Cons of TypeORM

  • Steeper learning curve, especially for complex use cases
  • Requires more boilerplate code for setup and configuration
  • Performance can be slower for large-scale applications compared to Prisma

Code Comparison

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

Prisma:

model User {
  id   Int    @id @default(autoincrement())
  name String
}

TypeORM requires more decorators and explicit type definitions, while Prisma uses a more concise schema definition language. TypeORM's approach offers more flexibility but can be more verbose, whereas Prisma's schema is simpler and easier to read at a glance.

Both ORMs have their strengths and weaknesses, and the choice between them often depends on specific project requirements, team expertise, and scalability needs.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • More mature and established ORM with a larger ecosystem
  • Supports a wider range of databases out-of-the-box
  • Offers more flexibility in defining models and relationships

Cons of Sequelize

  • Steeper learning curve, especially for complex queries
  • Less type-safe compared to Prisma's generated types
  • Requires more boilerplate code for common operations

Code Comparison

Sequelize model definition:

const User = sequelize.define('User', {
  name: DataTypes.STRING,
  email: DataTypes.STRING
});

Prisma schema definition:

model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String
}

Sequelize offers more flexibility in model definition but requires more code, while Prisma provides a more concise and declarative approach. Prisma's schema is easier to read and maintain, especially for larger projects. However, Sequelize's flexibility can be advantageous for complex scenarios or when working with legacy databases.

Both ORMs have their strengths, and the choice between them often depends on project requirements, team expertise, and specific use cases.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • More flexible and lightweight, allowing for fine-grained control over SQL queries
  • Supports a wider range of databases, including less common ones
  • Better performance for complex queries and large-scale applications

Cons of Knex

  • Requires more manual work and boilerplate code for common operations
  • Less type safety and IDE support compared to Prisma's strong typing
  • Steeper learning curve for developers new to SQL and query building

Code Comparison

Knex query:

knex('users')
  .where('age', '>', 18)
  .andWhere('is_active', true)
  .select('name', 'email')

Prisma query:

prisma.user.findMany({
  where: {
    age: { gt: 18 },
    is_active: true
  },
  select: { name: true, email: true }
})

Both Knex and Prisma are popular query builders and ORMs for Node.js applications. Knex offers more flexibility and control over SQL queries, while Prisma provides a more user-friendly and type-safe approach. The choice between them depends on the specific needs of your project, such as database support, performance requirements, and developer preferences.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.

Pros of MikroORM

  • More flexible and customizable, allowing for complex queries and relationships
  • Supports both Active Record and Data Mapper patterns
  • Better TypeScript support with strict typing and decorators

Cons of MikroORM

  • Steeper learning curve due to more complex API
  • Smaller community and ecosystem compared to Prisma
  • Less automated schema management and migrations

Code Comparison

MikroORM:

@Entity()
export class User {
  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;
}

const user = orm.em.create(User, { name: 'John' });
await orm.em.persistAndFlush(user);

Prisma:

model User {
  id   Int    @id @default(autoincrement())
  name String
}

const user = await prisma.user.create({
  data: { name: 'John' },
});

MikroORM offers more control over entity definitions and persistence, while Prisma provides a simpler, more declarative approach. MikroORM's code is more verbose but allows for greater customization, whereas Prisma's schema and operations are more concise and easier to understand at a glance.

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

Pros of Bookshelf

  • Lightweight and flexible ORM with minimal overhead
  • Supports multiple database systems (PostgreSQL, MySQL, SQLite3)
  • Provides a more traditional ORM approach, familiar to developers coming from other ecosystems

Cons of Bookshelf

  • Less automated schema management and migration tools
  • Requires more manual configuration and setup
  • Smaller community and ecosystem compared to Prisma

Code Comparison

Bookshelf model definition:

const User = bookshelf.Model.extend({
  tableName: 'users',
  posts() {
    return this.hasMany(Post);
  }
});

Prisma schema definition:

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

Bookshelf offers a more JavaScript-centric approach to defining models and relationships, while Prisma uses a declarative schema language. Prisma's approach is more concise and provides stronger type safety, but Bookshelf's method may feel more familiar to JavaScript developers.

Prisma generally requires less boilerplate code and offers more advanced features out of the box, such as automatic migrations and a powerful query API. However, Bookshelf provides more flexibility for custom configurations and may be preferred for simpler projects or those requiring fine-grained control over database interactions.

An SQL-friendly ORM for Node.js

Pros of Objection.js

  • More flexible and customizable, allowing for complex queries and relationships
  • Better integration with existing Node.js and Express applications
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, Oracle)

Cons of Objection.js

  • Steeper learning curve, especially for developers new to ORM concepts
  • Less automated schema management and migrations compared to Prisma
  • Requires more boilerplate code for basic CRUD operations

Code Comparison

Objection.js:

const user = await User.query()
  .findById(1)
  .withGraphFetched('posts')
  .modifyGraph('posts', builder => {
    builder.orderBy('createdAt', 'desc');
  });

Prisma:

const user = await prisma.user.findUnique({
  where: { id: 1 },
  include: {
    posts: {
      orderBy: { createdAt: 'desc' }
    }
  }
});

Both Objection.js and Prisma are powerful ORMs for Node.js, but they cater to different needs. Objection.js offers more flexibility and control, making it suitable for complex applications with specific requirements. Prisma, on the other hand, provides a more streamlined development experience with its auto-generated client and simplified query API. The choice between the two depends on the project's complexity, the team's expertise, and the desired level of abstraction.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Prisma

Prisma

Discord

Quickstart   â€¢   Website   â€¢   Docs   â€¢   Examples   â€¢   Blog   â€¢   Discord   â€¢   Twitter

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.

The Prisma ORM can also further be extended with these Prisma products:

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 Prisma works

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 gets updated:

npx prisma generate

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

Using Prisma Client to send queries to your database

Once the Prisma Client is generated, you can import it 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 a 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: 'alice@prisma.io',
    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 Discord and here on GitHub.

Security

If you have a security issue to report, please contact us at security@prisma.io.

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 👍 reaction 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.

Tests Status

  • Prisma Tests Status:
    Prisma Tests Status
  • Ecosystem Tests Status:
    Ecosystem Tests Status

NPM DownloadsLast 30 Days