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.
We'll cover the following...
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.
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,
StringandInt.) - Model: A field can have a
modelas afieldtype, 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 withxrepresenting the character length. -
@id: Sets the column as the primaryidcolumn 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.
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.