Lesson 13-Prisma Framework for Node.js

Prisma Core Concepts

Prisma is a modern, open-source Object-Relational Mapping (ORM) tool designed for Node.js and TypeScript developers to simplify database operations and provide a type-safe experience. It supports multiple databases, including PostgreSQL, MySQL, SQLite, MongoDB, SQL Server, and recently added Cloudflare D1.

What is Prisma?

Prisma is more than just an ORM; it is a comprehensive database toolkit that offers solutions for schema definition, data operations, migrations, and querying. Its core philosophy is to provide a type-safe, declarative API, enabling developers to interact with databases more efficiently and with fewer errors.

Why Choose Prisma?

  • Type Safety: Deep integration with TypeScript ensures type-safe database operations, reducing runtime errors.
  • Powerful Query API: Offers a rich query API for complex operations like relational queries, pagination, sorting, and filtering.
  • Data Model Definition: Uses Prisma Schema for declarative model definitions, making schemas clear and maintainable.
  • Data Migrations: Prisma Migrate simplifies schema changes and version control.
  • High Performance: Generates optimized SQL queries through a high-performance query engine.
  • Community and Ecosystem: Active community with extensive documentation, tutorials, and plugins.

Prisma’s Main Components

Prisma Schema

The core of Prisma, used to define data models. Prisma Schema is a text file containing the structure, fields, indexes, and relationships of database tables, serving as the bridge between Prisma and the database.

Prisma Client

A type-safe database query library auto-generated from Prisma Schema, offering a declarative way to perform database operations. It ensures type-safe interactions, reducing runtime errors.

Prisma Migrate

A database migration tool for managing schema changes. It allows developers to create, apply, and roll back migrations, keeping the database schema in sync with the codebase.

Prisma CLI

A command-line tool for Prisma-related tasks, such as generating Prisma Client, applying migrations, and launching Prisma Studio.

Prisma Studio

A graphical user interface for browsing and editing database data, providing an intuitive interface for data debugging during development.

Code Example

Below is a simple Prisma project setup and usage example:

Initialize Project

npm init -y
npm install prisma @prisma/client

Configure Prisma Schema

Create a prisma/schema.prisma file to define the data model:

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

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

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

Generate Prisma Client

npx prisma generate

Use Prisma Client

In your TypeScript code, import and use Prisma Client:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // Create a new user
  const user = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice'
    },
  })

  console.log(user)

  // Create a post linked to the user
  const post = await prisma.post.create({
    data: {
      title: 'Hello World',
      author: {
        connect: { id: user.id },
      },
    },
  })

  console.log(post)

  // Query user with posts
  const foundUser = await prisma.user.findUnique({
    where: { id: user.id },
    include: {
      posts: true,
    },
  })

  console.log(foundUser)

  await prisma.$disconnect()
}

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

Configuring Database Connections

Prisma supports multiple databases, including PostgreSQL, MySQL, SQLite, MongoDB, SQL Server, and Cloudflare D1. Specify the database type and connection details in prisma/schema.prisma.

PostgreSQL Configuration

datasource db {
  provider = "postgresql"
  url      = env("POSTGRES_URL")
}

Set POSTGRES_URL in the .env file:

POSTGRES_URL="postgresql://user:pass@host:port/dbname"

MySQL Configuration

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

Set MYSQL_URL in the .env file:

MYSQL_URL="mysql://user:pass@host:port/dbname"

SQLite Configuration

SQLite is a file-based database, typically requiring no username or password:

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

Set DATABASE_URL in the .env file:

DATABASE_URL="file:./dev.db"

SQL Server Configuration

datasource db {
  provider = "sqlserver"
  url      = env("SQLSERVER_URL")
}

Set SQLSERVER_URL in the .env file:

SQLSERVER_URL="sqlserver://user:pass@host:port/dbname"

MongoDB Configuration

MongoDB, a NoSQL database, is configured differently:

datasource db {
  provider = "mongodb"
  url      = env("MONGODB_URI")
}

Set MONGODB_URI in the .env file:

MONGODB_URI="mongodb://user:pass@host:port/dbname"

Cloudflare D1 Configuration

Cloudflare D1 is a new database service:

datasource db {
  provider = "d1"
  url      = env("D1_URL")
}

Set D1_URL in the .env file:

D1_URL="https://api.cloudflare.com/client/v4/accounts/ACCOUNT_ID/d1/bindings/DATABASE_NAME"

Multiple Database Configurations

To use multiple databases in a project, define multiple data sources in prisma/schema.prisma:

datasource postgresql {
  provider = "postgresql"
  url      = env("POSTGRES_URL")
}

datasource sqlite {
  provider = "sqlite"
  url      = env("SQLITE_URL")
}

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

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

model Post {
  id     Int      @id @default(autoincrement()) (sqlite)
  title  String
}

Prisma Architecture

Prisma Schema

Prisma Schema is a core component, typically stored in prisma/schema.prisma. It defines data models and database connection details using the Prisma Data Model Language (PDSL), allowing declarative specification of table structures, fields, indexes, and relationships.

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

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

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
}

This example defines User and Post models with a one-to-many relationship.

Prisma Client

Prisma Client is a type-safe query library auto-generated from Prisma Schema, providing methods for database operations like CRUD.

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  const user = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice'
    },
  })

  console.log(user)

  const post = await prisma.post.create({
    data: {
      title: 'Hello World',
      author: {
        connect: { id: user.id },
      },
    },
  })

  console.log(post)

  const foundUser = await prisma.user.findUnique({
    where: { id: user.id },
    include: {
      posts: true,
    },
  })

  console.log(foundUser)

  await prisma.$disconnect()
}

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

Prisma Migrate

Prisma Migrate manages database schema changes, allowing creation, application, and rollback of migrations to keep the schema in sync with the code.

npx prisma migrate dev --name initial
npx prisma migrate deploy

Prisma CLI

Prisma CLI is a command-line tool for tasks like generating Prisma Client, applying migrations, and launching Prisma Studio.

npx prisma generate
npx prisma studio

Prisma Studio

Prisma Studio is a GUI for browsing and editing database data, ideal for debugging during development.

npx prisma studio

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here

Share your love