Search⌘ K
AI Features

Introduction to Prisma

Explore Prisma, a popular TypeScript ORM that uses schema models to map database tables and defines relationships with fields and attributes. Understand Prisma's client API for type-safe database queries and automatic migrations, enabling efficient backend development with various SQL databases.

Overview of Prisma ORM

Prisma is a popular and stable library with an active community contributing to building TypeScript’s back-end applications. Among the ORMs used in the industry, Prisma happens to be one of the best. It uses regular JavaScript objects and can interact with any SQL database.

TypeScript 3.3.4
// create employee
const new_employee = await prisma.employee.create({
data: {
employee_name: 'Alice',
employee_email: 'alice@prisma.io',
},
})

Features of Prisma

Models

Prisma has a very unique structure. It provides a model that enables a well-outlined structure, defining how our database columns interact with each other.

//schema.prisma

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

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

model Employee {

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

Prisma schema

A key part of the Prisma schema is the model. The model maps to the table created in the database, similarly to how we defined Employee above. The parts of this model are called fields.

There are two major, supported field types:

  • Scalar: Scalar data types are the regular data types (for example, String and Int.)
  • Model: A field can have a model as a field type, and this is used to define relationships.

The Prisma schema also introduces attributes. These attributes map the column value to the native database data type. A few of these are:

  • @unique: Used to declare a column value as unique.

  • @default: Used to set a default value for the column.

  • @VarChar(x): Used to declare a character length for the column with x representing the character length.

  • @id: Sets the column as the primary id column for that given model or table.

API Interface

Another important feature is the Prisma client, which provides an interface for communicating with the database and carrying out queries.

TypeScript 3.3.4
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// create employee
const new_employee = await prisma.employee.create({
data: {
employee_name: 'Alice',
employee_email: 'alice@prisma.io',
},
})
// fetch-query:::get all employees
const employees = await prisma.employee.findMany()

Among other TypeScript ORMs, Prisma has a unique feature that automatically writes migration and generates type-safe code. Prisma currently supports MongoDB (preview), SQL Server, MySQL, PostgreSQL, and SQLite.