You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/recipes/prisma.md
+78-80Lines changed: 78 additions & 80 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,19 +1,20 @@
1
1
### Prisma
2
2
3
-
[Prisma](https://www.prisma.io) is an [open-source](https://github.com/prisma/prisma)database toolkit. You can use it to query data from a database inside a Node.js or TypeScript application. Prisma and NestJS go great together since you can use Prisma in your services to fulfill the data needs from your controllers.
3
+
[Prisma](https://www.prisma.io) is an [open-source](https://github.com/prisma/prisma)ORM for Node.js and TypeScript. It is used as an **alternative** to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](https://knexjs.org/)) or ORMs (like [TypeORM](https://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL, SQL Server and SQLite.
4
4
5
-
Prisma is used as an **alternative** to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](https://knexjs.org/)) or ORMs (like [TypeORM](https://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL and SQLite.
5
+
While Prisma can be used with plain JavaScript, it embraces TypeScript and provides a level to type-safety that goes beyond the guarantees other ORMs in the TypeScript ecosystem. You can find an in-depth comparison of the type-safety guarantees of Prisma and TypeORM[here](https://www.prisma.io/docs/concepts/more/comparisons/prisma-and-typeorm#type-safety).
6
6
7
-
While Prisma is a toolkit that contains multiple tools, the focus of this guide will be on using [Prisma Client](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). Prisma Client is an auto-generated and type-safe query builder that lets you read and write data in your database.
8
-
9
-
> info **Note** If you want to get a quick overview of how Prisma works, you can follow the [Quickstart](https://www.prisma.io/docs/getting-started/quickstart) or read the [Introduction](https://www.prisma.io/docs/understand-prisma/introduction) in the [documentation](https://www.prisma.io/docs/).
7
+
> info **Note** If you want to get a quick overview of how Prisma works, you can follow the [Quickstart](https://www.prisma.io/docs/getting-started/quickstart) or read the [Introduction](https://www.prisma.io/docs/understand-prisma/introduction) in the [documentation](https://www.prisma.io/docs/). There also are ready-to-run examples for [REST](https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-nestjs) and [GraphQL](https://github.com/prisma/prisma-examples/tree/latest/typescript/graphql-nestjs) in the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repo.
10
8
11
9
#### Getting started
12
10
13
11
In this recipe, you'll learn how to get started with NestJS and Prisma from scratch. You are going to build a sample NestJS application with a REST API that can read and write data in a database.
14
12
15
13
For the purpose of this guide, you'll use a [SQLite](https://sqlite.org/) database to save the overhead of setting up a database server. Note that you can still follow this guide, even if you're using PostgreSQL or MySQL – you'll get extra instructions for using these databases at the right places.
16
14
15
+
> info **Note** If you already have an existing project and consider migrating to Prisma, you can follow the guide for [adding Prisma to an existing project](https://www.prisma.io/docs/getting-started/setup-prisma/add-to-existing-project-typescript-postgres). If you are migrating from TypeORM, you can read the guide [Migrating from TypeORM to Prisma](https://www.prisma.io/docs/guides/migrate-to-prisma/migrate-from-typeorm).
16
+
17
+
17
18
#### Create your NestJS project
18
19
19
20
To get started, install the NestJS CLI and create your app skeleton with the following commands:
@@ -30,6 +31,7 @@ See the [First steps](https://docs.nestjs.com/first-steps) page to learn more ab
30
31
Start by installing the Prisma CLI as a development dependency in your project:
31
32
32
33
```bash
34
+
$ cd hello-prisma
33
35
$ npm install @prisma/cli --save-dev
34
36
```
35
37
@@ -66,15 +68,11 @@ This command creates a new `prisma` directory with the following contents:
66
68
-`schema.prisma`: Specifies your database connection and contains the database schema
67
69
-`.env`: A [dotenv](https://github.com/motdotla/dotenv) file, typically used to store your database credentials in a group of environment variables
68
70
69
-
#### Create your SQLite database file and set the database connection
70
-
71
-
SQLite databases are simple files; no server is required to use a SQLite database. You can therefore create a new SQLite database by manually creating a new file on your file system.
71
+
#### Set the database connection
72
72
73
-
Navigate into the new `prisma`directory and create a file called `dev.db` inside of it.
73
+
Your database connection is configured in the `datasource` block in your `schema.prisma`file. By default it's set to `postgresql`, but since you're using a SQLite database in this guide you need to adjust the `provider` field of the `datasource` block to `sqlite`:
74
74
75
-
Next, open up `schema.prisma` and adjust the `provider` field of the `datasource` block to `sqlite`:
76
-
77
-
```prisma
75
+
```groovy
78
76
datasource db {
79
77
provider = "sqlite"
80
78
url = env("DATABASE_URL")
@@ -91,15 +89,19 @@ Now, open up `.env` and adjust the `DATABASE_URL` environment variable to look a
91
89
DATABASE_URL="file:./dev.db"
92
90
```
93
91
92
+
SQLite databases are simple files; no server is required to use a SQLite database. So instead of configuring a connection URL with a _host_ and _port_, you can just point it to a local file which in this case is called `dev.db`. This file will be created in the next step.
93
+
94
94
<details><summary>Expand if you're using PostgreSQL or MySQL</summary>
95
95
96
+
With PostgreSQL and MySQL, you need to configure the connection URL to point to the _database server_. You can learn more about the required connection URL format [here](https://www.prisma.io/docs/reference/database-reference/connection-urls).
97
+
96
98
**PostgreSQL**
97
99
98
100
If you're using PostgreSQL, you have to adjust the `schema.prisma` and `.env` files as follows:
99
101
100
102
**`schema.prisma`**
101
103
102
-
```prisma
104
+
```groovy
103
105
datasource db {
104
106
provider = "postgresql"
105
107
url = env("DATABASE_URL")
@@ -130,7 +132,7 @@ If you're using MySQL, you have to adjust the `schema.prisma` and `.env` files a
130
132
131
133
**`schema.prisma`**
132
134
133
-
```prisma
135
+
```groovy
134
136
datasource db {
135
137
provider = "mysql"
136
138
url = env("DATABASE_URL")
@@ -151,92 +153,83 @@ Replace the placeholders spelled in all uppercase letters with your database cre
151
153
152
154
</details>
153
155
154
-
#### Create two database tables
156
+
#### Create two database tables with Prisma Migrate
155
157
156
-
In this section, you'll create two new tables in your database. Run the following SQL statements in your terminal:
158
+
In this section, you'll create two new tables in your database using [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate). Prisma Migrate generates SQL migration files for your declarative data model definition in the Prisma schema. These migration files are fully customizable so that you can configure any additional features of the underlying database or include additional commands, e.g. for seeding.
157
159
158
-
**Mac OS / Linux**
160
+
Add the following two models to your `schema.prisma` file:
With your Prisma models in place, you can generate your SQL migration files and run them against the database. Run the following commands in your terminal:
178
181
179
182
```bash
180
-
$ sqlite3 ./prisma/dev.db
181
-
CREATE TABLE "User" (
182
-
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
183
-
"name" TEXT,
184
-
"email" TEXT NOT NULL UNIQUE
185
-
);
186
-
CREATE TABLE "Post" (
187
-
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
188
-
"title" TEXT NOT NULL,
189
-
"content" TEXT,
190
-
"published" BOOLEAN DEFAULT false,
191
-
"authorId" INTEGER REFERENCES "User"(id)
192
-
);
183
+
$ npx prisma migrate dev --name init --preview-feature
193
184
```
194
185
195
-
Note that Prisma also features a **schema migration** tool called [Prisma Migrate](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-migrate). Prisma Migrate lets you manually define your models in your Prisma schema and takes care of creating the tables in your database. Because Prisma Migrate is currently considered experimental, this guide uses an alternative workflow of using plain SQL to create your database tables and generate Prisma models via [introspection](https://www.prisma.io/docs/reference/tools-and-interfaces/introspection).
196
-
197
-
#### Introspect your database to obtain your Prisma models in the Prisma schema
186
+
> info **Note** The `prisma migrate` commands currently requires the `--preview-feature` option as it's in [Preview](https://www.prisma.io/docs/about/releases#preview).
198
187
199
-
Now that you've created your database tables, you can **introspect** the database to generate your [Prisma models](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-schema/models). After that, you will install and generate Prisma Client, which will expose queries that are tailored to these models.
200
-
201
-
To introspect your database, run the following command in your terminal:
188
+
This `prisma migrate dev` command generates SQL files and directly runs them against the database. In this case, the following migration files was created in the existing `prisma` directory:
202
189
203
190
```bash
204
-
$ npx prisma introspect
191
+
$ tree prisma
192
+
prisma
193
+
├── dev.db
194
+
├── migrations
195
+
│ └── 20201207100915_init
196
+
│ └── migration.sql
197
+
└── schema.prisma
205
198
```
206
199
207
-
This reads your SQL schema and translates each table into a corresponding Prisma model. Your `schema.prisma` file now looks as follows:
200
+
<details><summary>Expand to view the generated SQL statements</summary>
208
201
209
-
```prisma
210
-
generator client {
211
-
provider = "prisma-client-js"
212
-
}
202
+
The following tables were created in your SQLite database:
213
203
214
-
datasource db {
215
-
provider = "sqlite"
216
-
url = env("DATABASE_URL")
217
-
}
204
+
```sql
205
+
-- CreateTable
206
+
CREATETABLE "User" (
207
+
"id"INTEGERNOT NULLPRIMARY KEY AUTOINCREMENT,
208
+
"email"TEXTNOT NULL,
209
+
"name"TEXT
210
+
);
218
211
219
-
model User {
220
-
email String @unique
221
-
id Int @default(autoincrement()) @id
222
-
name String?
223
-
Post Post[]
224
-
}
212
+
-- CreateTable
213
+
CREATETABLE "Post" (
214
+
"id"INTEGERNOT NULLPRIMARY KEY AUTOINCREMENT,
215
+
"title"TEXTNOT NULL,
216
+
"content"TEXT,
217
+
"published"BOOLEAN DEFAULT false,
218
+
"authorId"INTEGER,
225
219
226
-
model Post {
227
-
authorId Int?
228
-
content String?
229
-
id Int @default(autoincrement()) @id
230
-
published Boolean? @default(false)
231
-
title String
232
-
User User? @relation(fields: [authorId], references: [id])
233
-
}
220
+
FOREIGN KEY ("authorId") REFERENCES"User"("id") ON DELETESETNULLONUPDATE CASCADE
221
+
);
222
+
223
+
-- CreateIndex
224
+
CREATE UNIQUE INDEX "User.email_unique"ON"User"("email");
234
225
```
235
226
236
-
With your Prisma models in place, you can install and generate Prisma Client.
227
+
</details>
237
228
238
229
#### Install and generate Prisma Client
239
230
231
+
Prisma Client is a type-safe database client that's _generated_ from your Prisma model definition. Because of this approach, Prisma Client can expose [CRUD](https://www.prisma.io/docs/concepts/components/prisma-client/crud) operations that are _tailored_ specifically to your models.
232
+
240
233
To install Prisma Client in your project, run the following command in your terminal:
@@ -537,4 +530,9 @@ This controller implements the following routes:
537
530
538
531
In this recipe, you learned how to use Prisma along with NestJS to implement a REST API. The controller that implements the routes of the API is calling a `PrismaService` which in turn uses Prisma Client to send queries to a database to fulfill the data needs of incoming requests.
539
532
540
-
If you want to learn more about Prisma, be sure to check out the [documentation](https://www.prisma.io/docs/).
533
+
If you want to learn more about using NestJS with Prisma, be sure to check out the following resources:
534
+
535
+
-[NestJS & Prisma](https://www.prisma.io/nestjs)
536
+
-[Ready-to-run example projects for REST & GraphQL](https://github.com/prisma/prisma-examples/)
-[Video: Accessing Databases using NestJS with Prisma (5min)](https://www.youtube.com/watch?v=UlVJ340UEuk&ab_channel=Prisma) by [Marc Stammerjohann](https://github.com/marcjulian)
0 commit comments