Skip to content

Commit 8cefac0

Browse files
Merge pull request #1586 from nikolasburk/patch-1
docs(prisma): use prisma migrate instead of instrospection
2 parents 935f809 + d123aca commit 8cefac0

File tree

1 file changed

+78
-80
lines changed

1 file changed

+78
-80
lines changed

content/recipes/prisma.md

Lines changed: 78 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
### Prisma
22

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.
44

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).
66

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.
108
119
#### Getting started
1210

1311
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.
1412

1513
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.
1614

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+
1718
#### Create your NestJS project
1819

1920
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
3031
Start by installing the Prisma CLI as a development dependency in your project:
3132

3233
```bash
34+
$ cd hello-prisma
3335
$ npm install @prisma/cli --save-dev
3436
```
3537

@@ -66,15 +68,11 @@ This command creates a new `prisma` directory with the following contents:
6668
- `schema.prisma`: Specifies your database connection and contains the database schema
6769
- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file, typically used to store your database credentials in a group of environment variables
6870

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
7272

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`:
7474

75-
Next, open up `schema.prisma` and adjust the `provider` field of the `datasource` block to `sqlite`:
76-
77-
```prisma
75+
```groovy
7876
datasource db {
7977
provider = "sqlite"
8078
url = env("DATABASE_URL")
@@ -91,15 +89,19 @@ Now, open up `.env` and adjust the `DATABASE_URL` environment variable to look a
9189
DATABASE_URL="file:./dev.db"
9290
```
9391

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+
9494
<details><summary>Expand if you're using PostgreSQL or MySQL</summary>
9595

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+
9698
**PostgreSQL**
9799

98100
If you're using PostgreSQL, you have to adjust the `schema.prisma` and `.env` files as follows:
99101

100102
**`schema.prisma`**
101103

102-
```prisma
104+
```groovy
103105
datasource db {
104106
provider = "postgresql"
105107
url = env("DATABASE_URL")
@@ -130,7 +132,7 @@ If you're using MySQL, you have to adjust the `schema.prisma` and `.env` files a
130132

131133
**`schema.prisma`**
132134

133-
```prisma
135+
```groovy
134136
datasource db {
135137
provider = "mysql"
136138
url = env("DATABASE_URL")
@@ -151,92 +153,83 @@ Replace the placeholders spelled in all uppercase letters with your database cre
151153

152154
</details>
153155

154-
#### Create two database tables
156+
#### Create two database tables with Prisma Migrate
155157

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.
157159

158-
**Mac OS / Linux**
160+
Add the following two models to your `schema.prisma` file:
159161

160-
```bash
161-
$ sqlite3 dev.db \
162-
'CREATE TABLE "User" (
163-
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
164-
"name" TEXT,
165-
"email" TEXT NOT NULL UNIQUE
166-
);
167-
CREATE TABLE "Post" (
168-
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
169-
"title" TEXT NOT NULL,
170-
"content" TEXT,
171-
"published" BOOLEAN DEFAULT false,
172-
"authorId" INTEGER REFERENCES "User"(id)
173-
);
174-
'
162+
```groovy
163+
model User {
164+
id Int @default(autoincrement()) @id
165+
email String @unique
166+
name String?
167+
posts Post[]
168+
}
169+
170+
model Post {
171+
id Int @default(autoincrement()) @id
172+
title String
173+
content String?
174+
published Boolean? @default(false)
175+
author User? @relation(fields: [authorId], references: [id])
176+
authorId Int?
177+
}
175178
```
176179

177-
**Windows**
180+
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:
178181

179182
```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
193184
```
194185

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).
198187
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:
202189

203190
```bash
204-
$ npx prisma introspect
191+
$ tree prisma
192+
prisma
193+
├── dev.db
194+
├── migrations
195+
│ └── 20201207100915_init
196+
│ └── migration.sql
197+
└── schema.prisma
205198
```
206199

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>
208201

209-
```prisma
210-
generator client {
211-
provider = "prisma-client-js"
212-
}
202+
The following tables were created in your SQLite database:
213203

214-
datasource db {
215-
provider = "sqlite"
216-
url = env("DATABASE_URL")
217-
}
204+
```sql
205+
-- CreateTable
206+
CREATE TABLE "User" (
207+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
208+
"email" TEXT NOT NULL,
209+
"name" TEXT
210+
);
218211

219-
model User {
220-
email String @unique
221-
id Int @default(autoincrement()) @id
222-
name String?
223-
Post Post[]
224-
}
212+
-- CreateTable
213+
CREATE TABLE "Post" (
214+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
215+
"title" TEXT NOT NULL,
216+
"content" TEXT,
217+
"published" BOOLEAN DEFAULT false,
218+
"authorId" INTEGER,
225219

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 DELETE SET NULL ON UPDATE CASCADE
221+
);
222+
223+
-- CreateIndex
224+
CREATE UNIQUE INDEX "User.email_unique" ON "User"("email");
234225
```
235226

236-
With your Prisma models in place, you can install and generate Prisma Client.
227+
</details>
237228

238229
#### Install and generate Prisma Client
239230

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+
240233
To install Prisma Client in your project, run the following command in your terminal:
241234

242235
```bash
@@ -293,7 +286,7 @@ export class UserService {
293286
constructor(private prisma: PrismaService) {}
294287

295288
async user(userWhereUniqueInput: UserWhereUniqueInput): Promise<User | null> {
296-
return this.prisma.user.findOne({
289+
return this.prisma.user.findUnique({
297290
where: userWhereUniqueInput,
298291
});
299292
}
@@ -363,7 +356,7 @@ export class PostService {
363356
constructor(private prisma: PrismaService) {}
364357

365358
async post(postWhereUniqueInput: PostWhereUniqueInput): Promise<Post | null> {
366-
return this.prisma.post.findOne({
359+
return this.prisma.post.findUnique({
367360
where: postWhereUniqueInput,
368361
});
369362
}
@@ -537,4 +530,9 @@ This controller implements the following routes:
537530

538531
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.
539532

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/)
537+
- [Production-ready starter kit](https://github.com/fivethree-team/nestjs-prisma-starter#instructions)
538+
- [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

Comments
 (0)