From a30e0f0bb2b973e20153a7b66864a6364905cf13 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 15:59:01 +0100 Subject: [PATCH 01/76] continue docs --- content/01-getting-started/02-quickstart.mdx | 31 +++++++++---------- .../01-add-to-an-existing-project.mdx | 2 +- .../02-start-from-scratch-sql-migrations.mdx | 2 +- .../02-understand-prisma/01-introduction.mdx | 4 +-- .../04-introspection.mdx | 2 +- 5 files changed, 20 insertions(+), 21 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index a2bd2fd5aa..b841f45b7a 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -28,8 +28,10 @@ Open your terminal and download the starter project with the following command: curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter ``` +This downloaded a directory called `starter`. +
-
Expand for more info on the starter project +
Expand for more info on the starter project The starter project consists of five files: @@ -63,9 +65,10 @@ The SQLite database file `prisma/dev.db` contains two tables with dummy data: > **Note**: The number in the `author` column references the `id` column of the `User` table: the `2` in the `author` column refers to the `User` record with an `id` value of `2`. -Befor you move on, installl the npm dependencies with this command: +Befor you move on, navigate into the `starter` directory and install the npm dependencies with these commands: ``` +cd starter npm install ``` @@ -334,6 +337,13 @@ const deletedUser = await prisma.user.delete({
+### Setup Prisma with your own database + +To learn how to connect Prisma to your own database, you can follow the respective setup guide: + +- [Add Prisma to an existing project]() +- [Setup Prisma from scratch with your own database]() + ### Explore the data in Prisma Studio (experimental) Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -344,8 +354,6 @@ npx prisma studio --experimental ### Change the database schema (e.g. add more tables) -#### SQL (recommended) - Changing your database schema using SQL typically happens with the following steps. First, run a SQL migration against your database, e.g. with this command in your terminal: @@ -377,13 +385,12 @@ This updates the generated Prisma Client library in [`node_modules/@prisma/clien You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. -
Alternative: Use Prisma Migrate (experimental) +
Alternative: Use Prisma Migrate (experimental) Changing your database schema using Prisma Migrate typically happens with the following steps. First, adjust the data model in your Prisma schema, e.g. by adding a new model: -{/* Note: Currently commented out because it breaks the syntax highlighting in VS Code ```prisma @@ -409,7 +416,6 @@ model Post { author User? } ``` -*/} Next, create a new migration by running the following command: @@ -424,18 +430,11 @@ Now you can run the migration against the database `npx prisma migrate up --exp You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. -### Setup Prisma with your own database - -To learn how to connect Prisma to your own database, you can follow the respective setup guide: - -- [Add Prisma to an existing project]() -- [Setup Prisma from scratch with your own database]() - ### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: -#### TypeScript +**TypeScript** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | @@ -445,7 +444,7 @@ The [`prisma-examples`]() repository contains a number of ready-to-run examples: | [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | | [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | -#### JavaScript (Node.js) +**JavaScript (Node.js)** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index 6e59dc3747..b19b29ef08 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -470,7 +470,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Re-introspect your database 1. Re-generate Prisma Client -![](https://imgur.com/x3x2nYl.png) +![](https://imgur.com/7BUqpyv.png) ### Try a Prisma example diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index 443a191849..4dcddef110 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -537,7 +537,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Re-introspect your database 1. Re-generate Prisma Client -![](https://imgur.com/x3x2nYl.png) +![](https://imgur.com/7BUqpyv.png) ### Try a Prisma example diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 1b2935d6ec..5e6a280ed7 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -113,7 +113,7 @@ The typical workflow when using SQL migrations and introspection looks as follow 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/x3x2nYl.png) +![](https://imgur.com/7BUqpyv.png) With Prisma Migrate, the workflow looks slightly different: @@ -122,6 +122,6 @@ With Prisma Migrate, the workflow looks slightly different: 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/sovxPh9.png) +![](https://imgur.com/nX0jIo5.png) To dive deeper, please refer to the respective docs page. \ No newline at end of file diff --git a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx index fb50849242..46ef655618 100644 --- a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx +++ b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx @@ -56,7 +56,7 @@ The typical workflow for projects that are not using Prisma Migrate, but instead Note that as you evolve the application, this process can be repeated for an indefinite number of times. -![](https://imgur.com/x3x2nYl.png) +![](https://imgur.com/7BUqpyv.png) ## Rules and conventions From 94387aad87b6466c6aa5f3fd9160fbe00eacde85 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 16:13:30 +0100 Subject: [PATCH 02/76] continue docs --- content/01-getting-started/02-quickstart.mdx | 42 ++++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index b841f45b7a..a525acb0d1 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -24,7 +24,7 @@ This guide comes with a small starter project that already has Prisma configured Open your terminal and download the starter project with the following command: -``` +```copy curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter ``` @@ -67,7 +67,7 @@ The SQLite database file `prisma/dev.db` contains two tables with dummy data: Befor you move on, navigate into the `starter` directory and install the npm dependencies with these commands: -``` +```copy cd starter npm install ``` @@ -109,7 +109,7 @@ Here's a quick overview of the main parts: Inside the `main` function, add the folowing query to read all `User` records from the database and print the result: -```js +```js copy async function main() { const allUsers = await prisma.user.findMany() console.log(allUsers) @@ -118,7 +118,7 @@ async function main() { Now run the code with this command: -``` +``` copy npm run dev ``` @@ -133,7 +133,7 @@ This should print following result to output: One of the main features of Prisma Client is the ease for working with relations. You can retrieve the `posts` of each user by using the `include` option. Adjust your code to look as follows: -```js +```js copy async function main() { const allUsers = await prisma.user.findMany({ include: { posts: true }, @@ -145,7 +145,7 @@ async function main() { Run the code again with: -``` +``` copy npm run dev ``` @@ -173,7 +173,7 @@ The `findMany` query you used in the previous section only _reads_ data from the Adjust the `main` function to send a `create` query to the database: -```js +```js copy async function main() { const post = await prisma.post.create({ data: { @@ -196,7 +196,7 @@ This code creates a new `Post` record and _connects_ it in a [nested write]() to Run the code with this command: -``` +``` copy npm run dev ``` @@ -240,7 +240,7 @@ The query added a new record to the `Post` table: Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: -```js +```js copy async function main() { const post = await prisma.post.update({ where: { id: 2 }, @@ -252,7 +252,7 @@ async function main() { Now run the code using the same command as before: -``` +``` copy npm run dev ``` @@ -292,7 +292,7 @@ Here are a few suggestions for a number of more queries you can send with Prisma **Filter all `Post` records that contain `"prisma"`** -```js +```js copy const filteredPosts = await prisma.post.findMany({ where: { OR: [ @@ -305,7 +305,7 @@ const filteredPosts = await prisma.post.findMany({ **Create a new `User` and a new `Post` record in the same query** -```js +```js copy const user = await prisma.user.create({ data: { name: "Nancy", @@ -319,7 +319,7 @@ const user = await prisma.user.create({ **Use the fluent relations API to retrieve the `Post` records of a `User`** -```js +```js copy const posts = await prisma.user .findOne({ where: { email: "sarah@prisma.io" }, @@ -329,7 +329,7 @@ const posts = await prisma.user **Delete a `User` record** -```js +```js copy const deletedUser = await prisma.user.delete({ where: { email: "sarah@prisma.io" }, }) @@ -348,7 +348,7 @@ To learn how to connect Prisma to your own database, you can follow the respecti Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: -``` +``` copy npx prisma studio --experimental ``` @@ -358,7 +358,7 @@ Changing your database schema using SQL typically happens with the following ste First, run a SQL migration against your database, e.g. with this command in your terminal: -``` +``` copy sqlite3 ./prisma/dev.db \ 'CREATE TABLE "Profile" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, @@ -369,7 +369,7 @@ sqlite3 ./prisma/dev.db \ Then, introspect your database with this command from the Prisma CLI: -``` +``` copy npx prisma introspect ``` @@ -377,7 +377,7 @@ This updates your [Prisma schema]()) in `prisma/schema.prisma`. Finally, re-generate Prisma Client with this command: -``` +``` copy npx prisma generate ``` @@ -391,9 +391,7 @@ Changing your database schema using Prisma Migrate typically happens with the fo First, adjust the data model in your Prisma schema, e.g. by adding a new model: -Note: Currently commented out because it breaks the syntax highlighting in VS Code - -```prisma +```prisma copy model Profile { id Int @id @default(autoincrement()) bio String @@ -419,7 +417,7 @@ model Post { Next, create a new migration by running the following command: -``` +```copy npx prisma migrate save --name "add-profile" --experimental npx prisma migrate up --experimental ``` From eaf63db691d3a398e99e931bda83630513172f32 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 17:18:13 +0100 Subject: [PATCH 03/76] continue docs --- content/01-getting-started/02-quickstart.mdx | 10 ++ .../03-start-from-scratch-prisma-migrate.mdx | 119 ------------------ 2 files changed, 10 insertions(+), 119 deletions(-) delete mode 100644 content/01-getting-started/03-setup-prisma/03-start-from-scratch-prisma-migrate.mdx diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index a525acb0d1..98f08c16ac 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -337,6 +337,9 @@ const deletedUser = await prisma.user.delete({
+ +--- + ### Setup Prisma with your own database To learn how to connect Prisma to your own database, you can follow the respective setup guide: @@ -344,6 +347,8 @@ To learn how to connect Prisma to your own database, you can follow the respecti - [Add Prisma to an existing project]() - [Setup Prisma from scratch with your own database]() +--- + ### Explore the data in Prisma Studio (experimental) Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -352,6 +357,8 @@ Prisma Studio is a visual editor for the data in your database. You can use it b npx prisma studio --experimental ``` +--- + ### Change the database schema (e.g. add more tables) Changing your database schema using SQL typically happens with the following steps. @@ -428,6 +435,9 @@ Now you can run the migration against the database `npx prisma migrate up --exp You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. +--- + + ### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: diff --git a/content/01-getting-started/03-setup-prisma/03-start-from-scratch-prisma-migrate.mdx b/content/01-getting-started/03-setup-prisma/03-start-from-scratch-prisma-migrate.mdx deleted file mode 100644 index 4031d1c8ab..0000000000 --- a/content/01-getting-started/03-setup-prisma/03-start-from-scratch-prisma-migrate.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: 'Start from scratch (Prisma Migrate)' -metaTitle: '' -metaDescription: '' ---- - -## Overview - -**Note: The content of this page is temporary and will be updated soon.** - -This page explains how to get started with Prisma from scratch by connecting it to an empty database. It uses Prisma Migrate to define and migrate your database schema. - -> **Warning**: Prisma Migrate is currently in an **experimental** state. When using any of the commands below, you need to explicitly opt-in via an `--experimental` flag, e.g. `prisma2 migrate save --name 'init' --experimental`. - -Follow these steps for an initial Prisma setup: - -1. Run `mkdir hello-prisma` to create your project directory -1. Run `cd hello-prisma` to navigate into it -1. Run `touch schema.prisma` to create an empty [Prisma schema](../../prisma-schema-file.md) -1. Add a `datasource` to the Prisma schema and set your database connection string as the `url`, e.g.: - ```prisma - datasource db { - provider = "postgresql" - url = "postgresql://janedoe:janedoe@localhost:5432/hello-prisma" - } - ``` -1. Add your models to the Prisma schema, e.g.: - - ```prisma - model Post { - post_id Int @id @default(autoincrement()) - content String? - title String - author User? - } - - model Profile { - profile_id Int @id @default(autoincrement()) - bio String? - user User - } - - model User { - user_id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profiles Profile[] - } - ``` - -1. Add a `generator` to the Prisma schema to be able to generate Prisma Client: - ```prisma - generator client { - provider = "prisma-client-js" - } - ``` -1. Run the following commands to configure your project (TypeScript): - ``` - npm init -y - npm install typescript ts-node prisma2 @types/node --save-dev - npm install @prisma/client - ``` -1. Run `touch tsconfig.json` and the following contents to it: - ```json - { - "compilerOptions": { - "sourceMap": true, - "outDir": "dist", - "strict": true, - "lib": ["esnext"], - "esModuleInterop": true - } - } - ``` -1. Migrate your database by running the following commands: - ``` - npx prisma2 migrate save --name 'init' --experimental - npx prisma2 migrate up --experimental - ``` -1. Generate Prisma Client based on your data model with the following command: - ``` - npx prisma2 generate - ``` -1. Run `touch index.ts` to create a source file and add the following code: - - ```ts - import { PrismaClient } from '@prisma/client'; - - const prisma = new PrismaClient(); - - // A `main` function so that we can use async/await - async function main() { - const user1 = await prisma.user.create({ - data: { - email: 'alice@prisma.io', - name: 'Alice', - posts: { - create: { - title: 'Watch the talks from Prisma Day 2019', - content: 'https://www.prisma.io/blog/z11sg6ipb3i1/', - }, - }, - }, - include: { - posts: true, - }, - }); - console.log(user1); - } - - main() - .catch(e => console.error(e)) - .finally(async () => { - await prisma.disconnect(); - }); - ``` - -1. Run `npx ts-node index.ts` to execute the script From 92641e50fbc050c1cfbbbc02f42de06063692a36 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 17:21:57 +0100 Subject: [PATCH 04/76] continue docs --- .../03-setup-prisma/01-add-to-an-existing-project.mdx | 8 ++++++-- .../02-start-from-scratch-sql-migrations.mdx | 10 ++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index b19b29ef08..01ec8fbddf 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -454,6 +454,8 @@ const deletedUser = await prisma.user.delete({
+--- + ### Explore the data in Prisma Studio (experimental) Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -472,11 +474,13 @@ To evolve the app, you need to follow the same flow of the tutorial: ![](https://imgur.com/7BUqpyv.png) +--- + ### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: -#### TypeScript +**TypeScript** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | @@ -486,7 +490,7 @@ The [`prisma-examples`]() repository contains a number of ready-to-run examples: | [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | | [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | -#### JavaScript (Node.js) +**JavaScript (Node.js)** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index 4dcddef110..eaffd29a85 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -521,6 +521,8 @@ const deletedUser = await prisma.user.delete({
+--- + ### Explore the data in Prisma Studio (experimental) Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -529,6 +531,8 @@ Prisma Studio is a visual editor for the data in your database. You can use it b npx prisma studio --experimental ``` +--- + ### Change the database schema (e.g. add more tables) To evolve the app, you need to follow the same flow of the tutorial: @@ -539,11 +543,13 @@ To evolve the app, you need to follow the same flow of the tutorial: ![](https://imgur.com/7BUqpyv.png) +--- + ### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: -#### TypeScript +**TypeScript** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | @@ -553,7 +559,7 @@ The [`prisma-examples`]() repository contains a number of ready-to-run examples: | [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | | [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | -#### JavaScript (Node.js) +**JavaScript (Node.js)** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | From 2ba32535e6e607b5c9463b2707fc46b152c691ca Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 17:44:34 +0100 Subject: [PATCH 05/76] continue docs --- .../01-what-is-prisma-migrate.mdx => 03-prisma-migrate.mdx} | 3 ++- .../01-tools-and-interfaces/03-prisma-migrate/index.mdx | 6 ------ 2 files changed, 2 insertions(+), 7 deletions(-) rename content/03-reference/01-tools-and-interfaces/{03-prisma-migrate/01-what-is-prisma-migrate.mdx => 03-prisma-migrate.mdx} (99%) delete mode 100644 content/03-reference/01-tools-and-interfaces/03-prisma-migrate/index.mdx diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate/01-what-is-prisma-migrate.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx similarity index 99% rename from content/03-reference/01-tools-and-interfaces/03-prisma-migrate/01-what-is-prisma-migrate.mdx rename to content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx index b571bb0630..640935ce37 100644 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate/01-what-is-prisma-migrate.mdx +++ b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx @@ -1,7 +1,8 @@ --- -title: 'What is Prisma Migrate' +title: 'Prisma Migrate' metaTitle: '' metaDescription: '' +experimental: true --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate/index.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate/index.mdx deleted file mode 100644 index db51c81e68..0000000000 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate/index.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: 'Prisma Migrate' -metaTitle: '' -metaDescription: '' -experimental: true ---- From ab2b826f1ad9c4dba2113f0ea070685e7615a65b Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 18:11:35 +0100 Subject: [PATCH 06/76] continue docs --- .../01-rest.md | 0 .../02-graphql.md | 0 .../index.mdx | 2 +- 3 files changed, 1 insertion(+), 1 deletion(-) rename content/02-understand-prisma/{03-how-prisma-fits-into-your-stack => 03-prisma-in-your-stack}/01-rest.md (100%) rename content/02-understand-prisma/{03-how-prisma-fits-into-your-stack => 03-prisma-in-your-stack}/02-graphql.md (100%) rename content/02-understand-prisma/{03-how-prisma-fits-into-your-stack => 03-prisma-in-your-stack}/index.mdx (71%) diff --git a/content/02-understand-prisma/03-how-prisma-fits-into-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md similarity index 100% rename from content/02-understand-prisma/03-how-prisma-fits-into-your-stack/01-rest.md rename to content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md diff --git a/content/02-understand-prisma/03-how-prisma-fits-into-your-stack/02-graphql.md b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md similarity index 100% rename from content/02-understand-prisma/03-how-prisma-fits-into-your-stack/02-graphql.md rename to content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md diff --git a/content/02-understand-prisma/03-how-prisma-fits-into-your-stack/index.mdx b/content/02-understand-prisma/03-prisma-in-your-stack/index.mdx similarity index 71% rename from content/02-understand-prisma/03-how-prisma-fits-into-your-stack/index.mdx rename to content/02-understand-prisma/03-prisma-in-your-stack/index.mdx index 1b5a9f46a4..ed30ac686b 100644 --- a/content/02-understand-prisma/03-how-prisma-fits-into-your-stack/index.mdx +++ b/content/02-understand-prisma/03-prisma-in-your-stack/index.mdx @@ -1,5 +1,5 @@ --- -title: 'How Prisma fits into your stack' +title: 'Prisma in your stack' metaTitle: 'How Prisma fits into your stack' metaDescription: 'How Prisma fits into your stack' --- From 843741da2f879d6108b524800a906632840f88ed Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Wed, 25 Mar 2020 19:15:43 +0100 Subject: [PATCH 07/76] continue docs --- content/01-getting-started/02-quickstart.mdx | 2 ++ .../03-setup-prisma/01-add-to-an-existing-project.mdx | 2 ++ .../03-setup-prisma/02-start-from-scratch-sql-migrations.mdx | 2 ++ .../02-importing-and-exporting-data/index.mdx | 2 +- .../04-unique-constraints-and-indexes/index.mdx | 2 +- .../08-renaming-tables-and-columns/index.mdx | 2 +- 6 files changed, 9 insertions(+), 3 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 98f08c16ac..5d137f16b5 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -280,6 +280,8 @@ Fantastic, you just wrote new data into your database for the first time using P ## Next steps +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. + ### Continue exploring the Prisma Client API You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index 01ec8fbddf..28416d71cb 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -397,6 +397,8 @@ node index.js ## Next steps +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. + ### Continue exploring the Prisma Client API You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing PostgreSQL-based setup from this guide to try them out. diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index eaffd29a85..486ee77106 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -464,6 +464,8 @@ Fantastic, you just wrote new data into your database for the first time using P ## Next steps +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. + ### Continue exploring the Prisma Client API You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing PostgreSQL-based setup from this guide to try them out. diff --git a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx b/content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx index 135dcfd040..d613cbe164 100644 --- a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx +++ b/content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx @@ -1,4 +1,4 @@ --- -title: 'Importing and exporting data' +title: 'Data import and export' metaTitle: 'Importing and exporting data' --- diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/index.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/index.mdx index 025cdb73ab..cb13132208 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/index.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/index.mdx @@ -1,4 +1,4 @@ --- -title: 'Unique constraints and indexes' +title: 'Unique constraints' metaTitle: '' --- diff --git a/content/04-guides/01-database-workflows/08-renaming-tables-and-columns/index.mdx b/content/04-guides/01-database-workflows/08-renaming-tables-and-columns/index.mdx index e9a6ec135a..a8743d562d 100644 --- a/content/04-guides/01-database-workflows/08-renaming-tables-and-columns/index.mdx +++ b/content/04-guides/01-database-workflows/08-renaming-tables-and-columns/index.mdx @@ -1,4 +1,4 @@ --- -title: 'Renaming tables and columns' +title: 'Renaming (e.g. tables)' metaTitle: '' --- From a49a31063d7bee144649fa8236a9d0661b79af2b Mon Sep 17 00:00:00 2001 From: Nilu Date: Thu, 26 Mar 2020 18:31:30 +0100 Subject: [PATCH 08/76] Tech switcher --- content/01-getting-started/04-example.mdx | 47 ++++++++ package.json | 1 + src/components/customMdx/code.tsx | 6 +- src/components/customMdx/index.tsx | 29 +---- src/components/customMdx/switchTech.tsx | 23 ++++ src/components/select.tsx | 132 ++++++++++++++++++++++ src/components/sidebar/treeNode.tsx | 3 +- src/components/techSwitcher.tsx | 94 +++++++++++++++ src/components/topSection.tsx | 78 +++++++++++-- src/icons/technologies/Flow.tsx | 27 +++++ src/icons/technologies/Go.tsx | 40 +++++++ src/icons/technologies/JS.tsx | 22 ++++ src/icons/technologies/MongoDB.tsx | 33 ++++++ src/icons/technologies/MySQL.tsx | 21 ++++ src/icons/technologies/NodeJS.tsx | 12 ++ src/icons/technologies/PostgreSQL.tsx | 46 ++++++++ src/icons/technologies/Typescript.tsx | 14 +++ src/interfaces/Article.interface.ts | 2 + src/layouts/articleLayout.tsx | 12 +- yarn.lock | 17 ++- 20 files changed, 617 insertions(+), 42 deletions(-) create mode 100644 content/01-getting-started/04-example.mdx create mode 100644 src/components/customMdx/switchTech.tsx create mode 100644 src/components/select.tsx create mode 100644 src/components/techSwitcher.tsx create mode 100644 src/icons/technologies/Flow.tsx create mode 100644 src/icons/technologies/Go.tsx create mode 100644 src/icons/technologies/JS.tsx create mode 100644 src/icons/technologies/MongoDB.tsx create mode 100644 src/icons/technologies/MySQL.tsx create mode 100644 src/icons/technologies/NodeJS.tsx create mode 100644 src/icons/technologies/PostgreSQL.tsx create mode 100644 src/icons/technologies/Typescript.tsx diff --git a/content/01-getting-started/04-example.mdx b/content/01-getting-started/04-example.mdx new file mode 100644 index 0000000000..98b0d21e16 --- /dev/null +++ b/content/01-getting-started/04-example.mdx @@ -0,0 +1,47 @@ +--- +title: 'Example' +metaTitle: '' +metaDescription: '' +langSwitcher: true +dbSwitcher: true +--- + + +## Overview + +This page won't be shown in sidebar. For now, h2 tags cannot be written inside `SwitchTech` block. But still can include headings using `

,

` tags and not using `### headings`. +`

` tags wont be shown in TOC yet. + + + +

Node Mysql

+ +```js +js +psql -h localhost -d hello-prisma -U janedoe -f schema.sql +``` + + +
+ + + +

Go Mysql

+ +```go +go +psql -h localhost -d hello-prisma -U janedoe -f schema.sql +``` + +
+ + + +

TS Mongodb

+ +```ts +ts +psql -h localhost -d hello-prisma -U janedoe -f schema.sql +``` + +
\ No newline at end of file diff --git a/package.json b/package.json index e5b0d8e41b..e79343c996 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "@mdx-js/react": "^1.5.5", "@philpl/buble": "^0.19.7", "babel-plugin-styled-components": "^1.10.0", + "downshift": "^5.0.5", "gatsby": "^2.1.31", "gatsby-image": "^2.0.33", "gatsby-plugin-manifest": "^2.0.24", diff --git a/src/components/customMdx/code.tsx b/src/components/customMdx/code.tsx index 3eee865817..1298f75c96 100644 --- a/src/components/customMdx/code.tsx +++ b/src/components/customMdx/code.tsx @@ -7,14 +7,14 @@ interface CodeProps { type CodeBlockProps = CodeProps & React.ReactNode; -const CodeBlock = ({ languages, children, ...props }: CodeBlockProps) => { +const CodeBlock = ({ languages, children }: CodeBlockProps) => { const [activeIndex, setActiveIndex] = React.useState(0); const child: any = React.Children.toArray(children)[activeIndex]; const code = child && child.props && child.props.children; return ( - {languages && Array.isArray(languages) && ( + {/* {languages && Array.isArray(languages) && ( {languages.map((lang, index) => { const setCurrentActive = () => setActiveIndex(index); @@ -30,7 +30,7 @@ const CodeBlock = ({ languages, children, ...props }: CodeBlockProps) => { ); })} - )} + )} */} {code} ); diff --git a/src/components/customMdx/index.tsx b/src/components/customMdx/index.tsx index 5fb3265ee1..7a500a8393 100644 --- a/src/components/customMdx/index.tsx +++ b/src/components/customMdx/index.tsx @@ -1,5 +1,6 @@ import React from 'react'; import CodeBlock from './code'; +import SwitchTech from './switchTech'; import Pre from './pre'; import makeHeading from './headings'; @@ -10,36 +11,12 @@ export default { h4: (props: any) => makeHeading('h4')({ ...props }), h5: (props: any) => makeHeading('h5')({ ...props }), h6: (props: any) => makeHeading('h6')({ ...props }), - // h1: (props: any) => ( - //

- // ), - // h2: (props: any) => { - // console.log(props) - // const text = stringify(props.children); - // const id = slug(text); - // return( - //

- // )}, - // h3: (props: any) => ( - //

- // ), - // h4: (props: any) => ( - //

- // ), - // h5: (props: any) => ( - //

- // ), - // h6: (props: any) => ( - //
- // ), p: (props: any) =>

, ul: (props: any) =>

    , CodeBlock, + SwitchTech, pre: Pre, - // a: AnchorTag, - // TODO add `img` // TODO add `blockquote` - // TODO add `ul` - // TODO add `li` // TODO add `table` + // TODO add `Collapsible element` }; diff --git a/src/components/customMdx/switchTech.tsx b/src/components/customMdx/switchTech.tsx new file mode 100644 index 0000000000..cf00972f1d --- /dev/null +++ b/src/components/customMdx/switchTech.tsx @@ -0,0 +1,23 @@ +import React from 'react'; +import styled from 'styled-components'; + +interface CodeProps { + technologies?: string[]; +} + +type CodeBlockProps = CodeProps & React.ReactNode; + +const SwitchTech = ({ technologies, children }: CodeBlockProps) => ( + {children} +); + +export default SwitchTech; + +const SwitchWrapper = styled.section` + display: none; + margin-top: 2rem; + position: relative; + &.show { + display: block; + } +`; diff --git a/src/components/select.tsx b/src/components/select.tsx new file mode 100644 index 0000000000..62e33ca344 --- /dev/null +++ b/src/components/select.tsx @@ -0,0 +1,132 @@ +import React from 'react'; +import styled from 'styled-components'; +import Downshift from 'downshift'; +import ArrowDown from '../icons/ArrowDown'; + +interface SelectProps { + items: any[]; + renderItem: (item: any) => any; + onChange: (item: any) => void; + selectedItem: any; + itemToString: (item: any) => string; + width?: number; + top?: number; + selectPlaceholder?: string; +} + +const SelectComponent = (props: SelectProps) => { + const { selectedItem, renderItem, onChange, itemToString, items, top, selectPlaceholder } = props; + const width = props.width || 160; + return ( + + {({ + isOpen, + getToggleButtonProps, + getItemProps, + highlightedIndex, + selectedItem: dsSelectedItem, + }: any) => { + const firstItem = isOpen && selectPlaceholder ? null : selectedItem; + + return ( +
    + +
    + {isOpen && ( + + {items.map((item: any, index: number) => ( + + {renderItem(item)} + + ))} + + )} +
    +
    + ); + }} +
    + ); +}; + +export default SelectComponent; + +const Select = styled.button` + background: #ffffff; + border: 1px solid #e2e8f0; + box-sizing: border-box; + border-radius: 5px; + padding: 10px; + width: ${(p: any) => p.width}px; + display: flex; + align-items: center; + justify-content: space-between; + min-height: 40px; + color: #1a202c; + font-size: 1rem; + font-family: 'Open Sans'; + &:focus { + outline: 0; + } + &.open { + border-bottom-left-radius: 0px; + border-bottom-right-radius: 0px; + } + &:hover { + cursor: pointer; + } +` as any; + +const Dropdown = styled.div` + background: white; + transform: translateY(14px); + border-bottom-left-radius: 6px; + border-bottom-right-radius: 6px; + color: grey; + box-shadow: 0px 2px 4px rgba(8, 35, 51, 0.05); +`; + +const Item = styled.div` + padding: 8px 14px; + color: grey; + background: 'white'; + cursor: pointer; + display: flex; + align-items: center; + > * + * { + margin-left: 12px; + } +`; + +const Left = styled.div` + display: flex; + align-items: center; + width: 100%; + margin-right: 16px; + > * + * { + margin-left: 12px; + } +`; + +const Muted = styled.div` + opacity: 0.5; +`; diff --git a/src/components/sidebar/treeNode.tsx b/src/components/sidebar/treeNode.tsx index ebb5fbff01..f09ce00a12 100644 --- a/src/components/sidebar/treeNode.tsx +++ b/src/components/sidebar/treeNode.tsx @@ -130,10 +130,9 @@ const TreeNode = ({ items.map((item: any) => (item.lastLevel = true)); hasBorder = true; } - return ( - {title && label !== 'index' && ( + {title && label !== 'index' && url !== '/01-getting-started/04-example' && ( void; +} + +interface TechItem { + technology: keyof typeof icons; +} + +const icons = { + node: , + typescript: , + mysql: , + postgres: , + mongodb: , + go: , + flow: , +}; + +const technologyTypes = { + languages: ['node', 'typescript', 'flow', 'go'], + databases: ['mysql', 'postgres', 'mongodb'], +}; + +export const technologyNames = { + node: 'JavaScript', + typescript: 'TypeScript', + flow: 'Flow', + mysql: 'MySQL', + postgres: 'PostgreSQL', + mongodb: 'MongoDB', + go: 'Go', +}; + +const TechnologySwitch = ({ type, onChangeTech }: TechSwitchProps) => { + const langDefault = { technology: 'node' }; + const dbDefault = { technology: 'mysql' }; + const defaultItem = type === 'lang' ? langDefault : dbDefault; + + const [selectedItem, setSelectedItem] = React.useState(defaultItem); + + const renderItem = (item: TechItem) => { + return ( + <> + {icons[item.technology]} + {technologyNames[item.technology]} + + ); + }; + + const itemToString = (item: TechItem) => item && item.technology; + + const handleChange = (item: TechItem) => { + setSelectedItem(item); + onChangeTech(item); + }; + + const items = + type === 'lang' + ? technologyTypes.languages.map((lang: any) => ({ technology: lang })) + : technologyTypes.databases.map((db: any) => ({ technology: db })); + + return ( + + + + ); +}; + +const Container = styled.div` + margin: 16px 1rem 24px 0; +`; + +export default TechnologySwitch; diff --git a/src/components/topSection.tsx b/src/components/topSection.tsx index ee1d2299de..5661438761 100644 --- a/src/components/topSection.tsx +++ b/src/components/topSection.tsx @@ -1,6 +1,15 @@ import * as React from 'react'; import styled from 'styled-components'; import TOC from './toc'; +import TechnologySwitch from './techSwitcher'; + +const TopSectionWrapper = styled.div` + position: relative; + hr.bigger-margin { + margin-top: 3.5rem; + margin-bottom: 4rem; + } +`; const BreadcrumbTitle = styled.h4` color: #718096; @@ -19,13 +28,66 @@ const MainTitle = styled.h1` margin-top: 4px; `; -const TopSection = ({ location, title, parentTitle, indexPage }: any) => ( -
    - {!indexPage && {parentTitle}} - {title} - {!indexPage &&
    } - {!indexPage && } -
    -); +const SwitcherWrapper = styled.div` + display: flex; + position: absolute; + top: 78px; +`; + +const TopSection = ({ location, title, parentTitle, indexPage, langSwitcher, dbSwitcher }: any) => { + const [langSelected, setLangSelected] = React.useState('node'); + const [dbSelected, setDbSelected] = React.useState('mysql'); + + const techChanged = (item: any, type: string) => { + const elements = document.querySelectorAll('[id^="techswitch"]'); + elements.forEach((element: any) => element.classList.remove('show')); + const elemToShow = [].slice.call(elements).filter((elm: any) => { + if (type === 'lang') { + return dbSwitcher + ? elm.id.includes(`-${item.technology}`) && elm.id.includes(`-${dbSelected}`) + : elm.id.includes(`-${item.technology}`); + } else if (type === 'db') { + return langSwitcher + ? elm.id.includes(`-${item.technology}`) && elm.id.includes(`-${langSelected}`) + : elm.id.includes(`-${item.technology}`); + } + }); + elemToShow && elemToShow.forEach((eShow: any) => eShow.classList.add('show')); + }; + + const langChanged = (item: any) => { + techChanged(item, 'lang'); + setLangSelected(item.technology); + }; + + const dbChanged = (item: any) => { + techChanged(item, 'db'); + setDbSelected(item.technology); + }; + + React.useEffect(() => { + if (langSwitcher && !dbSwitcher) { + langChanged({ technology: langSelected }); + } else if (dbSwitcher && !langSwitcher) { + dbChanged({ technology: dbSelected }); + } else if (dbSwitcher && langSwitcher) { + langChanged({ technology: langSelected }); + dbChanged({ technology: dbSelected }); + } + }); + + return ( + + {!indexPage && {parentTitle}} + {title} + {!indexPage &&
    } + + {langSwitcher && } + {dbSwitcher && } + + {!indexPage && } +
    + ); +}; export default TopSection; diff --git a/src/icons/technologies/Flow.tsx b/src/icons/technologies/Flow.tsx new file mode 100644 index 0000000000..ac23130ced --- /dev/null +++ b/src/icons/technologies/Flow.tsx @@ -0,0 +1,27 @@ +import React from 'react'; + +export default () => ( + + + + + + + + + + + + +); diff --git a/src/icons/technologies/Go.tsx b/src/icons/technologies/Go.tsx new file mode 100644 index 0000000000..07ebd9eded --- /dev/null +++ b/src/icons/technologies/Go.tsx @@ -0,0 +1,40 @@ +import React from 'react'; + +export default () => ( + + + + + + + + + + + + + + +); diff --git a/src/icons/technologies/JS.tsx b/src/icons/technologies/JS.tsx new file mode 100644 index 0000000000..13f7ef0793 --- /dev/null +++ b/src/icons/technologies/JS.tsx @@ -0,0 +1,22 @@ +import React from 'react'; + +export default () => ( + + + + + + +); diff --git a/src/icons/technologies/MongoDB.tsx b/src/icons/technologies/MongoDB.tsx new file mode 100644 index 0000000000..ed0144352b --- /dev/null +++ b/src/icons/technologies/MongoDB.tsx @@ -0,0 +1,33 @@ +import React from 'react'; + +export default () => ( + + + + + + + + + + + + + +); diff --git a/src/icons/technologies/MySQL.tsx b/src/icons/technologies/MySQL.tsx new file mode 100644 index 0000000000..5a033cb915 --- /dev/null +++ b/src/icons/technologies/MySQL.tsx @@ -0,0 +1,21 @@ +import React from 'react'; + +export default () => ( + + + + + +); diff --git a/src/icons/technologies/NodeJS.tsx b/src/icons/technologies/NodeJS.tsx new file mode 100644 index 0000000000..f128f99351 --- /dev/null +++ b/src/icons/technologies/NodeJS.tsx @@ -0,0 +1,12 @@ +import React from 'react'; + +export const NodeJS = () => ( + + + + +); diff --git a/src/icons/technologies/PostgreSQL.tsx b/src/icons/technologies/PostgreSQL.tsx new file mode 100644 index 0000000000..332ea396a4 --- /dev/null +++ b/src/icons/technologies/PostgreSQL.tsx @@ -0,0 +1,46 @@ +import React from 'react'; + +export default () => ( + + + + + + + + + + +); diff --git a/src/icons/technologies/Typescript.tsx b/src/icons/technologies/Typescript.tsx new file mode 100644 index 0000000000..3524d8e68f --- /dev/null +++ b/src/icons/technologies/Typescript.tsx @@ -0,0 +1,14 @@ +import React from 'react'; + +export const Typescript = () => ( + + + + +); diff --git a/src/interfaces/Article.interface.ts b/src/interfaces/Article.interface.ts index 74cb07776f..4e19adb13f 100644 --- a/src/interfaces/Article.interface.ts +++ b/src/interfaces/Article.interface.ts @@ -16,6 +16,8 @@ export interface ArticleData { title: string; metaTitle?: string; metaDescription?: string; + langSwitcher?: boolean; + dbSwitcher?: boolean; }; }; allMdx: AllEdges; diff --git a/src/layouts/articleLayout.tsx b/src/layouts/articleLayout.tsx index dc44e808db..4ef0e0f47b 100644 --- a/src/layouts/articleLayout.tsx +++ b/src/layouts/articleLayout.tsx @@ -18,7 +18,7 @@ const ArticleLayout = ({ data, ...props }: ArticleLayoutProps) => { allMdx, mdx: { fields: { slug }, - frontmatter: { title, metaTitle, metaDescription }, + frontmatter: { title, metaTitle, metaDescription, langSwitcher, dbSwitcher }, body, }, } = data; @@ -53,7 +53,13 @@ const ArticleLayout = ({ data, ...props }: ArticleLayoutProps) => {
    - +
    {body} @@ -77,6 +83,8 @@ export const query = graphql` title metaTitle metaDescription + langSwitcher + dbSwitcher } } allMdx { diff --git a/yarn.lock b/yarn.lock index 15161c07d8..213bfa7b91 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3798,6 +3798,11 @@ compression@^1.7.4: safe-buffer "5.1.2" vary "~1.1.2" +compute-scroll-into-view@^1.0.9: + version "1.0.13" + resolved "https://registry.yarnpkg.com/compute-scroll-into-view/-/compute-scroll-into-view-1.0.13.tgz#be1b1663b0e3f56cd5f7713082549f562a3477e2" + integrity sha512-o+w9w7A98aAFi/GjK8cxSV+CdASuPa2rR5UWs3+yHkJzWqaKoBEufFNWYaXInCSmUfDCVhesG+v9MTWqOjsxFg== + concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -4979,6 +4984,16 @@ download@^7.1.0: p-event "^2.1.0" pify "^3.0.0" +downshift@^5.0.5: + version "5.0.5" + resolved "https://registry.yarnpkg.com/downshift/-/downshift-5.0.5.tgz#1cc90dc09ae62998ce28a4ce457e0f1cdd0bfcfa" + integrity sha512-V1idov3Rkvz1YWA1K67aIx51EgokIDvep4x6KmU7HhsayI8DvTEZBeH4O92zeFVGximKujRO7ChBzBAf4PKWFA== + dependencies: + "@babel/runtime" "^7.4.5" + compute-scroll-into-view "^1.0.9" + prop-types "^15.7.2" + react-is "^16.9.0" + duplexer3@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2" @@ -12157,7 +12172,7 @@ react-hot-loader@^4.12.20: shallowequal "^1.1.0" source-map "^0.7.3" -react-is@^16.6.0, react-is@^16.7.0, react-is@^16.8.1, react-is@^16.8.4: +react-is@^16.6.0, react-is@^16.7.0, react-is@^16.8.1, react-is@^16.8.4, react-is@^16.9.0: version "16.13.1" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== From c9a8c8dffa47026c276dda9dbc75dff502db0622 Mon Sep 17 00:00:00 2001 From: Nilu Date: Thu, 26 Mar 2020 19:04:35 +0100 Subject: [PATCH 09/76] Select route --- src/components/techSwitcher.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/techSwitcher.tsx b/src/components/techSwitcher.tsx index 62075a18a8..5e3fe6dbc1 100644 --- a/src/components/techSwitcher.tsx +++ b/src/components/techSwitcher.tsx @@ -1,7 +1,7 @@ import React from 'react'; import styled from 'styled-components'; import { Typescript } from '../icons/technologies/Typescript'; -import SelectComponent from './Select'; +import SelectComponent from './select'; import PostgreSQL from '../icons/technologies/PostgreSQL'; import MySQL from '../icons/technologies/MySQL'; import MongoDB from '../icons/technologies/MongoDB'; From 913817ce7f97e3966c27fcb1cd85adb7db665b8c Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 07:23:41 +0100 Subject: [PATCH 10/76] ajdust sidenav --- README.md | 79 ++++++++++++++++++ .../02-understand-prisma/01-introduction.mdx | 78 +---------------- .../02-understand-prisma/02-why-prisma.mdx | 83 +++++++++++++++++++ .../{02-features.mdx => 03-features.mdx} | 0 .../01-rest.md | 0 .../02-graphql.md | 0 .../index.mdx | 0 ...sma-an-orm.mdx => 05-is-prisma-an-orm.mdx} | 0 ...data-modeling.mdx => 06-data-modeling.mdx} | 0 ...-hood.mdx => 07-prisma-under-the-hood.mdx} | 0 10 files changed, 163 insertions(+), 77 deletions(-) create mode 100644 content/02-understand-prisma/02-why-prisma.mdx rename content/02-understand-prisma/{02-features.mdx => 03-features.mdx} (100%) rename content/02-understand-prisma/{03-prisma-in-your-stack => 04-prisma-in-your-stack}/01-rest.md (100%) rename content/02-understand-prisma/{03-prisma-in-your-stack => 04-prisma-in-your-stack}/02-graphql.md (100%) rename content/02-understand-prisma/{03-prisma-in-your-stack => 04-prisma-in-your-stack}/index.mdx (100%) rename content/02-understand-prisma/{04-is-prisma-an-orm.mdx => 05-is-prisma-an-orm.mdx} (100%) rename content/02-understand-prisma/{05-data-modeling.mdx => 06-data-modeling.mdx} (100%) rename content/02-understand-prisma/{06-prisma-under-the-hood.mdx => 07-prisma-under-the-hood.mdx} (100%) diff --git a/README.md b/README.md index 7e9d4a3c70..40e339b4dc 100644 --- a/README.md +++ b/README.md @@ -45,3 +45,82 @@ Open `config.js` for available config options for `gatsby`, `header`, `footer` a - `title` - Title of the website in main page - `description` - Description of the website - `keywords` - Keywords of the website for SEO + +## Inserting, moving and deleting files + +All files/folders in the context are prefixed with a _position_ which indicates the order in which they appear in the sidenav on the docs website. This makes it cumbersome to insert, move and delete files because the positions of a number of other files (if not all) in the same folder might need to be adjusted. Thanks to [Luca Steeb](https://github.com/steebchen/), you can perform these operations with a dedicated CLI called [`mdtool`](https://gist.githubusercontent.com/steebchen/bd085ebde1fcf4242e3fdd0df4d202a6/raw/c04e3d262eb6a302a9fab98f6428fec9329681e2/mdtool). + +### Install + +```bash +wget https://gist.githubusercontent.com/steebchen/bd085ebde1fcf4242e3fdd0df4d202a6/raw/c04e3d262eb6a302a9fab98f6428fec9329681e2/mdtool -qO /usr/local/bin/mdtool +chmod +x /usr/local/bin/mdtool +``` + +### Usage + +#### Overview + +``` +mdtool insert 3 +mdtool swap A B +mdtool move A B +mdtool remove 4 +``` + +#### `mdtool insert` + +Make place for a new file at given index and increment all numbers by one after that index: + +``` +$ mdtool insert INDEX + +# e.g.: +$ mdtool insert 2 + +# Result: for files 01-a, 02-b, 03-c, and 04-d; 03-c is renamed to 04-c and 04-d is renamed to 05-d so you can create a new file at index 2 +``` + +#### `mdtool swap` + +Swap two files; specify both filenames (prefix numbers get automatically adjusted): + +``` +$ mdtool swap FILENAME1 FILENAME2 + +# e.g.: +$ mdtool swap 03-file1.mdx 07-file2.mdx + +# Result: Files are now named: 03-file2.mdx 07-file1.mdx +``` + +#### `mdtool move` + +Move a given file to another given index + +``` +$ mdtool move FILENAME INDEX + +# e.g.: +$ mdtool move 05-file.mdx 2 + +# Result: 05-file.mdx is move to 02-file.mdx, plus previous files 02-*, 03-*, 04-* are incremented +``` + + +#### `mdtool swap` + +Shift all other items by -1 at a given index: + +``` +$ mdtool remove INDEX + +# e.g.: +$ mdtool remove 2 + +# Result: 01-a, 02-b, 03-c, 04-d becomes 01-a, 02-b, 02-c, 03-d; 02-b is supposed to be manually deleted +``` + +#### Thanks Luca + +![](https://imgur.com/LJ0FGHk.png) \ No newline at end of file diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 6b4d572948..2abc0000b5 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -This page gives a high-level overview of **what** Prisma is, **why** you want to use and **how** it works. +This page gives a high-level overview of what Prisma is and how it works. If you have want to learn more about the motivation of Prisma, check out the [Why Prisma?](./why-prisma) page. ## What @@ -20,82 +20,6 @@ Prisma Client can be used in _any_ Node.js or TypeScript application. This can b Every project that uses Prisma is further based on a [Prisma schema file]() which contains your database connection, client generators and a representation of your database schema as a delarative Prisma [data model](). -## Why - -Working with relational databases is a major bottleneck in application development. Debugging SQL queries or complex ORM objects often consume hours of development time. - -Prisma makes it easy for developers to reason about their database queries by providing a clean and type-safe API for submitting database queries which returns _plain old JavaScript objects_. - -### Problems with SQL, ORMs and other database tools - -The main problem with the database tools that currently exist in the Node.js and TypeScript ecosystem is that they require a major tradeoff between _productvity_ and _control_. - -![](https://imgur.com/juPfyZS.png) - -#### Raw SQL: Full control, low productivity - -With raw SQL (e.g. using the native [`pg`](https://node-postgres.com/) or [`mysql`](https://github.com/mysqljs/mysql#readme) Node.js database drivers) you have full control over your database operations. However, productivity suffers as sending plain SQL strings to the database is cumbersome and comes with a lot of overhead (manual connection handling, repetetive boilerplate, ...). - -Another major issue with this approach is that you don't get any type safety for your query results. Of course, you can type the results manually but this is a huge amount of work and requires major refactorings each time you change your database schema or queries to keep the typings in sync. - -Furthermore, submitting SQL queries as plain strings means you don't get any autocompletion in your editors. - -#### SQL query builders: High control, medium productivity - -A common solution that retains a high level of control and provides better productivity is to use a SQL query builder (e.g. [knex.js]()). These sort of tools provide a programmatic abstraction to construct SQL queries. - -The biggest drawback with SQL query builders is that application developers still need to think about their data in terms of SQL. This incurs a cognitive and practical cost of translating relational data into objects. Another issue is that it's too easy to shoot yourself in the foot if you don't know exactly what you're doing in your SQL queries. - -#### ORMs: Less control, better productivity - -ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. You can then read and write data by calling methods on the instances of your model classes. - -This is way more convenient and comes closer to the mental model developers have when thinking about their data. So, what's the catch? - -> ORM represents a quagmire which starts well, gets more complicated as time passes, and before long entraps its users in a commitment that has no clear demarcation point, no clear win conditions, and no clear exit strategy. -> -> [The Vietname of Computer Science, Ted Neward (2006)](http://blogs.tedneward.com/post/the-vietnam-of-computer-science/) - -As an application developer, the mental model you have for your data is that of an _object_. The mental model for data in SQL on the other hand are _tables_. - -The divide between these two different representations of data is often referred to as the [object-relational impedance mismatch](). The object-relational impedance mismatch also is a major reason why many developers don't like working with traditional ORMs. - -As an example, consider how data is organized and relationships are handled with each apprach: - -- **Relational databases**: Data is typically normalized (flat) and uses foreign keys to link across entities. The entities then need to be JOINed to manifest the actual relationships. -- **Object-oriented**: Objects can be deeply nested structures where you can traverse relationships simply by using dot notation. - -This alludes to one of the major pitfalls with ORMs: While they make it _seem_ that you can simply traverse relationships using familiar dot notation, under the hood the ORM generates SQL JOINs which are expensive and have the potential to drastically slow down your application (one symptom of this is the [n+1 problem](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping)). - -To conlude: The appeal of ORMs is the premise of abstracting away the relational model and thinking about your data purely in terms of objects. While the premise is great, it's based on the wrong assumption that relational data can easily be mapped to objects which leads to lots of complications and pitfalls. - -### Application developers should care about data โ€“ not SQL - -Despite developed in the 1970s(!), SQL has stood the test of time in an impressive manner. However, with the advancement and modernization of developers tools, it's worth asking if SQL really the best abstraction for application developers to work with? - -After all, **developers should only care about the _data_ they need to implement a feature** and not spend time figuring out complicated SQL queries or massaging query results to fit their needs. - -There's another argument to be made against SQL in application development. The power of SQL can be a blessing if you know exactly what you're doing, but its complexity can be a curse. There are a lot of [antipatterns](http://img.bigdatabugs.com/SQL%20Antipatterns@www.bigDataBugs.com.pdf) and pitfalls that even experienced SQL users struggle to anticipate, often at the cost of performance and hours of debugging time. - -Developers should be able to ask for the data they need instead of having to worry about "doing the right thing" in their SQL queries. They should be using an abstraction that makes the right decisions for them. This can mean that the abstraction imposes certain "healthy" constraints that prevent developers from making mistakes. - -### Prisma makes developers productive - -Prisma's main goal is to make application developers more productive when working with databases. Here are a few examples how Prima achieves this: - -- **Thinking in objects** instead of mapping relational data -- **Queries not classes** to avoid complex model objects -- **Single source of truth** for database and application models -- **Healthy constraints** that prevent common pitfalls and antipatterns -- **An abstraction that make the right thing easy** ("pit of success") -- **Type-safe database queries** that can be validated at compile time -- **Less boilerplate** so developers can focus on the important parts of their app -- **Auto-completion in code editors** instead of needing to look up documentation - -Considering the tradeoff between productivity and control again, this is how Prisma fits in: - -![](https://imgur.com/JkQHIKl.png) - ## How Prisma offers two main workflows which depend on _how_ you're performing _schema migrations_ (e.g.adding new or altering existing tables): diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx new file mode 100644 index 0000000000..b667aadf16 --- /dev/null +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -0,0 +1,83 @@ +--- +title: 'Why Prisma?' +metaTitle: '' +metaDescription: '' +--- + +## Overview + +On this page, you'll learn about the motivation for Prisma and how it compares to ther database tools like ORMs and SQL query builders. + +Working with relational databases is a major bottleneck in application development. Debugging SQL queries or complex ORM objects often consume hours of development time. + +Prisma makes it easy for developers to reason about their database queries by providing a clean and type-safe API for submitting database queries which returns _plain old JavaScript objects_. + +## Problems with SQL, ORMs and other database tools + +The main problem with the database tools that currently exist in the Node.js and TypeScript ecosystem is that they require a major tradeoff between _productvity_ and _control_. + +![](https://imgur.com/juPfyZS.png) + +### Raw SQL: Full control, low productivity + +With raw SQL (e.g. using the native [`pg`](https://node-postgres.com/) or [`mysql`](https://github.com/mysqljs/mysql#readme) Node.js database drivers) you have full control over your database operations. However, productivity suffers as sending plain SQL strings to the database is cumbersome and comes with a lot of overhead (manual connection handling, repetetive boilerplate, ...). + +Another major issue with this approach is that you don't get any type safety for your query results. Of course, you can type the results manually but this is a huge amount of work and requires major refactorings each time you change your database schema or queries to keep the typings in sync. + +Furthermore, submitting SQL queries as plain strings means you don't get any autocompletion in your editors. + +### SQL query builders: High control, medium productivity + +A common solution that retains a high level of control and provides better productivity is to use a SQL query builder (e.g. [knex.js]()). These sort of tools provide a programmatic abstraction to construct SQL queries. + +The biggest drawback with SQL query builders is that application developers still need to think about their data in terms of SQL. This incurs a cognitive and practical cost of translating relational data into objects. Another issue is that it's too easy to shoot yourself in the foot if you don't know exactly what you're doing in your SQL queries. + +### ORMs: Less control, better productivity + +ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. You can then read and write data by calling methods on the instances of your model classes. + +This is way more convenient and comes closer to the mental model developers have when thinking about their data. So, what's the catch? + +> ORM represents a quagmire which starts well, gets more complicated as time passes, and before long entraps its users in a commitment that has no clear demarcation point, no clear win conditions, and no clear exit strategy. +> +> [The Vietname of Computer Science, Ted Neward (2006)](http://blogs.tedneward.com/post/the-vietnam-of-computer-science/) + +As an application developer, the mental model you have for your data is that of an _object_. The mental model for data in SQL on the other hand are _tables_. + +The divide between these two different representations of data is often referred to as the [object-relational impedance mismatch](). The object-relational impedance mismatch also is a major reason why many developers don't like working with traditional ORMs. + +As an example, consider how data is organized and relationships are handled with each apprach: + +- **Relational databases**: Data is typically normalized (flat) and uses foreign keys to link across entities. The entities then need to be JOINed to manifest the actual relationships. +- **Object-oriented**: Objects can be deeply nested structures where you can traverse relationships simply by using dot notation. + +This alludes to one of the major pitfalls with ORMs: While they make it _seem_ that you can simply traverse relationships using familiar dot notation, under the hood the ORM generates SQL JOINs which are expensive and have the potential to drastically slow down your application (one symptom of this is the [n+1 problem](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping)). + +To conlude: The appeal of ORMs is the premise of abstracting away the relational model and thinking about your data purely in terms of objects. While the premise is great, it's based on the wrong assumption that relational data can easily be mapped to objects which leads to lots of complications and pitfalls. + +## Application developers should care about data โ€“ not SQL + +Despite developed in the 1970s(!), SQL has stood the test of time in an impressive manner. However, with the advancement and modernization of developers tools, it's worth asking if SQL really the best abstraction for application developers to work with? + +After all, **developers should only care about the _data_ they need to implement a feature** and not spend time figuring out complicated SQL queries or massaging query results to fit their needs. + +There's another argument to be made against SQL in application development. The power of SQL can be a blessing if you know exactly what you're doing, but its complexity can be a curse. There are a lot of [antipatterns](http://img.bigdatabugs.com/SQL%20Antipatterns@www.bigDataBugs.com.pdf) and pitfalls that even experienced SQL users struggle to anticipate, often at the cost of performance and hours of debugging time. + +Developers should be able to ask for the data they need instead of having to worry about "doing the right thing" in their SQL queries. They should be using an abstraction that makes the right decisions for them. This can mean that the abstraction imposes certain "healthy" constraints that prevent developers from making mistakes. + +## Prisma makes developers productive + +Prisma's main goal is to make application developers more productive when working with databases. Here are a few examples how Prima achieves this: + +- **Thinking in objects** instead of mapping relational data +- **Queries not classes** to avoid complex model objects +- **Single source of truth** for database and application models +- **Healthy constraints** that prevent common pitfalls and antipatterns +- **An abstraction that make the right thing easy** ("pit of success") +- **Type-safe database queries** that can be validated at compile time +- **Less boilerplate** so developers can focus on the important parts of their app +- **Auto-completion in code editors** instead of needing to look up documentation + +Considering the tradeoff between productivity and control again, this is how Prisma fits in: + +![](https://imgur.com/JkQHIKl.png) diff --git a/content/02-understand-prisma/02-features.mdx b/content/02-understand-prisma/03-features.mdx similarity index 100% rename from content/02-understand-prisma/02-features.mdx rename to content/02-understand-prisma/03-features.mdx diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/04-prisma-in-your-stack/01-rest.md similarity index 100% rename from content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md rename to content/02-understand-prisma/04-prisma-in-your-stack/01-rest.md diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md b/content/02-understand-prisma/04-prisma-in-your-stack/02-graphql.md similarity index 100% rename from content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md rename to content/02-understand-prisma/04-prisma-in-your-stack/02-graphql.md diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/index.mdx b/content/02-understand-prisma/04-prisma-in-your-stack/index.mdx similarity index 100% rename from content/02-understand-prisma/03-prisma-in-your-stack/index.mdx rename to content/02-understand-prisma/04-prisma-in-your-stack/index.mdx diff --git a/content/02-understand-prisma/04-is-prisma-an-orm.mdx b/content/02-understand-prisma/05-is-prisma-an-orm.mdx similarity index 100% rename from content/02-understand-prisma/04-is-prisma-an-orm.mdx rename to content/02-understand-prisma/05-is-prisma-an-orm.mdx diff --git a/content/02-understand-prisma/05-data-modeling.mdx b/content/02-understand-prisma/06-data-modeling.mdx similarity index 100% rename from content/02-understand-prisma/05-data-modeling.mdx rename to content/02-understand-prisma/06-data-modeling.mdx diff --git a/content/02-understand-prisma/06-prisma-under-the-hood.mdx b/content/02-understand-prisma/07-prisma-under-the-hood.mdx similarity index 100% rename from content/02-understand-prisma/06-prisma-under-the-hood.mdx rename to content/02-understand-prisma/07-prisma-under-the-hood.mdx From 0549b26fb8a779f19804c88bc847ad588e564e77 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 08:09:07 +0100 Subject: [PATCH 11/76] ajdust sidenav --- .../02-understand-prisma/01-introduction.mdx | 114 +++++++++++++++--- .../02-understand-prisma/02-why-prisma.mdx | 8 +- .../01-rest.md | 0 .../02-graphql.md | 0 .../index.mdx | 0 ...sma-an-orm.mdx => 04-is-prisma-an-orm.mdx} | 0 ...data-modeling.mdx => 05-data-modeling.mdx} | 0 ...-hood.mdx => 06-prisma-under-the-hood.mdx} | 0 ...le-bundlers.mdx => 18-module-bundlers.mdx} | 2 +- .../02-database-connectors/01-features.mdx} | 4 + .../{01-postgresql.mdx => 02-postgresql.mdx} | 0 .../{02-mysql.mdx => 03-mysql.mdx} | 0 .../{03-sqlite.mdx => 04-sqlite.mdx} | 0 ...ection-urls.mdx => 05-connection-urls.mdx} | 0 content/05-more/01-about-the-docs.mdx | 6 +- content/05-more/02-style-guide.mdx | 4 + 16 files changed, 116 insertions(+), 22 deletions(-) rename content/02-understand-prisma/{04-prisma-in-your-stack => 03-prisma-in-your-stack}/01-rest.md (100%) rename content/02-understand-prisma/{04-prisma-in-your-stack => 03-prisma-in-your-stack}/02-graphql.md (100%) rename content/02-understand-prisma/{04-prisma-in-your-stack => 03-prisma-in-your-stack}/index.mdx (100%) rename content/02-understand-prisma/{05-is-prisma-an-orm.mdx => 04-is-prisma-an-orm.mdx} (100%) rename content/02-understand-prisma/{06-data-modeling.mdx => 05-data-modeling.mdx} (100%) rename content/02-understand-prisma/{07-prisma-under-the-hood.mdx => 06-prisma-under-the-hood.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{18-usage-with-module-bundlers.mdx => 18-module-bundlers.mdx} (96%) rename content/{02-understand-prisma/03-features.mdx => 03-reference/02-database-connectors/01-features.mdx} (98%) rename content/03-reference/02-database-connectors/{01-postgresql.mdx => 02-postgresql.mdx} (100%) rename content/03-reference/02-database-connectors/{02-mysql.mdx => 03-mysql.mdx} (100%) rename content/03-reference/02-database-connectors/{03-sqlite.mdx => 04-sqlite.mdx} (100%) rename content/03-reference/02-database-connectors/{04-connection-urls.mdx => 05-connection-urls.mdx} (100%) diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 2abc0000b5..b303e8b052 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -6,37 +6,102 @@ metaDescription: '' ## Overview -This page gives a high-level overview of what Prisma is and how it works. If you have want to learn more about the motivation of Prisma, check out the [Why Prisma?](./why-prisma) page. +This page gives a high-level overview of what Prisma is and how it works. -## What +If you want to get started with a _practical introduction_ and learn about the Prisma Client API, head over to the [Quickstart](). + +To learn more about the _motivation_ of Prisma, check out the [Why Prisma?](./why-prisma) page. + +## What is Prisma? Prisma is an [open source]() database toolkit. It mainly consists of the following parts: -- **Prisma Client**: An auto-generated and type-safe query builder for Node.js and TypeScript. -- **Prisma Migrate** (experimental): A declarative schema migration system. -- **Prisma Studio** (experimental): A GUI to view and edit data in your database. +- **Prisma Client**: Auto-generated and type-safe query builder for Node.js & TypeScript +- **Prisma Migrate** (_experimental_): Declarative schema migration system +- **Prisma Studio** (_experimental_): GUI to view and edit data in your database -Prisma Client can be used in _any_ Node.js or TypeScript application. This can be a [REST API](), a [GraphQL API]() a gRPC API or anything else that needs a database. +Prisma Client can be used in _any_ Node.js or TypeScript backend application. This can be a [REST API](), a [GraphQL API]() a gRPC API or anything else that needs a database. -Every project that uses Prisma is further based on a [Prisma schema file]() which contains your database connection, client generators and a representation of your database schema as a delarative Prisma [data model](). +## How does Prisma work? -## How +### The Prisma schema -Prisma offers two main workflows which depend on _how_ you're performing _schema migrations_ (e.g.adding new or altering existing tables): +Every project that use a tool from the Prisma toolkit starts with a [Prisma schema file](). The Prisma schema allows developers to define their _application models_ in an intuitive data modeling language. It also contains the connection to a database and defines a _generator_: -- **SQL migrations and introspection** (recommended) -- **Prisma Migrate** (experimental) +```prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} -> **Note** As long as Prisma Migrate is in an experimental state, the recommended way for using Prisma is with SQL migrations and introspection. Note that you can still use Prisma Migrate in non-critical applications. +generator client { + provider = "prisma-client-js" +} -The typical workflow when using SQL migrations and introspection looks as follows: +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? +} -1. Manually adjust your database schema using SQL -1. (Re-)introspect your database -1. (Re-)generate Prisma Client -1. Use Prisma Client in your application code to access your database +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` -![](https://imgur.com/7BUqpyv.png) +> **Note**: The Prisma schema has powerful data modeling features. For example, it allows you to define [virtual relation fields]() which will make it easier to work with [relations in the Prisma Client API](). In the case above, the `posts` field on `User` is virtual. + +In this schema, you configure three things: + +- **Data source**: Specifies your database connection (via an environment variable) +- **Generator**: Indicates that you want to genenerate Prisma Client +- **Data model**: Defines your application models + +### The Prisma data model + +On this page, the focus is on the data model. You can learn more about [Data sources]() and [Generators]() on the respective docs pages. + +#### Functions of Prisma models + +The data model is a collection of [models](). A model has two major functions: + +- Map to a table in the underlying database +- Provide the foundation for the queries in the Prisma Client API + +#### Getting a data model + +There are two major workflows for "getting" a data model into your Prisma schema: + +- Generate the data model from [introspecting]() a database +- Manually writing the data model and mapping it to the database with [Prisma Migrate]() + +Once the data model is defined, you can [generate Prisma Client]() which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields). + +### Accessing your database with Prisma Client + +#### Generating Prisma Client + +The first step when using Prisma Client is installing its npm package: + +``` +npm install @prisma/client +``` + +Note that the installation of this package invokes the `prisma generate` command which reads your Prisma schema and _generates_ the Prisma Client code. The code will be located in `node_modules/@prisma/client`. After you change your data model, you'll need to manually run `prisma generate` to ensure the code inside `node_modules/@prisma/client` get updated. + +> **Note**: Because the Prisma Client node module contains specific context about _your_ Prisma schema, it's sometimes referred to as a ["smart node module"](). + +#### + + +### Typical Prisma workflows + +#### Prisma Migrate With Prisma Migrate, the workflow looks slightly different: @@ -47,4 +112,17 @@ With Prisma Migrate, the workflow looks slightly different: ![](https://imgur.com/nX0jIo5.png) +#### SQL migrations and introspection + +The typical workflow when using **SQL migrations and introspection** looks as follows: + +1. Manually adjust your database schema using SQL +1. (Re-)introspect your database +1. (Re-)generate Prisma Client +1. Use Prisma Client in your application code to access your database + +![](https://imgur.com/7BUqpyv.png) + + + To dive deeper, please refer to the respective docs page. diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx index b667aadf16..da53e07737 100644 --- a/content/02-understand-prisma/02-why-prisma.mdx +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -34,7 +34,13 @@ The biggest drawback with SQL query builders is that application developers stil ### ORMs: Less control, better productivity -ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. You can then read and write data by calling methods on the instances of your model classes. +ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. + +> "Object relational mappers" (ORMs) exist to bridge the gap between the programmers' friend (the object), and the database's primitive (the relation). The reasons for these differing models are as much cultural as functional: programmers like objects because they encapsulate the state of a single thing in a running program. Databases like relations because they better suit whole-dataset constraints and efficient access patterns for the entire dataset. +> +> [The Troublesome Active Record Pattern, Cal Paterson (2020)](http://calpaterson.com/activerecord.html) + +You can then read and write data by calling methods on the instances of your model classes. This is way more convenient and comes closer to the mental model developers have when thinking about their data. So, what's the catch? diff --git a/content/02-understand-prisma/04-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md similarity index 100% rename from content/02-understand-prisma/04-prisma-in-your-stack/01-rest.md rename to content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md diff --git a/content/02-understand-prisma/04-prisma-in-your-stack/02-graphql.md b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md similarity index 100% rename from content/02-understand-prisma/04-prisma-in-your-stack/02-graphql.md rename to content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md diff --git a/content/02-understand-prisma/04-prisma-in-your-stack/index.mdx b/content/02-understand-prisma/03-prisma-in-your-stack/index.mdx similarity index 100% rename from content/02-understand-prisma/04-prisma-in-your-stack/index.mdx rename to content/02-understand-prisma/03-prisma-in-your-stack/index.mdx diff --git a/content/02-understand-prisma/05-is-prisma-an-orm.mdx b/content/02-understand-prisma/04-is-prisma-an-orm.mdx similarity index 100% rename from content/02-understand-prisma/05-is-prisma-an-orm.mdx rename to content/02-understand-prisma/04-is-prisma-an-orm.mdx diff --git a/content/02-understand-prisma/06-data-modeling.mdx b/content/02-understand-prisma/05-data-modeling.mdx similarity index 100% rename from content/02-understand-prisma/06-data-modeling.mdx rename to content/02-understand-prisma/05-data-modeling.mdx diff --git a/content/02-understand-prisma/07-prisma-under-the-hood.mdx b/content/02-understand-prisma/06-prisma-under-the-hood.mdx similarity index 100% rename from content/02-understand-prisma/07-prisma-under-the-hood.mdx rename to content/02-understand-prisma/06-prisma-under-the-hood.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-usage-with-module-bundlers.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx similarity index 96% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/18-usage-with-module-bundlers.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx index 1fc8d6be4a..595d3f529b 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-usage-with-module-bundlers.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx @@ -1,5 +1,5 @@ --- -title: 'Usage with module bundlers' +title: 'Module bundlers' metaTitle: '' metaDescription: '' --- diff --git a/content/02-understand-prisma/03-features.mdx b/content/03-reference/02-database-connectors/01-features.mdx similarity index 98% rename from content/02-understand-prisma/03-features.mdx rename to content/03-reference/02-database-connectors/01-features.mdx index fd223d578b..a802cb9333 100644 --- a/content/02-understand-prisma/03-features.mdx +++ b/content/03-reference/02-database-connectors/01-features.mdx @@ -4,6 +4,10 @@ metaTitle: '' metaDescription: '' --- +## Overview + +This page gives an overview of the features which are provided by the databases that Prisma supports. Additionally, it explains how each of these features can be used in Prisma with pointers to further documentation. + ## Relational database features This section describes which database features exist on the databases that are currently supported by Prisma. The **Prisma schema** column indicates how a certain feature can be represented in the [Prisma schema]() and links to its documentation. Note that database features can be used in **Prisma Client** even though they might not yet be representable in the Prisma schema. diff --git a/content/03-reference/02-database-connectors/01-postgresql.mdx b/content/03-reference/02-database-connectors/02-postgresql.mdx similarity index 100% rename from content/03-reference/02-database-connectors/01-postgresql.mdx rename to content/03-reference/02-database-connectors/02-postgresql.mdx diff --git a/content/03-reference/02-database-connectors/02-mysql.mdx b/content/03-reference/02-database-connectors/03-mysql.mdx similarity index 100% rename from content/03-reference/02-database-connectors/02-mysql.mdx rename to content/03-reference/02-database-connectors/03-mysql.mdx diff --git a/content/03-reference/02-database-connectors/03-sqlite.mdx b/content/03-reference/02-database-connectors/04-sqlite.mdx similarity index 100% rename from content/03-reference/02-database-connectors/03-sqlite.mdx rename to content/03-reference/02-database-connectors/04-sqlite.mdx diff --git a/content/03-reference/02-database-connectors/04-connection-urls.mdx b/content/03-reference/02-database-connectors/05-connection-urls.mdx similarity index 100% rename from content/03-reference/02-database-connectors/04-connection-urls.mdx rename to content/03-reference/02-database-connectors/05-connection-urls.mdx diff --git a/content/05-more/01-about-the-docs.mdx b/content/05-more/01-about-the-docs.mdx index 188276add0..5145f625c3 100644 --- a/content/05-more/01-about-the-docs.mdx +++ b/content/05-more/01-about-the-docs.mdx @@ -6,8 +6,6 @@ metaDescription: '' ## Overview -Coming ๐Ÿ”œ - ## The `User` and `Post` data model `User` and `Post` are the canonical models that are being used throughout the Prisma docs. This page gives some context on why these have been selected and how to interpret them. @@ -15,3 +13,7 @@ Coming ๐Ÿ”œ ## Naming conventions for tables and columns Table names are generally spelled in [PascalCase](). Column names in [camelCase](). + +## Embrace redundancy + +Meet the user where they are. \ No newline at end of file diff --git a/content/05-more/02-style-guide.mdx b/content/05-more/02-style-guide.mdx index d1a02f64f3..2c466832a7 100644 --- a/content/05-more/02-style-guide.mdx +++ b/content/05-more/02-style-guide.mdx @@ -75,6 +75,10 @@ This method allows people who would not like to learn more about xyz to stop rea If you want to abbreviate a term in your article, write it out fully first, then put the abbreviation in parentheses. After that, you may use the abbreviation going for the rest of the article. For example, "In computer science, an abstract syntax tree (AST) is โ€ฆ". +### Embrace redundancy + +Meet the user where they are. + ## Grammar and formatting ### Capitalize and spell out proper nouns From 68e2ed8162a4b1d2343cff3624768d11d89c5b0a Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 09:15:49 +0100 Subject: [PATCH 12/76] improve introduction --- .../02-understand-prisma/01-introduction.mdx | 112 ++++++++++++++++-- 1 file changed, 100 insertions(+), 12 deletions(-) diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index b303e8b052..baccc7e15e 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -92,27 +92,106 @@ The first step when using Prisma Client is installing its npm package: npm install @prisma/client ``` -Note that the installation of this package invokes the `prisma generate` command which reads your Prisma schema and _generates_ the Prisma Client code. The code will be located in `node_modules/@prisma/client`. After you change your data model, you'll need to manually run `prisma generate` to ensure the code inside `node_modules/@prisma/client` get updated. +Note that the installation of this package invokes the `prisma generate` command which reads your Prisma schema and _generates_ the Prisma Client code. The code will be located in `node_modules/@prisma/client`. -> **Note**: Because the Prisma Client node module contains specific context about _your_ Prisma schema, it's sometimes referred to as a ["smart node module"](). +After you change your data model, you'll need to manually re-generate Prisma Client to ensure the code inside `node_modules/@prisma/client` get updated: -#### +``` +prisma generate +``` +Note that cecause the Prisma Client node module contains specific context about _your_ Prisma schema, it's sometimes referred to as a ["smart node module"](). -### Typical Prisma workflows +#### Using Prisma Client to send queries to your database -#### Prisma Migrate +Once Prisma Client was generated, you can import in your code and send queries to your database. This is what the setup code looks like. -With Prisma Migrate, the workflow looks slightly different: +##### Import and instantiate Prisma Client -1. Manually adjust your [Prisma data model]() -1. Migrate your database using the `prisma migrate` CLI commands -1. (Re-)generate Prisma Client -1. Use Prisma Client in your application code to access your database + -![](https://imgur.com/nX0jIo5.png) +```ts +import { PrismaClient } from '@prisma/client' + +const prisma = new PrismaClient() +``` + +```js +const { PrismaClient } = require('@prisma/client') -#### SQL migrations and introspection +const prisma = new PrismaClient() +``` + + + +Now you can start queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return _plain old JavaScript objects_. + +Learn more about the available operations in the [Prisma Client API reference](). + +##### Retrieve all `User` records from the database + +```ts +// Run inside `async` function +const allUsers = await prisma.user.findMany() +``` + +##### Include the `posts` relation on each returned `User` object + +```ts +// Run inside `async` function +const allUsers = await prisma.user.findMany({ + include: { posts: true }, +}) +``` + +##### Filter all `Post` records that contain `"prisma"` + +```ts +// Run inside `async` function +const filteredPosts = await prisma.post.findMany({ + where: { + OR: [ + { title: { contains: "prisma" } }, + { content: { contains: "prisma" } }, + ], + }, +}) +``` + +##### Create a new `User` and a new `Post` record in the same query + +```ts +// Run inside `async` function +const user = await prisma.user.create({ + data: { + name: "Alice", + email: "alice@prisma.io", + posts: { + create: { title: "Join us for Prisma Day 2020" }, + }, + }, +}) +``` + +##### Update an existing `Post` record + +```ts +// Run inside `async` function +const post = await prisma.post.update({ + where: { id: 42 }, + data: { published: true }, +}) +``` + +#### Usage with TypeScript + +Note that when using TypeScript, the result of this query will be _statically typed_ so that you can't accidentally access a property that doesn't exist (and any typos are caught). Learn more about leveraging Prisma Client's generated types on the [Advanced usage of generated types]() page in the docs. + +## Typical Prisma workflows + +As mentioned above, there are two ways for "getting" your data model into the Prisma schema. Depending on which approach you choose, your main Prisma workflow might look different. + +### SQL migrations and introspection The typical workflow when using **SQL migrations and introspection** looks as follows: @@ -123,6 +202,15 @@ The typical workflow when using **SQL migrations and introspection** looks as fo ![](https://imgur.com/7BUqpyv.png) +### Prisma Migrate + +With **Prisma Migrate**, the workflow looks slightly different: +1. Manually adjust your [Prisma data model]() +1. Migrate your database using the `prisma migrate` CLI commands +1. (Re-)generate Prisma Client +1. Use Prisma Client in your application code to access your database + +![](https://imgur.com/nX0jIo5.png) To dive deeper, please refer to the respective docs page. From 190614fa2fd9f2b78608ee9896275bb6813b1101 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 09:59:49 +0100 Subject: [PATCH 13/76] add landing page and adjust sidenav --- ...ection-urls.mdx => 02-connection-urls.mdx} | 0 .../{02-postgresql.mdx => 03-postgresql.mdx} | 0 .../{03-mysql.mdx => 04-mysql.mdx} | 0 .../{04-sqlite.mdx => 05-sqlite.mdx} | 0 content/index.mdx | 23 +++++++++++++++++++ 5 files changed, 23 insertions(+) rename content/03-reference/02-database-connectors/{05-connection-urls.mdx => 02-connection-urls.mdx} (100%) rename content/03-reference/02-database-connectors/{02-postgresql.mdx => 03-postgresql.mdx} (100%) rename content/03-reference/02-database-connectors/{03-mysql.mdx => 04-mysql.mdx} (100%) rename content/03-reference/02-database-connectors/{04-sqlite.mdx => 05-sqlite.mdx} (100%) create mode 100644 content/index.mdx diff --git a/content/03-reference/02-database-connectors/05-connection-urls.mdx b/content/03-reference/02-database-connectors/02-connection-urls.mdx similarity index 100% rename from content/03-reference/02-database-connectors/05-connection-urls.mdx rename to content/03-reference/02-database-connectors/02-connection-urls.mdx diff --git a/content/03-reference/02-database-connectors/02-postgresql.mdx b/content/03-reference/02-database-connectors/03-postgresql.mdx similarity index 100% rename from content/03-reference/02-database-connectors/02-postgresql.mdx rename to content/03-reference/02-database-connectors/03-postgresql.mdx diff --git a/content/03-reference/02-database-connectors/03-mysql.mdx b/content/03-reference/02-database-connectors/04-mysql.mdx similarity index 100% rename from content/03-reference/02-database-connectors/03-mysql.mdx rename to content/03-reference/02-database-connectors/04-mysql.mdx diff --git a/content/03-reference/02-database-connectors/04-sqlite.mdx b/content/03-reference/02-database-connectors/05-sqlite.mdx similarity index 100% rename from content/03-reference/02-database-connectors/04-sqlite.mdx rename to content/03-reference/02-database-connectors/05-sqlite.mdx diff --git a/content/index.mdx b/content/index.mdx new file mode 100644 index 0000000000..032b0e5cac --- /dev/null +++ b/content/index.mdx @@ -0,0 +1,23 @@ +--- +title: 'Prisma Documentation' +metaTitle: '' +metaDescription: '' +--- + +## Overview + +Welcome to the Prisma documentation! You can find an overview of the available content in the sections below. The fastest way to get started with Prisma is the [**Quickstart**](). + +> **Using Prisma 1? Refer to the [Prisma 1 documentation]().** + +## Getting started + +The **Getting started** informations contains _practical_ guides that help you get started with Prisma. + +## Understand Prisma + +## Reference + +## Guides + +## More From ec947554a937223b52d28d7610d028d8ca2cf1af Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 11:57:40 +0100 Subject: [PATCH 14/76] continue docs --- ...a-schema.mdx => 01-prisma-schema-file.mdx} | 0 ... 08-advanced-usage-of-generated-types.mdx} | 0 .../01-postgresql.mdx | 0 .../02-mysql.mdx | 0 .../03-sqlite.mdx | 0 .../index.mdx | 0 content/index.mdx | 78 ++++++++++++++++++- 7 files changed, 76 insertions(+), 2 deletions(-) rename content/03-reference/01-tools-and-interfaces/01-prisma-schema/{01-what-is-the-prisma-schema.mdx => 01-prisma-schema-file.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{08-generated-types.mdx => 08-advanced-usage-of-generated-types.mdx} (100%) rename content/04-guides/01-database-workflows/{02-importing-and-exporting-data => 02-import-and-export-data}/01-postgresql.mdx (100%) rename content/04-guides/01-database-workflows/{02-importing-and-exporting-data => 02-import-and-export-data}/02-mysql.mdx (100%) rename content/04-guides/01-database-workflows/{02-importing-and-exporting-data => 02-import-and-export-data}/03-sqlite.mdx (100%) rename content/04-guides/01-database-workflows/{02-importing-and-exporting-data => 02-import-and-export-data}/index.mdx (100%) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-what-is-the-prisma-schema.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-what-is-the-prisma-schema.mdx rename to content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-generated-types.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-advanced-usage-of-generated-types.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/08-generated-types.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/08-advanced-usage-of-generated-types.mdx diff --git a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/01-postgresql.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx similarity index 100% rename from content/04-guides/01-database-workflows/02-importing-and-exporting-data/01-postgresql.mdx rename to content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx diff --git a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/02-mysql.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx similarity index 100% rename from content/04-guides/01-database-workflows/02-importing-and-exporting-data/02-mysql.mdx rename to content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx diff --git a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/03-sqlite.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx similarity index 100% rename from content/04-guides/01-database-workflows/02-importing-and-exporting-data/03-sqlite.mdx rename to content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx diff --git a/content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/index.mdx similarity index 100% rename from content/04-guides/01-database-workflows/02-importing-and-exporting-data/index.mdx rename to content/04-guides/01-database-workflows/02-import-and-export-data/index.mdx diff --git a/content/index.mdx b/content/index.mdx index 032b0e5cac..f1bba00303 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -8,16 +8,90 @@ metaDescription: '' Welcome to the Prisma documentation! You can find an overview of the available content in the sections below. The fastest way to get started with Prisma is the [**Quickstart**](). -> **Using Prisma 1? Refer to the [Prisma 1 documentation]().** +> **If you're using Prisma 1, please refer to the [Prisma 1 documentation]().** ## Getting started -The **Getting started** informations contains _practical_ guides that help you get started with Prisma. +The **Getting started** section contains _practical guides_ to help you get started with Prisma. + +- [Quickstart]() +- Setup Prisma + - [Add Prisma to an existing project]() + - [Start from scratch (SQL migrations)]() ## Understand Prisma +The **Understand Prisma** section contains _conceptual_ information about Prisma. + +- [Introduction]() +- [Why Prisma?]() +- Prisma in your stack + - [REST]() + - [GraphQL]() +- [Is Prisma an ORM?]() +- [Data modeling]() +- [Under the hood]() + ## Reference +The **Reference** section contains _technical_ information about Prisma. + +- Tools and interfaces + - Prisma schema + - [Prisma schema file]() + - [Data sources]() + - [Generators]() + - [Data model]() + - [Models]() + - [Relations]() + - Prisma Client + - [Generating Prisma Client]() + - [Configuring the Prisma Client API]() + - [CRUD]() + - [Relation queries]() + - [Field selection]() + - [Raw database access]() + - [Connection management]() + - [Advanced usage of generated types]() + - [Filtering]() + - [Ordering]() + - [Pagination]() + - [Debugging]() + - [Error formatting]() + - [Transactions]() + - [Deployment]() + - [Query engine]() + - [Module bundlers]() + - [API]() + - [Database polyfills]() + - [Prisma Migrate]() + - [Introspection]() + - Prisma CLI + - [Installation]() + - [Command reference]() + - Database connectors + - [Features]() + - [Connection URLs]() + - [PostgreSQL]() + - [MySQL]() + - [SQLite]() + - More + - [Editor setup]() + - [Telemetry]() + ## Guides +The **Reference** section contains _step-by-step tutorials_ on various topics. + +- Database workflows + - Setting up a database + - Import and export data + - Primary keys + - Unique constraints + - Foreign keys + ## More + +The **More** section contains _meta information_ about Prisma and the documentation itself. + +- \ No newline at end of file From 3e52a6b9c6973599e839a7ff6af1b1de173c4ea2 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 13:08:19 +0100 Subject: [PATCH 15/76] landing page content --- content/index.mdx | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/content/index.mdx b/content/index.mdx index f1bba00303..36b07fec33 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -10,7 +10,9 @@ Welcome to the Prisma documentation! You can find an overview of the available c > **If you're using Prisma 1, please refer to the [Prisma 1 documentation]().** -## Getting started +## Table of contents + +### Getting started The **Getting started** section contains _practical guides_ to help you get started with Prisma. @@ -19,7 +21,7 @@ The **Getting started** section contains _practical guides_ to help you get star - [Add Prisma to an existing project]() - [Start from scratch (SQL migrations)]() -## Understand Prisma +### Understand Prisma The **Understand Prisma** section contains _conceptual_ information about Prisma. @@ -32,7 +34,7 @@ The **Understand Prisma** section contains _conceptual_ information about Prisma - [Data modeling]() - [Under the hood]() -## Reference +### Reference The **Reference** section contains _technical_ information about Prisma. @@ -79,19 +81,32 @@ The **Reference** section contains _technical_ information about Prisma. - [Editor setup]() - [Telemetry]() -## Guides +### Guides The **Reference** section contains _step-by-step tutorials_ on various topics. - Database workflows - - Setting up a database - - Import and export data - - Primary keys - - Unique constraints - - Foreign keys + - [Setting up a database]() + - [Import and export data]() + - [Primary keys]() + - [Unique constraints]() + - [Foreign keys]() + - [Cascading deletes]() + - [Data validation]() +- Deployment + - [Deploying to AWS Lambda]() + - [Deploying to ZEIT Now]() + - [Deploying to Netlify]() + -## More +### More The **More** section contains _meta information_ about Prisma and the documentation itself. -- \ No newline at end of file +- [About the docs]() +- [Prisma style guide]() +- [Supported databases]() +- [Creating bug reports]() +- [FAQ]() +- [Limitations]() +- [Roadmap]() \ No newline at end of file From 3b97ca393502a512d746af94536714775d4de621 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 14:59:57 +0100 Subject: [PATCH 16/76] continue docs --- content/02-understand-prisma/01-introduction.mdx | 2 +- .../01-tools-and-interfaces/01-prisma-schema/06-relations.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index baccc7e15e..3e24f8b5a6 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -10,7 +10,7 @@ This page gives a high-level overview of what Prisma is and how it works. If you want to get started with a _practical introduction_ and learn about the Prisma Client API, head over to the [Quickstart](). -To learn more about the _motivation_ of Prisma, check out the [Why Prisma?](./why-prisma) page. +To learn more about the _motivation_ for Prisma, check out the [Why Prisma?](./why-prisma) page. ## What is Prisma? diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 5489e13f97..223be53f1c 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -183,7 +183,7 @@ When you don't need to attach additional information to the relation, you can mo ### Foreign key relation field -Foreign key relation fields are relation fields that are backed by a foreign key in the underlying database. For +Foreign key relation fields are relation fields that are backed by a foreign key in the underlying database. **They always require the `@relation attribute**. ### Virtual relation fields From 4381320a60019998f0e6702e89d9282b092b77a8 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 15:31:30 +0100 Subject: [PATCH 17/76] continue docs --- content/01-getting-started/02-quickstart.mdx | 485 ++++++++++++++++++- yarn.lock | 10 +- 2 files changed, 479 insertions(+), 16 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 5d137f16b5..1246925e2f 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -3,9 +3,13 @@ title: 'Quickstart' metaTitle: '' metaDescription: '' duration: '5 min' +langSwitcher: true --- -## Overview + + + +

    Overview (TypeScript)

    This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain Node.js script using Prisma Client. @@ -14,11 +18,11 @@ For the demo purposes of this guide, you will use a local [SQLite]() database fi - [Add Prisma to an existing project]() - [Setup Prisma from scratch with your own database]() -## Prerequisites +

    Prerequisites

    The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. -## Download starter project & install dependencies +

    Download starter project & install dependencies

    This guide comes with a small starter project that already has Prisma configured against a SQLite database file. @@ -72,7 +76,7 @@ cd starter npm install ``` -## Write your first query with Prisma Client +

    Write your first query with Prisma Client

    The code inside `src/index.js` currently looks as follows: @@ -167,7 +171,7 @@ Each object inside `allUsers` now includes a `posts` field which represents the Congratulations, you just wrote your first query with Prisma Client ๐ŸŽ‰ -## Write data into the database +

    Write data into the database

    The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. @@ -278,11 +282,11 @@ The `Post` record with an `id` of `2` now got updated in the database: Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ -## Next steps +

    Next steps

    This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. -### Continue exploring the Prisma Client API +

    Continue exploring the Prisma Client API

    You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. @@ -342,7 +346,7 @@ const deletedUser = await prisma.user.delete({ --- -### Setup Prisma with your own database +

    Setup Prisma with your own database

    To learn how to connect Prisma to your own database, you can follow the respective setup guide: @@ -351,7 +355,7 @@ To learn how to connect Prisma to your own database, you can follow the respecti --- -### Explore the data in Prisma Studio (experimental) +

    Explore the data in Prisma Studio (experimental)

    Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -361,7 +365,464 @@ npx prisma studio --experimental --- -### Change the database schema (e.g. add more tables) +

    Change the database schema (e.g. add more tables)

    + +Changing your database schema using SQL typically happens with the following steps. + +First, run a SQL migration against your database, e.g. with this command in your terminal: + +``` copy +sqlite3 ./prisma/dev.db \ +'CREATE TABLE "Profile" ( + "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + "bio" TEXT, + "user" TEXT NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL +)' +``` + +Then, introspect your database with this command from the Prisma CLI: + +``` copy +npx prisma introspect +``` + +This updates your [Prisma schema]()) in `prisma/schema.prisma`. + +Finally, re-generate Prisma Client with this command: + +``` copy +npx prisma generate +``` + +This updates the generated Prisma Client library in [`node_modules/@prisma/client`](). + +You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. + +
    Alternative: Use Prisma Migrate (experimental) + +Changing your database schema using Prisma Migrate typically happens with the following steps. + +First, adjust the data model in your Prisma schema, e.g. by adding a new model: + +```prisma copy +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] + profile Profile? +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? +} +``` + +Next, create a new migration by running the following command: + +```copy +npx prisma migrate save --name "add-profile" --experimental +npx prisma migrate up --experimental +``` + +Now you can run the migration against the database `npx prisma migrate up --experimental`. + +
    + +You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. + +--- + + +

    Try a Prisma example

    + +The [`prisma-examples`]() repository contains a number of ready-to-run examples: + +**TypeScript** + +| Demo | Stack | Description | +| :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | + +**JavaScript (Node.js)** + +| Demo | Stack | Description | +| :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | + +
    + + + + +

    Overview

    + +This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain Node.js script using Prisma Client. + +For the demo purposes of this guide, you will use a local [SQLite]() database file. This guide does _not_ cover the Prisma setup process. If you're looking to set up Prisma with your own database, you have these options: + +- [Add Prisma to an existing project]() +- [Setup Prisma from scratch with your own database]() + +

    Prerequisites

    + +The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. + +

    Download starter project & install dependencies

    + +This guide comes with a small starter project that already has Prisma configured against a SQLite database file. + +Open your terminal and download the starter project with the following command: + +```copy +curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter +``` + +This downloaded a directory called `starter`. + +
    +
    Expand for more info on the starter project + +The starter project consists of five files: + +- `package.json`: Defines your npm dependencies +- `prisma/schema.prisma`: Prisma configuration file defining your [models]() +- `prisma/.env`: Defines your database connection URL as an environment variable +- `prisma/dev.db`: A SQLite database file +- `scr/index.js`: A plain, executable Node.js script + +Note that the only two dependencies defined in your project are: + +- `@prisma/cli`: The Prisma CLI which you can invoke with `npx prisma` +- `@prisma/client`: Prisma Client library for accessing your database + +
    + +The SQLite database file `prisma/dev.db` contains two tables with dummy data: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"sarah@prisma.io"` | `"Sarah"` | +| `2` | `"maria@prisma.io"` | `"Maria"` | + +**Post** + +| **id** | **title** | **content** | **published** | **author** | +| :----- | :-------------- | :---------- | :------------ | :--------- | +| `1` | `"Hello World"` | `null` | `false` | `2` | + +> **Note**: The number in the `author` column references the `id` column of the `User` table: the `2` in the `author` column refers to the `User` record with an `id` value of `2`. + +Befor you move on, navigate into the `starter` directory and install the npm dependencies with these commands: + +```copy +cd starter +npm install +``` + +

    Write your first query with Prisma Client

    + +The code inside `src/index.js` currently looks as follows: + +```js +const { PrismaClient } = require("@prisma/client") + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .catch(e => { + throw e + }) + .finally(async () => { + await prisma.disconnect() + }) +``` + +
    +
    Expand for an explanation of the script + +Here's a quick overview of the main parts: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function called `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +
    + +Inside the `main` function, add the folowing query to read all `User` records from the database and print the result: + +```js copy +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +``` copy +npm run dev +``` + +This should print following result to output: + +```js +[ + { id: 1, email: "sarah@prisma.io", name: "Sarah" }, + { id: 2, email: "maria@prisma.io", name: "Maria" }, +] +``` + +One of the main features of Prisma Client is the ease for working with relations. You can retrieve the `posts` of each user by using the `include` option. Adjust your code to look as follows: + +```js copy +async function main() { + const allUsers = await prisma.user.findMany({ + include: { posts: true }, + }) + // use `console.dir` to print nested objects + console.dir(allUsers, { depth: null }) +} +``` + +Run the code again with: + +``` copy +npm run dev +``` + +Each object inside `allUsers` now includes a `posts` field which represents the data in the relation between the `User` and `Post` tables: + +```js +[ + { id: 1, email: 'sarah@prisma.io', name: 'Sarah', posts: [] } + { + id: 2, + email: 'maria@prisma.io', + name: 'Maria', + posts: [ + { id: 1, title: 'Hello World', content: null, published: false } + ] + } +] +``` + +Congratulations, you just wrote your first query with Prisma Client ๐ŸŽ‰ + +

    Write data into the database

    + +The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js copy +async function main() { + const post = await prisma.post.create({ + data: { + title: "Prisma makes databases easy", + author: { + connect: { email: "sarah@prisma.io" }, + }, + }, + }) + console.log(post) + + const allUsers = await prisma.user.findMany({ + include: { posts: true }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `Post` record and _connects_ it in a [nested write]() to an existing `User` record. + +Run the code with this command: + +``` copy +npm run dev +``` + +The output should look similar to this: + +```js +{ + id: 2, + title: 'Prisma makes databases easy', + content: null, + published: false +} +[ + { + id: 1, + email: 'sarah@prisma.io', + name: 'Sarah', + posts: [ + { id: 2, title: 'Prisma makes databases easy', content: null, published: false } + ] + } + { + id: 2, + email: 'maria@prisma.io', + name: 'Maria', + posts: [ + { id: 1, title: 'Hello World', content: null, published: false } + ] + } +] +``` + +The query added a new record to the `Post` table: + +**Post** + +| **id** | **title** | **content** | **published** | **author** | +| :----- | :------------------------------ | :---------- | :------------ | :--------- | +| `1` | `"Hello World"` | `null` | `false` | `2` | +| `2` | `"Prisma makes databases easy"` | `null` | `false` | `1` | + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js copy +async function main() { + const post = await prisma.post.update({ + where: { id: 2 }, + data: { published: true }, + }) + console.log(post) +} +``` + +Now run the code using the same command as before: + +``` copy +npm run dev +``` + +You will see the following output: + +```js +{ + id: 2, + title: 'Prisma makes databases easy', + content: null, + published: true +} +``` + +The `Post` record with an `id` of `2` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **author** | +| :----- | :------------------------------ | :---------- | :------------ | :--------- | +| `1` | `"Hello World"` | `null` | `false` | `2` | +| `2` | `"Prisma makes databases easy"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ + +

    Next steps

    + +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. + +

    Continue exploring the Prisma Client API

    + +You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. + +**Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. + +
    Expand for more Prisma Client API examples + +Here are a few suggestions for a number of more queries you can send with Prisma Client: + +**Filter all `Post` records that contain `"prisma"`** + +```js copy +const filteredPosts = await prisma.post.findMany({ + where: { + OR: [ + { title: { contains: "prisma" } }, + { content: { contains: "prisma" } }, + ], + }, +}) +``` + +**Create a new `User` and a new `Post` record in the same query** + +```js copy +const user = await prisma.user.create({ + data: { + name: "Nancy", + email: "nancy@prisma.io", + posts: { + create: { title: "Join us for Prisma Day 2020" }, + }, + }, +}) +``` + +**Use the fluent relations API to retrieve the `Post` records of a `User`** + +```js copy +const posts = await prisma.user + .findOne({ + where: { email: "sarah@prisma.io" }, + }) + .posts() +``` + +**Delete a `User` record** + +```js copy +const deletedUser = await prisma.user.delete({ + where: { email: "sarah@prisma.io" }, +}) +``` + +
    + + +--- + +

    Setup Prisma with your own database

    + +To learn how to connect Prisma to your own database, you can follow the respective setup guide: + +- [Add Prisma to an existing project]() +- [Setup Prisma from scratch with your own database]() + +--- + +

    Explore the data in Prisma Studio (experimental)

    + +Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: + +``` copy +npx prisma studio --experimental +``` + +--- + +

    Change the database schema (e.g. add more tables)

    Changing your database schema using SQL typically happens with the following steps. @@ -440,7 +901,7 @@ You can now run queries against the new `Profile` table, e.g. using `prisma.prof --- -### Try a Prisma example +

    Try a Prisma example

    The [`prisma-examples`]() repository contains a number of ready-to-run examples: @@ -462,3 +923,5 @@ The [`prisma-examples`]() repository contains a number of ready-to-run examples: | [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | | [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | | [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | + +
    diff --git a/yarn.lock b/yarn.lock index 8e25491f08..ddd6a9aa80 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6390,10 +6390,10 @@ gatsby-plugin-react-helmet@^3.0.9: dependencies: "@babel/runtime" "^7.8.7" -gatsby-plugin-sharp@^2.5.2: - version "2.5.2" - resolved "https://registry.yarnpkg.com/gatsby-plugin-sharp/-/gatsby-plugin-sharp-2.5.2.tgz#73a12ebfc053a940cd75e920cd3f292e0bdc3dcd" - integrity sha512-dWVnuOeeZhEsaYaBcctSybDzYv8wmsjZlxhFspnveMscEgO1whBW5eolBNzRLa+ooocW3wRKg0TYljLlLfHv4g== +gatsby-plugin-sharp@^2.4.5: + version "2.5.3" + resolved "https://registry.yarnpkg.com/gatsby-plugin-sharp/-/gatsby-plugin-sharp-2.5.3.tgz#7644ab20228f13af5b9fdebc5c1bb22662dfc7c3" + integrity sha512-/qx0QJNXsmHudEGlRm6oqkq+X228hGBJ6KjCJpJK5bUwWdhcZRJNar337g/2BXPchaxk1emJTUK9y+qSvVpPvw== dependencies: "@babel/runtime" "^7.8.7" async "^2.6.3" @@ -14868,7 +14868,7 @@ unist-util-visit-children@^1.0.0: resolved "https://registry.yarnpkg.com/unist-util-visit-children/-/unist-util-visit-children-1.1.4.tgz#e8a087e58a33a2815f76ea1901c15dec2cb4b432" integrity sha512-sA/nXwYRCQVRwZU2/tQWUqJ9JSFM1X3x7JIOsIgSzrFHcfVt6NkzDtKzyxg2cZWkCwGF9CO8x4QNZRJRMK8FeQ== -unist-util-visit-parents@^2.0.0, unist-util-visit-parents@^2.1.2: +unist-util-visit-parents@^2.0.0, unist-util-visit-parents@^2.0.1, unist-util-visit-parents@^2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-2.1.2.tgz#25e43e55312166f3348cae6743588781d112c1e9" integrity sha512-DyN5vD4NE3aSeB+PXYNKxzGsfocxp6asDc2XXE3b0ekO2BaRUpBicbbUygfSvYfUz1IkmjFR1YF7dPklraMZ2g== From 97cd0cbf6efc5041111a2f2b2484625d5cab8b9e Mon Sep 17 00:00:00 2001 From: Nilu Date: Fri, 27 Mar 2020 16:17:38 +0100 Subject: [PATCH 18/76] default lang, db --- content/01-getting-started/04-example.mdx | 4 ++-- src/components/techSwitcher.tsx | 14 ++++---------- src/components/topSection.tsx | 4 ++-- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/content/01-getting-started/04-example.mdx b/content/01-getting-started/04-example.mdx index 98b0d21e16..c820121034 100644 --- a/content/01-getting-started/04-example.mdx +++ b/content/01-getting-started/04-example.mdx @@ -24,9 +24,9 @@ psql -h localhost -d hello-prisma -U janedoe -f schema.sql - + -

    Go Mysql

    +

    node postgres

    ```go go diff --git a/src/components/techSwitcher.tsx b/src/components/techSwitcher.tsx index 5e3fe6dbc1..e30f348e51 100644 --- a/src/components/techSwitcher.tsx +++ b/src/components/techSwitcher.tsx @@ -5,8 +5,6 @@ import SelectComponent from './select'; import PostgreSQL from '../icons/technologies/PostgreSQL'; import MySQL from '../icons/technologies/MySQL'; import MongoDB from '../icons/technologies/MongoDB'; -import Go from '../icons/technologies/Go'; -import Flow from '../icons/technologies/Flow'; import JS from '../icons/technologies/JS'; interface TechSwitchProps { @@ -23,29 +21,25 @@ const icons = { typescript: , mysql: , postgres: , - mongodb: , - go: , - flow: , + mongodb: }; const technologyTypes = { - languages: ['node', 'typescript', 'flow', 'go'], + languages: ['node', 'typescript'], databases: ['mysql', 'postgres', 'mongodb'], }; export const technologyNames = { node: 'JavaScript', typescript: 'TypeScript', - flow: 'Flow', mysql: 'MySQL', postgres: 'PostgreSQL', mongodb: 'MongoDB', - go: 'Go', }; const TechnologySwitch = ({ type, onChangeTech }: TechSwitchProps) => { - const langDefault = { technology: 'node' }; - const dbDefault = { technology: 'mysql' }; + const langDefault = { technology: 'typescript' }; + const dbDefault = { technology: 'postgres' }; const defaultItem = type === 'lang' ? langDefault : dbDefault; const [selectedItem, setSelectedItem] = React.useState(defaultItem); diff --git a/src/components/topSection.tsx b/src/components/topSection.tsx index 5661438761..2a9891e5fe 100644 --- a/src/components/topSection.tsx +++ b/src/components/topSection.tsx @@ -35,8 +35,8 @@ const SwitcherWrapper = styled.div` `; const TopSection = ({ location, title, parentTitle, indexPage, langSwitcher, dbSwitcher }: any) => { - const [langSelected, setLangSelected] = React.useState('node'); - const [dbSelected, setDbSelected] = React.useState('mysql'); + const [langSelected, setLangSelected] = React.useState('typescript'); + const [dbSelected, setDbSelected] = React.useState('postgres'); const techChanged = (item: any, type: string) => { const elements = document.querySelectorAll('[id^="techswitch"]'); From ff7134b1c391b15312555740399005f89420d927 Mon Sep 17 00:00:00 2001 From: Nilu Date: Fri, 27 Mar 2020 17:36:57 +0100 Subject: [PATCH 19/76] Bug fix for table --- content/02-understand-prisma/02-why-prisma.mdx | 4 ++-- content/05-more/01-about-the-docs.mdx | 2 +- content/index.mdx | 7 +++---- src/components/customMdx/code.tsx | 2 +- src/components/customMdx/collapsible.tsx | 6 +++--- src/components/customMdx/index.tsx | 4 +++- src/components/customMdx/table.tsx | 18 ++++++++++++++++++ src/components/layout.css | 18 +++--------------- src/components/seo.tsx | 2 +- src/components/techSwitcher.tsx | 2 +- src/pages/index.tsx | 11 ----------- 11 files changed, 36 insertions(+), 40 deletions(-) create mode 100644 src/components/customMdx/table.tsx diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx index da53e07737..9cdc639b38 100644 --- a/content/02-understand-prisma/02-why-prisma.mdx +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -34,10 +34,10 @@ The biggest drawback with SQL query builders is that application developers stil ### ORMs: Less control, better productivity -ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. +ORMs abstract away from SQL by letting you _define your application models as classes_, these classes are mapped to tables in the database. > "Object relational mappers" (ORMs) exist to bridge the gap between the programmers' friend (the object), and the database's primitive (the relation). The reasons for these differing models are as much cultural as functional: programmers like objects because they encapsulate the state of a single thing in a running program. Databases like relations because they better suit whole-dataset constraints and efficient access patterns for the entire dataset. -> +> > [The Troublesome Active Record Pattern, Cal Paterson (2020)](http://calpaterson.com/activerecord.html) You can then read and write data by calling methods on the instances of your model classes. diff --git a/content/05-more/01-about-the-docs.mdx b/content/05-more/01-about-the-docs.mdx index 5145f625c3..974c033157 100644 --- a/content/05-more/01-about-the-docs.mdx +++ b/content/05-more/01-about-the-docs.mdx @@ -16,4 +16,4 @@ Table names are generally spelled in [PascalCase](). Column names in [camelCase] ## Embrace redundancy -Meet the user where they are. \ No newline at end of file +Meet the user where they are. diff --git a/content/index.mdx b/content/index.mdx index 36b07fec33..483042ab40 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -83,7 +83,7 @@ The **Reference** section contains _technical_ information about Prisma. ### Guides -The **Reference** section contains _step-by-step tutorials_ on various topics. +The **Reference** section contains _step-by-step tutorials_ on various topics. - Database workflows - [Setting up a database]() @@ -98,10 +98,9 @@ The **Reference** section contains _step-by-step tutorials_ on various topics. - [Deploying to ZEIT Now]() - [Deploying to Netlify]() - ### More -The **More** section contains _meta information_ about Prisma and the documentation itself. +The **More** section contains _meta information_ about Prisma and the documentation itself. - [About the docs]() - [Prisma style guide]() @@ -109,4 +108,4 @@ The **More** section contains _meta information_ about Prisma and the documenta - [Creating bug reports]() - [FAQ]() - [Limitations]() -- [Roadmap]() \ No newline at end of file +- [Roadmap]() diff --git a/src/components/customMdx/code.tsx b/src/components/customMdx/code.tsx index 8ade28efb8..8ae9fa84b6 100644 --- a/src/components/customMdx/code.tsx +++ b/src/components/customMdx/code.tsx @@ -22,4 +22,4 @@ const Code = ({ className, children, ...props }: CodeProps) => { ); }; -export default Code; \ No newline at end of file +export default Code; diff --git a/src/components/customMdx/collapsible.tsx b/src/components/customMdx/collapsible.tsx index 96c6f014aa..e7c649802b 100644 --- a/src/components/customMdx/collapsible.tsx +++ b/src/components/customMdx/collapsible.tsx @@ -9,9 +9,9 @@ const getRemainingChildren = (children: any) => children.filter((child: any) => !(child.props && child.props.originalType === 'summary')); const CollapseBox = ({ children, ...props }: CollapseProps) => { - const titleChild = children && children.find( - (child: any) => child.props && child.props.originalType === 'summary' - ); + const titleChild = + children && + children.find((child: any) => child.props && child.props.originalType === 'summary'); const title = titleChild && titleChild.props.children; return ( diff --git a/src/components/customMdx/index.tsx b/src/components/customMdx/index.tsx index 663789ca92..22914145b0 100644 --- a/src/components/customMdx/index.tsx +++ b/src/components/customMdx/index.tsx @@ -4,6 +4,7 @@ import CodeBlock from './codeBlock'; import Code from './code'; import Pre from './pre'; import CollapseBox from './collapsible'; +import Table from './table'; import makeHeading from './headings'; export default { @@ -19,5 +20,6 @@ export default { SwitchTech, pre: Pre, code: Code, - details: CollapseBox + details: CollapseBox, + table: Table, }; diff --git a/src/components/customMdx/table.tsx b/src/components/customMdx/table.tsx new file mode 100644 index 0000000000..9fbacf7774 --- /dev/null +++ b/src/components/customMdx/table.tsx @@ -0,0 +1,18 @@ +import React from 'react'; +import styled from 'styled-components'; + +type TableProps = React.ReactNode; + +const Table = ({ children, ...props }: TableProps) => { + return ( + + {children}
    +
    + ); +}; + +export default Table; + +const TableWrapper = styled.div` + overflow-x: auto; +`; diff --git a/src/components/layout.css b/src/components/layout.css index b073ae6466..95f66355c2 100644 --- a/src/components/layout.css +++ b/src/components/layout.css @@ -50,15 +50,6 @@ h6 > a { color: #1a202c !important; } -/* h2 > a:focus::before, -h2 > a:hover::before { - content: '#'; - margin-left: -20px; - margin-right: 5px; - color: #cbd5e0; - font-weight: normal; -} */ - * { box-sizing: border-box; } @@ -89,15 +80,12 @@ li { } table { - min-width: 100%; - table-layout: fixed; + width: 100%; word-break: normal; border: 1px solid #e2e8f0; border-radius: 8px; border-spacing: 0px; margin: 1.5rem 0px; - display: block; - overflow-x: scroll; white-space: nowrap; } @@ -113,10 +101,10 @@ table td { border-top: 1px solid rgb(204, 217, 223); } -:not(pre) > code[class*='language-text'], :not(pre) > code { +:not(pre) > code[class*='language-text'], +:not(pre) > code { font-family: 'Roboto Mono'; font-style: normal; - /* font-weight: 500; */ font-size: 14px; line-height: 24px; background: #edf2f7; diff --git a/src/components/seo.tsx b/src/components/seo.tsx index be6c09caa4..dd0aea36e2 100644 --- a/src/components/seo.tsx +++ b/src/components/seo.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import Helmet from 'react-helmet'; -import favicon from '../images/favicon-32x32.png' +import favicon from '../images/favicon-32x32.png'; type SEOProps = { title?: string; diff --git a/src/components/techSwitcher.tsx b/src/components/techSwitcher.tsx index e30f348e51..2af3a192a6 100644 --- a/src/components/techSwitcher.tsx +++ b/src/components/techSwitcher.tsx @@ -21,7 +21,7 @@ const icons = { typescript: , mysql: , postgres: , - mongodb: + mongodb: , }; const technologyTypes = { diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 63a1d4ea6a..a887723b06 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -5,17 +5,6 @@ import Layout from '../components/layout'; import TopSection from '../components/topSection'; import SEO from '../components/seo'; -// const Container = styled.span` -// font-family: 'Rubik', sans-serif; -// font-size: 3rem; -// font-weight: 500; -// color: #2f3747; -// font-weight: bold; -// display: flex; -// padding: 40px; -// justify-content: center; -// `; - const BlockContent = styled.div` background: #ffffff; box-shadow: 0px 4px 8px rgba(47, 55, 71, 0.05), 0px 1px 3px rgba(47, 55, 71, 0.1); From 41ebbd303dafb3cd96bc86839b494b0bc03177b2 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 18:43:01 +0100 Subject: [PATCH 20/76] add more tech combos for getting started --- content/01-getting-started/02-quickstart.mdx | 549 ++++-------------- .../01-add-to-an-existing-project.mdx | 211 ++++++- .../02-start-from-scratch-sql-migrations.mdx | 2 +- .../02-prisma-client/18-module-bundlers.mdx | 8 +- content/index.mdx | 8 + 5 files changed, 316 insertions(+), 462 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 1246925e2f..32315a1a14 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -2,41 +2,95 @@ title: 'Quickstart' metaTitle: '' metaDescription: '' -duration: '5 min' +duration: '5 min' langSwitcher: true --- +## Overview - + -

    Overview (TypeScript)

    +This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain **TypeScript** script using Prisma Client. -This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain Node.js script using Prisma Client. +
    + + + +This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain **Node.js** script using Prisma Client. + + For the demo purposes of this guide, you will use a local [SQLite]() database file. This guide does _not_ cover the Prisma setup process. If you're looking to set up Prisma with your own database, you have these options: - [Add Prisma to an existing project]() - [Setup Prisma from scratch with your own database]() -

    Prerequisites

    +## Prerequisites + + + +The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. + +TypeScript will be added as a local dependency to the project, so no need to install it. + + + + The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. -

    Download starter project & install dependencies

    +
    + + +## Download starter project & install dependencies This guide comes with a small starter project that already has Prisma configured against a SQLite database file. Open your terminal and download the starter project with the following command: + + ```copy curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter ``` + + + + +```copy +curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter +``` + + This downloaded a directory called `starter`.
    Expand for more info on the starter project + + + +The starter project consists of six files: + +- `package.json`: Defines your npm dependencies +- `prisma/schema.prisma`: Prisma configuration file defining your [models]() +- `prisma/.env`: Defines your database connection URL as an environment variable +- `prisma/dev.db`: A SQLite database file +- `scr/index.ts`: A plain, executable TypeScript script +- `tsconfig.json`: TypeScript configuration + +Note that the dependencies defined in your project are: + +- `@prisma/cli`: The Prisma CLI which you can invoke with `npx prisma` +- `@prisma/client`: Prisma Client library for accessing your database +- `typescript`: TypeScript toolchain +- `ts-node`: Used to execute the TypeScript script + + + + + The starter project consists of five files: - `package.json`: Defines your npm dependencies @@ -50,6 +104,8 @@ Note that the only two dependencies defined in your project are: - `@prisma/cli`: The Prisma CLI which you can invoke with `npx prisma` - `@prisma/client`: Prisma Client library for accessing your database + +
    The SQLite database file `prisma/dev.db` contains two tables with dummy data: @@ -76,12 +132,14 @@ cd starter npm install ``` -

    Write your first query with Prisma Client

    +## Write your first query with Prisma Client -The code inside `src/index.js` currently looks as follows: + -```js -const { PrismaClient } = require("@prisma/client") +The code inside `src/index.ts` currently looks as follows: + +```ts +import { PrismaClient } from "@prisma/client" const prisma = new PrismaClient() @@ -98,443 +156,11 @@ main() }) ``` -
    -
    Expand for an explanation of the script - -Here's a quick overview of the main parts: - -1. Import the `PrismaClient` constructor from the `@prisma/client` node module -1. Instantiate `PrismaClient` -1. Define an `async` function called `main` to send queries to the database -1. Call the `main` function -1. Close the database connections when the script terminates - -
    - -Inside the `main` function, add the folowing query to read all `User` records from the database and print the result: - -```js copy -async function main() { - const allUsers = await prisma.user.findMany() - console.log(allUsers) -} -``` - -Now run the code with this command: - -``` copy -npm run dev -``` - -This should print following result to output: - -```js -[ - { id: 1, email: "sarah@prisma.io", name: "Sarah" }, - { id: 2, email: "maria@prisma.io", name: "Maria" }, -] -``` - -One of the main features of Prisma Client is the ease for working with relations. You can retrieve the `posts` of each user by using the `include` option. Adjust your code to look as follows: - -```js copy -async function main() { - const allUsers = await prisma.user.findMany({ - include: { posts: true }, - }) - // use `console.dir` to print nested objects - console.dir(allUsers, { depth: null }) -} -``` - -Run the code again with: - -``` copy -npm run dev -``` - -Each object inside `allUsers` now includes a `posts` field which represents the data in the relation between the `User` and `Post` tables: - -```js -[ - { id: 1, email: 'sarah@prisma.io', name: 'Sarah', posts: [] } - { - id: 2, - email: 'maria@prisma.io', - name: 'Maria', - posts: [ - { id: 1, title: 'Hello World', content: null, published: false } - ] - } -] -``` - -Congratulations, you just wrote your first query with Prisma Client ๐ŸŽ‰ - -

    Write data into the database

    - -The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. - -Adjust the `main` function to send a `create` query to the database: - -```js copy -async function main() { - const post = await prisma.post.create({ - data: { - title: "Prisma makes databases easy", - author: { - connect: { email: "sarah@prisma.io" }, - }, - }, - }) - console.log(post) - - const allUsers = await prisma.user.findMany({ - include: { posts: true }, - }) - console.dir(allUsers, { depth: null }) -} -``` - -This code creates a new `Post` record and _connects_ it in a [nested write]() to an existing `User` record. - -Run the code with this command: - -``` copy -npm run dev -``` - -The output should look similar to this: - -```js -{ - id: 2, - title: 'Prisma makes databases easy', - content: null, - published: false -} -[ - { - id: 1, - email: 'sarah@prisma.io', - name: 'Sarah', - posts: [ - { id: 2, title: 'Prisma makes databases easy', content: null, published: false } - ] - } - { - id: 2, - email: 'maria@prisma.io', - name: 'Maria', - posts: [ - { id: 1, title: 'Hello World', content: null, published: false } - ] - } -] -``` - -The query added a new record to the `Post` table: - -**Post** - -| **id** | **title** | **content** | **published** | **author** | -| :----- | :------------------------------ | :---------- | :------------ | :--------- | -| `1` | `"Hello World"` | `null` | `false` | `2` | -| `2` | `"Prisma makes databases easy"` | `null` | `false` | `1` | - -Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: - -```js copy -async function main() { - const post = await prisma.post.update({ - where: { id: 2 }, - data: { published: true }, - }) - console.log(post) -} -``` - -Now run the code using the same command as before: - -``` copy -npm run dev -``` - -You will see the following output: - -```js -{ - id: 2, - title: 'Prisma makes databases easy', - content: null, - published: true -} -``` - -The `Post` record with an `id` of `2` now got updated in the database: - -**Post** - -| **id** | **title** | **content** | **published** | **author** | -| :----- | :------------------------------ | :---------- | :------------ | :--------- | -| `1` | `"Hello World"` | `null` | `false` | `2` | -| `2` | `"Prisma makes databases easy"` | `null` | `true` | `1` | - -Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ - -

    Next steps

    - -This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. - -

    Continue exploring the Prisma Client API

    - -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. - -**Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. - -
    Expand for more Prisma Client API examples - -Here are a few suggestions for a number of more queries you can send with Prisma Client: - -**Filter all `Post` records that contain `"prisma"`** - -```js copy -const filteredPosts = await prisma.post.findMany({ - where: { - OR: [ - { title: { contains: "prisma" } }, - { content: { contains: "prisma" } }, - ], - }, -}) -``` - -**Create a new `User` and a new `Post` record in the same query** - -```js copy -const user = await prisma.user.create({ - data: { - name: "Nancy", - email: "nancy@prisma.io", - posts: { - create: { title: "Join us for Prisma Day 2020" }, - }, - }, -}) -``` - -**Use the fluent relations API to retrieve the `Post` records of a `User`** - -```js copy -const posts = await prisma.user - .findOne({ - where: { email: "sarah@prisma.io" }, - }) - .posts() -``` - -**Delete a `User` record** - -```js copy -const deletedUser = await prisma.user.delete({ - where: { email: "sarah@prisma.io" }, -}) -``` - -
    - - ---- - -

    Setup Prisma with your own database

    - -To learn how to connect Prisma to your own database, you can follow the respective setup guide: - -- [Add Prisma to an existing project]() -- [Setup Prisma from scratch with your own database]() - ---- - -

    Explore the data in Prisma Studio (experimental)

    - -Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: - -``` copy -npx prisma studio --experimental -``` - ---- - -

    Change the database schema (e.g. add more tables)

    - -Changing your database schema using SQL typically happens with the following steps. - -First, run a SQL migration against your database, e.g. with this command in your terminal: - -``` copy -sqlite3 ./prisma/dev.db \ -'CREATE TABLE "Profile" ( - "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - "bio" TEXT, - "user" TEXT NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL -)' -``` - -Then, introspect your database with this command from the Prisma CLI: - -``` copy -npx prisma introspect -``` - -This updates your [Prisma schema]()) in `prisma/schema.prisma`. - -Finally, re-generate Prisma Client with this command: - -``` copy -npx prisma generate -``` - -This updates the generated Prisma Client library in [`node_modules/@prisma/client`](). - -You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. - -
    Alternative: Use Prisma Migrate (experimental) - -Changing your database schema using Prisma Migrate typically happens with the following steps. - -First, adjust the data model in your Prisma schema, e.g. by adding a new model: - -```prisma copy -model User { - id Int @id @default(autoincrement()) - email String @unique - name String? - posts Post[] - profile Profile? -} - -model Post { - id Int @id @default(autoincrement()) - title String - content String? - published Boolean @default(false) - author User? -} -``` - -Next, create a new migration by running the following command: - -```copy -npx prisma migrate save --name "add-profile" --experimental -npx prisma migrate up --experimental -``` - -Now you can run the migration against the database `npx prisma migrate up --experimental`. - -
    - -You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. - ---- - - -

    Try a Prisma example

    - -The [`prisma-examples`]() repository contains a number of ready-to-run examples: - -**TypeScript** - -| Demo | Stack | Description | -| :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | - -**JavaScript (Node.js)** - -| Demo | Stack | Description | -| :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API |
    - -

    Overview

    - -This page explains how to get started with Prisma in five minutes. You will learn how to send queries to a SQL database in a plain Node.js script using Prisma Client. - -For the demo purposes of this guide, you will use a local [SQLite]() database file. This guide does _not_ cover the Prisma setup process. If you're looking to set up Prisma with your own database, you have these options: - -- [Add Prisma to an existing project]() -- [Setup Prisma from scratch with your own database]() - -

    Prerequisites

    - -The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. - -

    Download starter project & install dependencies

    - -This guide comes with a small starter project that already has Prisma configured against a SQLite database file. - -Open your terminal and download the starter project with the following command: - -```copy -curl https://codeload.github.com/prisma/prisma-examples/tar.gz/starter | tar -xz --strip=2 prisma-examples-starter/javascript/starter -``` - -This downloaded a directory called `starter`. - -
    -
    Expand for more info on the starter project - -The starter project consists of five files: - -- `package.json`: Defines your npm dependencies -- `prisma/schema.prisma`: Prisma configuration file defining your [models]() -- `prisma/.env`: Defines your database connection URL as an environment variable -- `prisma/dev.db`: A SQLite database file -- `scr/index.js`: A plain, executable Node.js script - -Note that the only two dependencies defined in your project are: - -- `@prisma/cli`: The Prisma CLI which you can invoke with `npx prisma` -- `@prisma/client`: Prisma Client library for accessing your database - -
    - -The SQLite database file `prisma/dev.db` contains two tables with dummy data: - -**User** - -| **id** | **email** | **name** | -| :----- | :------------------ | :-------- | -| `1` | `"sarah@prisma.io"` | `"Sarah"` | -| `2` | `"maria@prisma.io"` | `"Maria"` | - -**Post** - -| **id** | **title** | **content** | **published** | **author** | -| :----- | :-------------- | :---------- | :------------ | :--------- | -| `1` | `"Hello World"` | `null` | `false` | `2` | - -> **Note**: The number in the `author` column references the `id` column of the `User` table: the `2` in the `author` column refers to the `User` record with an `id` value of `2`. - -Befor you move on, navigate into the `starter` directory and install the npm dependencies with these commands: - -```copy -cd starter -npm install -``` - -

    Write your first query with Prisma Client

    - The code inside `src/index.js` currently looks as follows: ```js @@ -555,6 +181,8 @@ main() }) ``` +
    +
    Expand for an explanation of the script @@ -626,9 +254,30 @@ Each object inside `allUsers` now includes a `posts` field which represents the ] ``` + + + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts +const allUsers: (User & { + posts: Post[]; +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean +} +``` + + + + Congratulations, you just wrote your first query with Prisma Client ๐ŸŽ‰ -

    Write data into the database

    +## Write data into the database The `findMany` query you used in the previous section only _reads_ data from the database. In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. @@ -739,11 +388,11 @@ The `Post` record with an `id` of `2` now got updated in the database: Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ -

    Next steps

    +## Next steps This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. -

    Continue exploring the Prisma Client API

    +### Continue exploring the Prisma Client API You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. @@ -803,7 +452,7 @@ const deletedUser = await prisma.user.delete({ --- -

    Setup Prisma with your own database

    +### Setup Prisma with your own database To learn how to connect Prisma to your own database, you can follow the respective setup guide: @@ -812,7 +461,7 @@ To learn how to connect Prisma to your own database, you can follow the respecti --- -

    Explore the data in Prisma Studio (experimental)

    +### Explore the data in Prisma Studio (experimental) Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: @@ -822,7 +471,7 @@ npx prisma studio --experimental --- -

    Change the database schema (e.g. add more tables)

    +### Change the database schema (e.g. add more tables) Changing your database schema using SQL typically happens with the following steps. @@ -901,7 +550,7 @@ You can now run queries against the new `Profile` table, e.g. using `prisma.prof --- -

    Try a Prisma example

    +### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: @@ -923,5 +572,3 @@ The [`prisma-examples`]() repository contains a number of ready-to-run examples: | [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | | [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | | [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | - - diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index 28416d71cb..9a6415f131 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -2,27 +2,67 @@ title: 'Add Prisma to an existing project' metaTitle: '' metaDescription: '' +dbSwitcher: true +langSwitcher: true --- ## Overview -This page walks you through the process of adding Prisma to a Node.js project with an existing database. + + +This page walks you through the process of adding Prisma to a **TypeScript** project with an existing database. + + + + + +This page walks you through the process of adding Prisma to a **Node.js** project with an existing database. + + ## Prerequisites In order to successfully complete this guide, you need: + + +- an existing Node.js (version 10 or higher) project with a `package.json` +- [Node.js]() installed on your machine +- a [PostgreSQL]() database server running and a database with at least one table + + + + + +- an existing Node.js (version 10 or higher) project with a `package.json` +- [Node.js]() installed on your machine +- a [MySQL]() database server running and a database with at least one table + + + + + +- an existing Node.js (version 10 or higher) project with a `package.json` +- [Node.js]() installed on your machine +- a [MySQL]() database server running and a database with at least one table + + + + + - an existing Node.js (version 10 or higher) project with a `package.json` - [Node.js]() installed on your machine - a [PostgreSQL]() database server running and a database with at least one table + + Make sure your have your database [connection URL]() (includes your authentication credentials) at hand! If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](). ## Setup Prisma -As a first step, navigate into it your project direcctory that contains the `package.json`. +As a first step, navigate into it your project directory that contains the `package.json`. Next, add the Prisma CLI as a development dependency in your project: @@ -51,6 +91,8 @@ This command created a new directory called `prisma` with the following contents To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](): + + ```prisma datasource postgresql { provider = "postgresql" @@ -61,7 +103,7 @@ datasource postgresql { In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: ``` -DATABASE_URL="postgresql://johndoe:johndoe@localhost:5432/mydb?schema=public" +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" ``` You now need to adjust the connection URL to point to your own database. @@ -82,7 +124,7 @@ Here's a short explanation of each component: If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. -As an example, for a PostgreSQL database hosted on Heroku, the [connection string](./core/connectors/postgresql.md#connection-string) might look similar to this: +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: ``` DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" @@ -94,9 +136,166 @@ When running PostgreSQL locally, your user and password as well as the database DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" ``` + + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: + +``` +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): + +``` +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) +- `DATABASE`: The name of the [database]() +- `SCHEMA`: The name of the [schema]() inside the database + +If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. + +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: + +``` +DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" +``` + +When running PostgreSQL locally, your user and password as well as the database name typically correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: + +``` +DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" +``` + + + + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma +datasource mysql { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: + +``` +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): + +``` +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database]() + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: + +``` +DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +``` +DATABASE_URL="postgresql://root:randompassword@localhost:3306/mydb" +``` + + + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma +datasource mysql { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: + +``` +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): + +``` +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database]() + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: + +``` +DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +``` +DATABASE_URL="postgresql://root:randompassword@localhost:3306/mydb" +``` + + + + ## Introspect your database with Prisma -For the purpose of this guide, we'll use a demo SQL schemas with three tables: +For the purpose of this guide, we'll use a demo SQL schema with three tables: ```sql copy CREATE TABLE "public"."User" ( @@ -123,7 +322,7 @@ CREATE TABLE "public"."Profile" ( ); ``` -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes are used, PostgreSQL would just read everything as _lowercase_ characters. +> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters.
    Expand for a graphical overview of the tables diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index 486ee77106..b47bcb5c07 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -131,7 +131,7 @@ CREATE TABLE "public"."Profile" ( ); ``` -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes are used, PostgreSQL would just read everything as _lowercase_ characters. +> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. You can create the tables using any PostgreSQL client of your choice. If you're using `psql`, you can now create the tables using the following command: diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx index 595d3f529b..6df75cbdaf 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx @@ -12,7 +12,7 @@ Since Prisma Client is not only based on JavaScript code, but also relies on the To do so, you can use plugins that let you copy over static assets: -| Bundler | Plugin | -| :------ | :-------------------------------------------------------------------------------------------------- | -| Webpack | [`copy-webpack-plugin`](https://github.com/webpack-contrib/copy-webpack-plugin#copy-webpack-plugin) | -| Parcel | [`parcel-plugin-static-fil | +| Bundler | Plugin | +| :------ | :------------------------------------------------------------------------------------------------------ | +| Webpack | [`copy-webpack-plugin`](https://github.com/webpack-contrib/copy-webpack-plugin#copy-webpack-plugin) | +| Parcel | [`parcel-plugin-static-files-copy`](https://github.com/elwin013/parcel-plugin-static-files-copy#readme) | diff --git a/content/index.mdx b/content/index.mdx index 36b07fec33..8c8798d690 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -21,6 +21,8 @@ The **Getting started** section contains _practical guides_ to help you get star - [Add Prisma to an existing project]() - [Start from scratch (SQL migrations)]() +--- + ### Understand Prisma The **Understand Prisma** section contains _conceptual_ information about Prisma. @@ -34,6 +36,8 @@ The **Understand Prisma** section contains _conceptual_ information about Prisma - [Data modeling]() - [Under the hood]() +--- + ### Reference The **Reference** section contains _technical_ information about Prisma. @@ -81,6 +85,8 @@ The **Reference** section contains _technical_ information about Prisma. - [Editor setup]() - [Telemetry]() +--- + ### Guides The **Reference** section contains _step-by-step tutorials_ on various topics. @@ -99,6 +105,8 @@ The **Reference** section contains _step-by-step tutorials_ on various topics. - [Deploying to Netlify]() +--- + ### More The **More** section contains _meta information_ about Prisma and the documentation itself. From a23e07adb99027d1e27e83d63f74de0180a5b172 Mon Sep 17 00:00:00 2001 From: Nilu Date: Fri, 27 Mar 2020 19:53:54 +0100 Subject: [PATCH 21/76] Added '*' to tech switcher + changed mongodb to sqlite --- content/01-getting-started/04-example.mdx | 48 +++++++++++++++++------ src/components/techSwitcher.tsx | 8 ++-- src/components/topSection.tsx | 31 ++++++++++++--- 3 files changed, 66 insertions(+), 21 deletions(-) diff --git a/content/01-getting-started/04-example.mdx b/content/01-getting-started/04-example.mdx index c820121034..f532246028 100644 --- a/content/01-getting-started/04-example.mdx +++ b/content/01-getting-started/04-example.mdx @@ -12,9 +12,9 @@ dbSwitcher: true This page won't be shown in sidebar. For now, h2 tags cannot be written inside `SwitchTech` block. But still can include headings using `

    ,

    ` tags and not using `### headings`. `

    ` tags wont be shown in TOC yet. - + -

    Node Mysql

    +

    JS *

    ```js js @@ -24,24 +24,50 @@ psql -h localhost -d hello-prisma -U janedoe -f schema.sql
    - + -

    node postgres

    +

    TS *

    -```go -go +```js +js psql -h localhost -d hello-prisma -U janedoe -f schema.sql ``` +
    - + -

    TS Mongodb

    +

    * MYSQL

    -```ts -ts +```js +js psql -h localhost -d hello-prisma -U janedoe -f schema.sql ``` -
    \ No newline at end of file + +
    + + + +

    * SQLite

    + +```js +js +psql -h localhost -d hello-prisma -U janedoe -f schema.sql +``` + + +
    + + + +

    * Postgres

    + +```js +js +psql -h localhost -d hello-prisma -U janedoe -f schema.sql +``` + + +
    diff --git a/src/components/techSwitcher.tsx b/src/components/techSwitcher.tsx index 2af3a192a6..7561a9e520 100644 --- a/src/components/techSwitcher.tsx +++ b/src/components/techSwitcher.tsx @@ -4,7 +4,7 @@ import { Typescript } from '../icons/technologies/Typescript'; import SelectComponent from './select'; import PostgreSQL from '../icons/technologies/PostgreSQL'; import MySQL from '../icons/technologies/MySQL'; -import MongoDB from '../icons/technologies/MongoDB'; +import MongoDB from '../icons/technologies/MongoDB'; // change icon as soon as we have it import JS from '../icons/technologies/JS'; interface TechSwitchProps { @@ -21,12 +21,12 @@ const icons = { typescript: , mysql: , postgres: , - mongodb: , + sqlite: , // change icon as soon as we have it }; const technologyTypes = { languages: ['node', 'typescript'], - databases: ['mysql', 'postgres', 'mongodb'], + databases: ['mysql', 'postgres', 'sqlite'], }; export const technologyNames = { @@ -34,7 +34,7 @@ export const technologyNames = { typescript: 'TypeScript', mysql: 'MySQL', postgres: 'PostgreSQL', - mongodb: 'MongoDB', + sqlite: 'SQLite', }; const TechnologySwitch = ({ type, onChangeTech }: TechSwitchProps) => { diff --git a/src/components/topSection.tsx b/src/components/topSection.tsx index 2a9891e5fe..d1e9f5d97f 100644 --- a/src/components/topSection.tsx +++ b/src/components/topSection.tsx @@ -38,18 +38,37 @@ const TopSection = ({ location, title, parentTitle, indexPage, langSwitcher, dbS const [langSelected, setLangSelected] = React.useState('typescript'); const [dbSelected, setDbSelected] = React.useState('postgres'); + // TODO : Simplify the function! const techChanged = (item: any, type: string) => { const elements = document.querySelectorAll('[id^="techswitch"]'); elements.forEach((element: any) => element.classList.remove('show')); const elemToShow = [].slice.call(elements).filter((elm: any) => { if (type === 'lang') { - return dbSwitcher - ? elm.id.includes(`-${item.technology}`) && elm.id.includes(`-${dbSelected}`) - : elm.id.includes(`-${item.technology}`); + if (dbSwitcher) { + if (elm.id.includes('-*-')) { // lang is any + return elm.id.includes(`-${dbSelected}`); + } else { + return ( + elm.id.includes(`-${item.technology}`) && + (elm.id.includes(`-${dbSelected}`) || elm.id.includes(`-*`)) + ); + } + } else { + return elm.id.includes(`-${item.technology}`); + } } else if (type === 'db') { - return langSwitcher - ? elm.id.includes(`-${item.technology}`) && elm.id.includes(`-${langSelected}`) - : elm.id.includes(`-${item.technology}`); + if (langSwitcher) { + if (elm.id.slice(-1) === '*') { // db is any + return elm.id.includes(`-${langSelected}`); + } else { + return ( + elm.id.includes(`-${item.technology}`) && + (elm.id.includes(`-${langSelected}`) || elm.id.includes(`-*`)) + ); + } + } else { + return elm.id.includes(`-${item.technology}`); + } } }); elemToShow && elemToShow.forEach((eShow: any) => eShow.classList.add('show')); From c704ea522df37d0a791b7f4c651c9835b6660ef1 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 20:02:23 +0100 Subject: [PATCH 22/76] start new relation syntax --- .../01-prisma-schema/04-data-model.mdx | 10 ++++------ .../01-prisma-schema/06-relations.mdx | 6 ++++-- .../05-foreign-keys/01-postgresql.mdx | 2 -- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index 4e6b1d51e6..d5a2f67014 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -57,14 +57,16 @@ model User { model Profile { id Int @id @default(autoincrement()) - user User + user User @relation(fields: [userId], references: [id]) + userId Int bio String } model Post { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) - author User + author User @relation(fields: [authorId], references: [id]) + authorId Int title String published Boolean @default(false) categories Category[] @@ -76,10 +78,6 @@ model Category { posts Post[] } -enum Role { - USER ADMIN -} - enum Role { USER ADMIN diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 223be53f1c..f6b378b03c 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -8,7 +8,9 @@ metaDescription: '' This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. -Relations between models are represented via foreign keys in the underlying database. However, as opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. This means that one of these relation fields represents the foreign key in the underlying database, the other relation field is a [virtual relation field]() (in the case of [implicit many-to-many relations]()), both relation fields are virtual. +Relations between models are represented via _foreign keys_ in the underlying database. However, as opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. + +This means that one of these relation fields represents the foreign key in the underlying database, the other relation field is a [virtual relation field]() (in the case of [implicit many-to-many relations]()), both relation fields are virtual. ## Example @@ -47,7 +49,7 @@ model Category { } ``` -> **Note**. This schema is the same as the [example data model](./data-modeling.md/#example) but has all [scalar fields](./data-modeling.md/#scalar-types) removed so you can focus on the relation fields. +> **Note**. This schema is the same as the [example data model]() but has all [scalar fields]() removed so you can focus on the relation fields. ## Terminology diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx index 752cdb555c..0f1621a4e8 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx @@ -267,5 +267,3 @@ Run the code with this command: ``` node index.js ``` - -> TODO: The code above did not work at the time of writing this. Needs to be validated once AUMFIDAR is fully finished. From 6cc181ce8ef2dd69900e70368260ce9e62be98d5 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 22:28:05 +0100 Subject: [PATCH 23/76] relations update --- .../01-add-to-an-existing-project.mdx | 20 +- .../01-prisma-schema/04-data-model.mdx | 12 +- .../01-prisma-schema/06-relations.mdx | 221 +++++++++--------- content/index.mdx | 2 +- 4 files changed, 116 insertions(+), 139 deletions(-) diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index 9a6415f131..8efbf03899 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -24,7 +24,7 @@ This page walks you through the process of adding Prisma to a **Node.js** projec In order to successfully complete this guide, you need: - + - an existing Node.js (version 10 or higher) project with a `package.json` - [Node.js]() installed on your machine @@ -32,15 +32,7 @@ In order to successfully complete this guide, you need: - - -- an existing Node.js (version 10 or higher) project with a `package.json` -- [Node.js]() installed on your machine -- a [MySQL]() database server running and a database with at least one table - - - - + - an existing Node.js (version 10 or higher) project with a `package.json` - [Node.js]() installed on your machine @@ -48,14 +40,6 @@ In order to successfully complete this guide, you need: - - -- an existing Node.js (version 10 or higher) project with a `package.json` -- [Node.js]() installed on your machine -- a [PostgreSQL]() database server running and a database with at least one table - - - Make sure your have your database [connection URL]() (includes your authentication credentials) at hand! If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](). diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index d5a2f67014..b4519b9e3d 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -56,19 +56,19 @@ model User { } model Profile { - id Int @id @default(autoincrement()) - user User @relation(fields: [userId], references: [id]) - userId Int - bio String + id Int @id @default(autoincrement()) + bio String + user User @relation(fields: [userId], references: [id]) + userId Int } model Post { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) - author User @relation(fields: [authorId], references: [id]) - authorId Int title String published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int categories Category[] } diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index f6b378b03c..9e88697992 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -8,48 +8,43 @@ metaDescription: '' This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. -Relations between models are represented via _foreign keys_ in the underlying database. However, as opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. +Relations between models are _physically_ represented via _foreign keys_ in the underlying database. However, as opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. -This means that one of these relation fields represents the foreign key in the underlying database, the other relation field is a [virtual relation field]() (in the case of [implicit many-to-many relations]()), both relation fields are virtual. +This means that one of these relation fields represents the physical foreign key in the underlying database, the other relation field is a [virtual relation field]() (in the case of [implicit many-to-many relations]()), both relation fields are virtual. + +The physical relation field must always be accompanied by a [link field]() on the same model. ## Example The examples on this page are based on the following schema file: ```prisma -datasource postgresql { - provider = "postgresql" - url = env("DATABASE_URL") -} - -generator client { - provider = "prisma-client-js" -} - model User { - id Int @id @default(autoincrement()) - posts Post[] - profile Profile? + id Int @id @default(autoincrement()) + posts Post[] // virtual relation field + profile Profile? // virtual relation field } model Profile { - id Int @id @default(autoincrement()) - user User + id Int @id @default(autoincrement()) + user User @relation(fields: [userId], references: [id]) // physical relation field + userId Int // link field } model Post { - id Int @id @default(autoincrement()) - author User - categories Category[] + id Int @id @default(autoincrement()) + author User @relation(fields: [authorId], references: [id]) // physical relation field + authorId Int // link field + categories Category[] // virtual relation field } model Category { - id Int @id @default(autoincrement()) - posts Post[] + id Int @id @default(autoincrement()) + posts Post[] // virtual relation field } ``` -> **Note**. This schema is the same as the [example data model]() but has all [scalar fields]() removed so you can focus on the relation fields. +> **Note**. This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [link fields]()) so you can focus on the relation fields. ## Terminology @@ -69,7 +64,11 @@ In the example above, there are the following relations: ### Relation fields -Relation fields are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. Consider these two models: +Relation fields are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. + +A relation field is always either [physically]() backed by a foreign key in the underlying database or it is [virtual]() (which means that it's not "visible" in the schema of the underlying database). + +Consider these two models: ```prisma model User { @@ -80,27 +79,29 @@ model User { } model Post { - id Int @id @default(autoincrement()) + id Int @id @default(autoincrement()) title String - author User + author User @relation(fields: [authorId], references: [id]) + authorId Int } ``` These models have the following fields: -| Model | Field | Type | Relation field | -| :----- | :------- | :------- | :-------------------- | -| `User` | `id` | `Int` | No | -| | `email` | `String` | No | -| | `role` | `Role` | No | -| | `posts` | `Post[]` | **Yes** (virtual) | -| `Post` | `id` | `Int` | No | -| | `title` | `String` | No | -| | `author` | `User` | **Yes** (foreign key) | +| Model | Field | Type | Relation field | +| :----- | :--------- | :------- | :--------------------------------- | +| `User` | `id` | `Int` | No | +| | `email` | `String` | No | +| | `role` | `Role` | No | +| | `posts` | `Post[]` | **Yes** (_virtual_) | +| `Post` | `id` | `Int` | No | +| | `title` | `String` | No | +| | `authorId` | `Int` | No (_link field_) | +| | `author` | `User` | **Yes** (_physical / foreign key_) | Both `posts` and `author` are relation fields because their types are not scalar types but other models. -Note that a relation field is always either backed by a foreign key in the underlying database or it is [virtual]() (which means that it's not "visible" in the schema of the underlying database). +Also note that the physical relation field `author` needs to reference the link field `authorId` on the `Post` model inside the `@relation` attribute. ### Implicit vs explicit many-to-many relations @@ -183,9 +184,36 @@ In this example, the `createdAt` field stores additional information about the r When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but get your data model from introspection, you can s -### Foreign key relation field +### Physical relation fields (foreign key) + +Physical relation relation fields are relation fields that are _physically_ backed by a foreign key in the underlying database. **They always require the `@relation attribute which must point to a link field**. -Foreign key relation fields are relation fields that are backed by a foreign key in the underlying database. **They always require the `@relation attribute**. +### Link fields + +A link field always has a scalar type and is the direct representation of a foreign key in the underlying database. It must be _referenced_ inside the `@relation` attribute of its physical relation field: + +```prisma +model User { + id Int @id @default(autoincrement()) + posts Post[] // virtual relation field + profile Profile? // virtual relation field +} + +model Profile { + id Int @id @default(autoincrement()) + user User @relation(fields: [userId], references: [id]) // physical relation field + userId Int // link field (that gets referenced in the `@relation` attribute above) +} + +model Post { + id Int @id @default(autoincrement()) + author User @relation(fields: [authorId], references: [id]) // physical relation field + authorId Int // link field (that gets referenced in the `@relation` attribute above) + categories Category[] // virtual relation field +} +``` + +Note that if the physical relation field is [required](), its link field counterpart also must be required. If the physical relation field is [optional](), the link field also must be optional. ### Virtual relation fields @@ -193,9 +221,11 @@ Virtual relation fields are relation fields in the Prisma schema that are not "m There are two different kinds of virtual relation fields. -For **1-1 and 1-n relations**, pne side of the relation represents a foreign key, the other side is a virtual relation field: +For **1-1 and 1-n relations**, one side of the relation represents a foreign key, the other side is a virtual relation field: -![](https://imgur.com/kOO4eh2.png) + + +![](https://imgur.com/nycymr8.png) For **implicit m-n-relations**, both relation fields are virtual since neither of them _directly_ maps to a foreign key: @@ -215,29 +245,34 @@ const user = await prisma.user.findOne({ where: { id: 1 } }).posts(); ## The @relation attribute -The `@relation` attribute can only be applied to the [relation fields]() of a Prisma model, not to its [scalar fields](). In most cases the `@relation` attribute is optional, but it can be required, e.g. when: +The `@relation` attribute can only be applied to the [relation fields]() of a Prisma model, not to its [scalar fields](). + +It is _always_ required on [physical relation fields]() and _sometimes_ required on [virtual relation fields](). + +Here are some cases when the `@relation` attribute is required, e.g. when: - you need to disambiguate a relation (that's e.g. the case when you have two relations between the same models) - you define a [self-relation](#self-relations) -- you need to determine on which side of the relation a foreign key should be used + - you need to control how the relation table is represented in the underlying database (e.g. use a specific name for a relation table) ### Signature ``` -@relation(_ name: String?, references: FieldReference[]?) +@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?) ``` > **Note**: The leading underscore in the signature means that the argument name can be omitted. -| Argument | Type | Required | Description | Example | -| :----------- | :----------------- | :------- | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------- | -| `name` | `String` | No | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | -| `references` | `FieldReference[]` | No | A list of [fields]() | `["id"]`, `["firstName, lastName"]` | +| Argument | Type | Required | Description | Example | +| :----------- | :----------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | +| `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | +| `fields` | `FieldReference[]` | On physical relation fields | A list of [fields]() of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | +| `references` | `FieldReference[]` | On physical relation fields | A list of [fields]() of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | -### Cases when the @relation attribute is required + ## One-to-one relations @@ -254,8 +289,9 @@ model User { } model Profile { - id Int @id @default(autoincrement()) - user User + id Int @id @default(autoincrement()) + user User @relation(fields: [userId], references: [id]) + userId Int } ``` @@ -272,12 +308,14 @@ CREATE TABLE "User" ( ); CREATE TABLE "Profile" ( id SERIAL PRIMARY KEY, - "user" integer NOT NULL UNIQUE, + "userId" INTEGER NOT NULL UNIQUE, FOREIGN KEY ("user") REFERENCES "User"(id) ); ``` -Notice the `UNIQUE` constraint on the foreign key `user`. If this `UNIQUE` constrain was missing, the relation would be considered a 1-n relation. +Notice the `UNIQUE` constraint on the foreign key `userId`. If this `UNIQUE` constrain was missing, the relation would be considered a 1-n relation. + +The link field `userId` on `Profile` model in the Prisma schema above maps to the `userId` column in the database. ### Making both sides required in one-to-one relations @@ -291,9 +329,9 @@ model User { } model Profile { - id Int @id @default(autoincrement()) - bio String - user User + id Int @id @default(autoincrement()) + user User @relation(fields: [userId], references: [id]) + userId Int } ``` @@ -340,66 +378,36 @@ If you're using [introspection](), you can make 1-1-relations required by manual Consider again the above 1-1-relation between `User` and `Profile` where `profile` is optional on `User`: -```prisma -model User { - id Int @id @default(autoincrement()) - profile Profile? -} - -model Profile { - id Int @id @default(autoincrement()) - user User -} -``` - -When using [Prisma Migrate](), this will create the foreign key on the `user` column of the `Profile` table in the underlying database. This is the only possible option because the `profile` relation field on `User` is actually [virtual](), so it can't be used as a foreign key. - -This is what the relation looks like in the database: - -![](https://imgur.com/N5wHT6D.png) - -If both of the relation fields in the relation would be either required or optional, Prisma Migrate assigns the foreign key to the table that comes first in the alphabet. - -**Both relation fields required** - ```prisma model User { id Int @id @default(autoincrement()) + name String profile Profile } model Profile { - id Int @id @default(autoincrement()) - user User + id Int @id @default(autoincrement()) + user User @relation(fields: [userId], references: [id]) + userId Int } ``` -**Both relation fields optional** +Because the `Profile` model has a [physical relation field]() (called `user`) and a [link field]() (called `userId`), it represents the foreign key in the underlying database. The `profile` relation field on `User` is [virtual](). -```prisma -model User { - id Int @id @default(autoincrement()) - profile Profile? -} - -model Profile { - id Int @id @default(autoincrement()) - user User? -} -``` - -In both cases, the foreign key is being added to the `Profile` table because its name comes in the alphabet before `User`: +This is what the relation looks like in the database: ![](https://imgur.com/N5wHT6D.png) -However, in these cases you can still determine yourself on which side of the relation the foreign key should be stored by using the `@relation` attribute. To store the foreign key on `User` you need to add the `@relation` attribute to its relation field as follows: + +However, you can still determine yourself on which side of the relation the foreign key should be stored. To store the foreign key on `User` you need to add the `@relation` attribute to its relation field and add a corresponding link field: **Both relation fields required but using `@relation` to determine the foreign key** ```prisma model User { - id Int @id @default(autoincrement()) - profile Profile @relation(references: [id]) // references `id` of `Profile` + id Int @id @default(autoincrement()) + profile Profile @relation(fields: [profileId], references: [id]) // references `id` of `Profile` + profileId Int } model Profile { @@ -413,7 +421,7 @@ model Profile { ```prisma model User { id Int @id @default(autoincrement()) - profile Profile? @relation(references: [id]) // references `id` of `Profile` + profile Profile? @relation(fields: [profileId], references: [id]) // references `id` of `Profile` } model Profile { @@ -426,21 +434,6 @@ In both cases, the foreign key is now defined on the `profile` column of the `Us ![](https://imgur.com/NAd72ql.png) -To summarize, these are the rules for determining which side of a 1-1-relation holds the foreign key: - -- If **one relation field is optional and the other one is required**, the required one holds the foreign key (as the other is [virtual]()). -- If **both relation fields are optional**, the one that comes first in the alphabet holds the foreign key. Note that this can be configured differently via the `@relation` attribute. -- If **both relation fields are required**, the one that comes first in the alphabet holds the foreign key. Note that this can be configured differently via the `@relation` attribute. - -Here's the summary in the form of a table assuming the two relation fields of the models from before `Profile.user` and `User.profile`: - -| `Profile.user` | `User.profile` | Foreign key on | `@relation` attribute | -| :------------- | :------------- | ----------------------------------------------------------- | ------------------------------------------------- | -| Required | Optional | `Profile` (because the relation field on `User` is virtual) | Can't be used to determine the foreign key | -| Optional | Required | `User` (because the relation field on `Profile` is virtual) | Can't be used to determine the foreign key | -| Optional | Optional | `Profile` (because it's first in the alphabet) | Can be used to manually determine the foreign key | -| Required | Required | `Profile` (because it's first in the alphabet) | Can be used to manually determine the foreign key | - ## One-to-many One-to-many (1-n) relations refer to relations where one record on one side of the relation can be connected to zero or more records on the other side. @@ -489,11 +482,11 @@ Since there's no `UNIQUE` constraint on the `author` column (foreign key), you c ### Required vs optional relation fields in one-to-many relations -A 1-n-relation always has one [virtual relation field]() (which must be a [list]()) and a [foreign key relation field](). In the example above, `posts Post[]` on the `User` model is virtual, `author User` holds a foreign key. +A 1-n-relation always has one [virtual relation field]() (which must be a [list]()) and a [physical relation field](). In the example above, `posts Post[]` on the `User` model is virtual, `author User` holds a foreign key. The relation fields in a relation can take the following forms: -- the foreign key relation field can be either optional or required +- the physical relation field can be either optional or required - the virtual relation field must be a list and is always required So, the following variant of the example above would be _allowed_: diff --git a/content/index.mdx b/content/index.mdx index 20fb1965c0..a2cb79611c 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -89,7 +89,7 @@ The **Reference** section contains _technical_ information about Prisma. ### Guides -The **Reference** section contains _step-by-step tutorials_ on various topics. +The **Guides** section contains _step-by-step tutorials_ on various topics. - Database workflows - [Setting up a database]() From d046350674d3499af76e5fee070a8bced0dbbcc4 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 22:38:42 +0100 Subject: [PATCH 24/76] relations update --- .../01-prisma-schema/06-relations.mdx | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 9e88697992..bc70574ffa 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -309,7 +309,7 @@ CREATE TABLE "User" ( CREATE TABLE "Profile" ( id SERIAL PRIMARY KEY, "userId" INTEGER NOT NULL UNIQUE, - FOREIGN KEY ("user") REFERENCES "User"(id) + FOREIGN KEY ("useIdr") REFERENCES "User"(id) ); ``` @@ -453,12 +453,13 @@ model User { } model Post { - id Int @id @default(autoincrement()) - author User + id Int @id @default(autoincrement()) + author User @relation(fields: [authorId], references: [author]) + authorId Int } ``` -Notice that the `posts` field on `User` is [virtual](), meaning that it's not manifested in the underlying database schema. +Notice that the `posts` field on `User` is [virtual](), meaning that it's not manifested in the underlying database schema. On the other side of the relation, the [physical relation field]() `author` and the [link field]() `authorId` represent the foreign key in the underlying database. This 1-n-relation expresses the following: @@ -473,8 +474,8 @@ CREATE TABLE "User" ( ); CREATE TABLE "Post" ( id SERIAL PRIMARY KEY, - author integer NOT NULL, - FOREIGN KEY (author) REFERENCES "User"(id) + "authorId" integer NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "User"(id) ); ``` @@ -482,11 +483,13 @@ Since there's no `UNIQUE` constraint on the `author` column (foreign key), you c ### Required vs optional relation fields in one-to-many relations -A 1-n-relation always has one [virtual relation field]() (which must be a [list]()) and a [physical relation field](). In the example above, `posts Post[]` on the `User` model is virtual, `author User` holds a foreign key. +A 1-n-relation always has one [virtual relation field]() (which must be a [list]()) and a [physical relation field]() that references a [link field](). In the example above, `posts` on the `User` model is virtual, `author` represents a foreign key and `authorId` is a link field. The relation fields in a relation can take the following forms: - the physical relation field can be either optional or required +- if the physical relation field is required, the link field must be required +- if the physical relation field is optional, the link field must be optional - the virtual relation field must be a list and is always required So, the following variant of the example above would be _allowed_: @@ -498,8 +501,9 @@ model User { } model Post { - id Int @id @default(autoincrement()) - author User? // make `author` optional + id Int @id @default(autoincrement()) + author User? @relation(fields: [authorId], references: [author]) + authorId Int? } ``` @@ -512,8 +516,10 @@ model User { } model Post { - id Int @id @default(autoincrement()) - author User + id Int @id @default(autoincrement()) + author User? @relation(fields: [authorId], references: [author]) + authorId Int? + } ``` From 2d4e973aefaa0c5ab89ebaace4cdcd77c568c426 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Fri, 27 Mar 2020 23:37:42 +0100 Subject: [PATCH 25/76] relations update --- .../01-prisma-schema/06-relations.mdx | 104 ++++++++++++------ 1 file changed, 69 insertions(+), 35 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index bc70574ffa..ed4d833454 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -35,16 +35,16 @@ model Post { id Int @id @default(autoincrement()) author User @relation(fields: [authorId], references: [id]) // physical relation field authorId Int // link field - categories Category[] // virtual relation field + categories Category[] @relation(references: [id]) // virtual relation field } model Category { id Int @id @default(autoincrement()) - posts Post[] // virtual relation field + posts Post[] @relation(references: [id]) // virtual relation field } ``` -> **Note**. This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [link fields]()) so you can focus on the relation fields. +> **Note**: This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [link fields]()) so you can focus on the relation fields. ## Terminology @@ -136,16 +136,18 @@ Implicit many-to-many relations define relation fields as lists on both sides of ```prisma model Post { - id Int @id @default(autoincrement()) - categories Category[] + id Int @id @default(autoincrement()) + categories Category[] @relation(references: [id]) } model Category { - id Int @id @default(autoincrement()) - posts Post[] + id Int @id @default(autoincrement()) + posts Post[] @relation(references: [id]) } ``` +Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. + Note that this m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). @@ -154,34 +156,43 @@ If you're not using Prisma Migrate but obtain your data model from [introspectio A relation table (also sometimes called _JOIN_, _link_ or _pivot_ table) connects two or more other tables and therefore creates a _relation_ between them. Creating relation tables is a common data modeling practice in SQL to represent relationships between different entities. -When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both relation fields that are backed by foreign keys (neither of them is virtual). +When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both relation fields are both [physical relation fields]() that each _reference_ a link field. -Another use case for relation tables is to add "meta-information" to a relation. For example, _when_ the relation was created. +Relation tables are also often used to add "meta-information" to a relation. For example, _when_ the relation was created. Here is an example for a relation table called `CategoriesOnPosts`: ```prisma model Post { id Int @id @default(autoincrement()) + title String categories Category[] } model Category { id Int @id @default(autoincrement()) + name String posts Post[] } model CategoriesOnPosts { - post Post - category Category - createdAt DateTime @default(now()) + post Post @relation(fields: [postId], references: [id]) + postId Int + category Category @relation(fields: [catgoryId], references: [id]) + catgoryId Int + createdAt DateTime @default(now()) - @@id([post, category]) + @@id([postId, categoryId]) } ``` In this example, the `createdAt` field stores additional information about the relation between `Post` and `Category` (i.e. it stores the point in time when "the post was added to the catgegory"). +Note that the same rules as for [1-n-relations]() apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations): + +- The relation field on one side must be [virtual]() (here these are `posts` and `categories`) +- The relation field on the other side must be [physical]() and _reference_ a [link field]() + When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but get your data model from introspection, you can s ### Physical relation fields (foreign key) @@ -534,25 +545,44 @@ In the example above, there's one _implicit_ m-n-relation betwen `Post` and `Cat ```prisma model Post { id Int @id @default(autoincrement()) - categories Category[] + categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] + posts Post[] @relation(references: [id]) } ``` -Notice that the `posts` field on `Category` and the `categories` field on `Post` both are [virtual](), meaning that they're not manifested in the underlying database schema. +Notice that the `posts` field on `Category` and the `categories` field on `Post` both are [virtual](), meaning that they're not manifested in the underlying database schema. Instead, the implicit many-to-many relation is maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. + +Both fields require the `@relation` attribute to specify the fields they _reference_ on the other model. -Instead, the implicit many-to-many relation is maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. +As another example, assume `Category` had a [multi-field ID](): + +```prisma +model Post { + id Int @id @default(autoincrement()) + categories Category[] @relation(references: [name, position]) +} + +model Category { + name String + position Int + posts Post[] @relation(references: [id]) + + @@id([name, position]) +} +``` This m-n-relation expresses the following: - "a post can have zero or more categories" - "a category can have zero or more posts" -In SQL, this implicit m-n-relation maps to the following tables (following Prisma's [conventions for relation tables]()): +The `@relation` attribute on the `Post` model now references the multi-field ID composed of `name` and `position`. + +In SQL, the first of the two implicit m-n-relations maps to the following tables (following Prisma's [conventions for relation tables]()): ```sql CREATE TABLE "Category" ( @@ -575,22 +605,26 @@ CREATE INDEX "_CategoryToPost_B_index" ON "_CategoryToPost"("B" int4_ops); An _explicit_ variant of a similar m-n-relation would define an extra model to represent a relation table. In this case, you can also attach additional information to the relation (such as the point in time when it was created): ```prisma -model Category { - id Int @default(autoincrement()) @id - categoryToPost CategoryToPost[] +model Post { + id Int @id @default(autoincrement()) + title String + categories Category[] } -model Post { - id Int @default(autoincrement()) @id - categoryToPost CategoryToPost[] +model Category { + id Int @id @default(autoincrement()) + name String + posts Post[] } -model CategoryToPost { - category Category - post Post - createdAt DateTime @default(now()) +model CategoriesOnPosts { + post Post @relation(fields: [postId], references: [id]) + postId Int + category Category @relation(fields: [catgoryId], references: [id]) + catgoryId Int + createdAt DateTime @default(now()) - @@unique([category, post], name: "CategoryToPost_category_post_unique") + @@id([postId, categoryId]) } ``` @@ -605,11 +639,11 @@ CREATE TABLE "Post" ( ); -- Relation table + indexes ------------------------------------------------------- CREATE TABLE "CategoryToPost" ( - "category" integer NOT NULL, - "post" integer NOT NULL, + "categoryId" integer NOT NULL, + "postId" integer NOT NULL, "createdAt" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY ("category") REFERENCES "Category"(id), - FOREIGN KEY ("post") REFERENCES "Post"(id) + FOREIGN KEY ("categoryId") REFERENCES "Category"(id), + FOREIGN KEY ("postId") REFERENCES "Post"(id) ); CREATE UNIQUE INDEX "CategoryToPost_category_post_unique" ON "CategoryToPost"("category" int4_ops,"post" int4_ops); ``` @@ -671,12 +705,12 @@ When using Prisma Migrate, you can configure the name of the relation table that ```prisma model Post { id Int @id @default(autoincrement()) - categories Category[] @relation("MyRelationTable") + categories Category[] @relation("MyRelationTable", references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] @relation("MyRelationTable") + posts Post[] @relation("MyRelationTable", references: [id]) } ``` From 2b73996dcb73f4572ef6e209660e3cfd535af25c Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 00:13:57 +0100 Subject: [PATCH 26/76] relations update --- .../01-prisma-schema/06-relations.mdx | 93 ++++++++++++++----- 1 file changed, 69 insertions(+), 24 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index ed4d833454..0b1412fba1 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -726,13 +726,14 @@ A one-to-one self-relation looks as follows: ```prisma model User { - id Int @id @default(autoincrement()) - name String? - husband User? @relation("MarriagePartners") - wife User @relation("MarriagePartners") + id Int @id @default(autoincrement()) + name String? + husband User @relation("MarriagePartners", fields: [id], references: [id]) + wife User? @relation("MarriagePartners") } ``` + This relation expresses the following: - "a user has zero or one _husband_ " @@ -740,18 +741,37 @@ This relation expresses the following: Note that one-to-one self-relations can not be made required on both sides, one field has to be optional. -In this case, the `wife` relation field is [virtual](). The `husband` field on the other hand is backed by a foreign key in the underlying database. This is implicitly determined by Prisma based on alphabetical order (`husband` comes before `wife` in the alphabet). You can adjust this by [setting the foreign key]() using the `@relation` attribute: +In this case, the `wife` relation field is [virtual](). The `husband` field on the other hand is a [physical relation field](), this means it is backed by a foreign key in the underlying database. Here, `id` is the [link field]() that's referenced by `husband`. + +You can also switch the virtual and physical relation fields: + +```prisma +model User { + id Int @id @default(autoincrement()) + name String? + husband User @relation("MarriagePartners", fields: [id], references: [id]) + wife User? @relation("MarriagePartners") +} +``` ```prisma model User { id Int @id @default(autoincrement()) name String? husband User? @relation("MarriagePartners") - wife User @relation("MarriagePartners", references: [id]) + wife User @relation("MarriagePartners", fields: [id], references: [id]) } ``` -Now the foreign key is stored on `wide` and `husband` is virtual. +Now the foreign key is stored on `wife` and `husband` is virtual. + +This relation is represented as follows in SQL: + +```sql +CREATE TABLE "User" ( + id SERIAL PRIMARY KEY REFERENCES "User"(id), +); +``` ### One-to-many self relations @@ -761,7 +781,7 @@ A one-to-many self-relation looks as follows: model User { id Int @id @default(autoincrement()) name String? - teacher User? @relation("TeacherStudents") + teacher User @relation("TeacherStudents", fields: [id], references: [id]) students User[] @relation("TeacherStudents") } ``` @@ -773,6 +793,14 @@ This relation expresses the following: Note that you can also require each user to have a teacher by making the `teacher` field [required](). +This relation is represented as follows in SQL: + +```sql +CREATE TABLE "User" ( + id SERIAL PRIMARY KEY REFERENCES "User"(id), +); +``` + ### Many-to-many self relations A many-to-many self-relation looks as follows: @@ -781,8 +809,8 @@ A many-to-many self-relation looks as follows: model User { id Int @id @default(autoincrement()) name String? - followedBy User[] @relation("UserFollows") - following User[] @relation("UserFollows") + followedBy User[] @relation("UserFollows", references: [id]) + following User[] @relation("UserFollows", references: [id]) } ``` @@ -791,6 +819,19 @@ This relation expresses the following: - "a user can be followed by zero or more users" - "a user can follow zero or more users" +Note that this n-n-relation is [implicit](). This means Prisma maintains a [relation table]() for it in the underlying database: + +```sql +CREATE TABLE "User" ( + id integer DEFAULT nextval('"User_id_seq"'::regclass) PRIMARY KEY, + name text +); +CREATE TABLE "_UserFollows" ( + "A" integer NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE, + "B" integer NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE +); +``` + ### Defining multiple self-relations on the same model You can also define multiple self-relations on the same model at once. Taking all relations from the previous sections as example, you could define a `User` model as follows: @@ -810,7 +851,7 @@ model User { ## Disambiguating relations -When you define two relations between two the same models, you need to add the `@relation` attribute to disambiguate them. As an example for why that's needed, consider the following models: +When you define two relations between two the same models, you need to add the `name` argument in the `@relation` attribute to disambiguate them. As an example for why that's needed, consider the following models: ```prisma model User { @@ -821,21 +862,23 @@ model User { } model Post { - id Int @id @default(autoincrement()) - title String? - author User - pinnedBy User? + id Int @id @default(autoincrement()) + title String? + author User @relation(fields: [authorId], references: [id]) + authorId Int + pinnedBy User? @relation(fields: [pinnedById], references: [id]) + pinnedById Int? } ``` In that case, the relations are ambiguous, there are four different ways to interpet them: -- `User.writtenPosts` โ†” `Post.author` -- `User.writtenPosts` โ†” `Post.pinnedBy` -- `User.pinnedPost` โ†” `Post.author` -- `User.pinnedPost` โ†” `Post.pinnedBy` +- `User.writtenPosts` โ†” `Post.author` + `Post.authorId` +- `User.writtenPosts` โ†” `Post.pinnedBy` + `Post.pinnedById` +- `User.pinnedPost` โ†” `Post.author` + `Post.authorId` +- `User.pinnedPost` โ†” `Post.pinnedBy` + `Post.pinnedById` -To disambiguate these relations, you need to annotate the relation fields with the `@relation` attribute and provide the `name` argument. You can set any `name` (except for the empty string `""`), but it must match on both sides of the relation: +To disambiguate these relations, you need to annotate the relation fields with the `@relation` attribute and provide the `name` argument. You can set any `name` (except for the empty string `""`), but it must be the same on both sides of the relation: ```prisma model User { @@ -846,9 +889,11 @@ model User { } model Post { - id Int @id @default(autoincrement()) - title String? - author User @relation("WrittenPosts") - pinnedBy User? @relation("PinnedPost") + id Int @id @default(autoincrement()) + title String? + author User @relation("WrittenPosts", fields: [authorId], references: [id]) + authorId Int + pinnedBy User? @relation(name: "PinnedPost", fields: [pinnedById], references: [id]) + pinnedById Int? } ``` From 6b6fc97d23230ceaea5a39d6b6f28bb42a202b75 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 08:58:48 +0100 Subject: [PATCH 27/76] relations update --- content/01-getting-started/02-quickstart.mdx | 4 ++-- .../01-tools-and-interfaces/01-prisma-schema/06-relations.mdx | 2 +- content/index.mdx | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 32315a1a14..31d652476f 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -119,11 +119,11 @@ The SQLite database file `prisma/dev.db` contains two tables with dummy data: **Post** -| **id** | **title** | **content** | **published** | **author** | +| **id** | **title** | **content** | **published** | **authorId** | | :----- | :-------------- | :---------- | :------------ | :--------- | | `1` | `"Hello World"` | `null` | `false` | `2` | -> **Note**: The number in the `author` column references the `id` column of the `User` table: the `2` in the `author` column refers to the `User` record with an `id` value of `2`. +> **Note**: The `authorId` column references the `id` column of the `User` table: the `2` in the `authorId` column refers to the `User` record with an `id` value of `2`. Befor you move on, navigate into the `starter` directory and install the npm dependencies with these commands: diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 0b1412fba1..3792313fcc 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -8,7 +8,7 @@ metaDescription: '' This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. -Relations between models are _physically_ represented via _foreign keys_ in the underlying database. However, as opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. +Relations between models are _physically_ represented via _foreign keys_ in the underlying database. A foreign key is only stored on _one_ side of a relation. As opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. This means that one of these relation fields represents the physical foreign key in the underlying database, the other relation field is a [virtual relation field]() (in the case of [implicit many-to-many relations]()), both relation fields are virtual. diff --git a/content/index.mdx b/content/index.mdx index a2cb79611c..7110dd877c 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -12,6 +12,8 @@ Welcome to the Prisma documentation! You can find an overview of the available c ## Table of contents +--- + ### Getting started The **Getting started** section contains _practical guides_ to help you get started with Prisma. From c4e987604046d16520b37983a0c9e292a62af568 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 09:35:08 +0100 Subject: [PATCH 28/76] update quickstart with new relation syntax --- content/01-getting-started/02-quickstart.mdx | 78 +++++++++++++------- 1 file changed, 50 insertions(+), 28 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 31d652476f..34de878463 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -242,13 +242,19 @@ Each object inside `allUsers` now includes a `posts` field which represents the ```js [ - { id: 1, email: 'sarah@prisma.io', name: 'Sarah', posts: [] } + { id: 1, email: 'sarah@prisma.io', name: 'Sarah', posts: [] }, { id: 2, email: 'maria@prisma.io', name: 'Maria', posts: [ - { id: 1, title: 'Hello World', content: null, published: false } + { + id: 1, + title: 'Hello World', + content: null, + published: false, + authorId: 2 + } ] } ] @@ -269,12 +275,12 @@ export type Post = { title: string content: string | null published: boolean + authorId: number | null } ``` - Congratulations, you just wrote your first query with Prisma Client ๐ŸŽ‰ ## Write data into the database @@ -317,7 +323,8 @@ The output should look similar to this: id: 2, title: 'Prisma makes databases easy', content: null, - published: false + published: false, + authorId: 1 } [ { @@ -325,15 +332,27 @@ The output should look similar to this: email: 'sarah@prisma.io', name: 'Sarah', posts: [ - { id: 2, title: 'Prisma makes databases easy', content: null, published: false } + { + id: 2, + title: 'Prisma makes databases easy', + content: null, + published: false, + authorId: 1 + } ] - } + }, { id: 2, email: 'maria@prisma.io', name: 'Maria', posts: [ - { id: 1, title: 'Hello World', content: null, published: false } + { + id: 1, + title: 'Hello World', + content: null, + published: false, + authorId: 2 + } ] } ] @@ -343,7 +362,7 @@ The query added a new record to the `Post` table: **Post** -| **id** | **title** | **content** | **published** | **author** | +| **id** | **title** | **content** | **published** | **authorId** | | :----- | :------------------------------ | :---------- | :------------ | :--------- | | `1` | `"Hello World"` | `null` | `false` | `2` | | `2` | `"Prisma makes databases easy"` | `null` | `false` | `1` | @@ -373,7 +392,8 @@ You will see the following output: id: 2, title: 'Prisma makes databases easy', content: null, - published: true + published: true, + authorId: 1 } ``` @@ -381,7 +401,7 @@ The `Post` record with an `id` of `2` now got updated in the database: **Post** -| **id** | **title** | **content** | **published** | **author** | +| **id** | **title** | **content** | **published** | **authorId** | | :----- | :------------------------------ | :---------- | :------------ | :--------- | | `1` | `"Hello World"` | `null` | `false` | `2` | | `2` | `"Prisma makes databases easy"` | `null` | `true` | `1` | @@ -482,7 +502,7 @@ sqlite3 ./prisma/dev.db \ 'CREATE TABLE "Profile" ( "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "bio" TEXT, - "user" TEXT NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL + "userId" TEXT NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE SET NULL )' ``` @@ -494,15 +514,7 @@ npx prisma introspect This updates your [Prisma schema]()) in `prisma/schema.prisma`. -Finally, re-generate Prisma Client with this command: - -``` copy -npx prisma generate -``` - -This updates the generated Prisma Client library in [`node_modules/@prisma/client`](). - -You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. +Note that after the introspection, you might want to [configure your Prisma Client API]().
    Alternative: Use Prisma Migrate (experimental) @@ -512,9 +524,10 @@ First, adjust the data model in your Prisma schema, e.g. by adding a new model: ```prisma copy model Profile { - id Int @id @default(autoincrement()) - bio String - user User + id Int @id @default(autoincrement()) + bio String + user User @relation(fields: [userId], references: [id]) + userId Int } model User { @@ -526,11 +539,12 @@ model User { } model Post { - id Int @id @default(autoincrement()) + id Int @id @default(autoincrement()) title String content String? - published Boolean @default(false) - author User? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? } ``` @@ -541,15 +555,23 @@ npx prisma migrate save --name "add-profile" --experimental npx prisma migrate up --experimental ``` -Now you can run the migration against the database `npx prisma migrate up --experimental`. +Now you can run the migration against the database `npx prisma migrate up --experimental`.
    + +Finally, re-generate Prisma Client with this command: + +``` copy +npx prisma generate +``` + +This updates the generated Prisma Client library in [`node_modules/@prisma/client`](). + You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. --- - ### Try a Prisma example The [`prisma-examples`]() repository contains a number of ready-to-run examples: From 27072f7a8bc8a485e0e0d3cb0df98788017dee70 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 11:20:50 +0100 Subject: [PATCH 29/76] update setup guides with new relation syntax and more tech combos --- content/01-getting-started/02-quickstart.mdx | 1 - .../01-add-to-an-existing-project.mdx | 358 ++++++++++-------- .../02-start-from-scratch-sql-migrations.mdx | 332 ++++++++++++++-- 3 files changed, 501 insertions(+), 190 deletions(-) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/02-quickstart.mdx index 34de878463..0d2084fa21 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/02-quickstart.mdx @@ -469,7 +469,6 @@ const deletedUser = await prisma.user.delete({

    - --- ### Setup Prisma with your own database diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx index 8efbf03899..9aa44136ae 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx @@ -8,13 +8,13 @@ langSwitcher: true ## Overview - + This page walks you through the process of adding Prisma to a **TypeScript** project with an existing database. - + This page walks you through the process of adding Prisma to a **Node.js** project with an existing database. @@ -75,54 +75,7 @@ This command created a new directory called `prisma` with the following contents To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](): - - -```prisma -datasource postgresql { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: - -``` -DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" -``` - -You now need to adjust the connection URL to point to your own database. - -The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): - -``` -postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA -``` - -Here's a short explanation of each component: - -- `USER`: The name of your database user -- `PASSWORD`: The password your database user -- `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) -- `DATABASE`: The name of the [database]() -- `SCHEMA`: The name of the [schema]() inside the database - -If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. - -As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: - -``` -DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" -``` - -When running PostgreSQL locally, your user and password as well as the database name typically correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: - -``` -DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" -``` - - - - + ```prisma datasource postgresql { @@ -139,7 +92,7 @@ DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=pub You now need to adjust the connection URL to point to your own database. -The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): +The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): ``` postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA @@ -161,7 +114,7 @@ As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]( DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" ``` -When running PostgreSQL locally, your user and password as well as the database name typically correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: +When running PostgreSQL locally, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: ``` DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" @@ -169,8 +122,7 @@ DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-p - - + ```prisma datasource postgresql { @@ -196,7 +148,7 @@ DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" You now need to adjust the connection URL to point to your own database. -The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): +The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): ``` mysql://USER:PASSWORD@HOST:PORT/DATABASE @@ -218,103 +170,114 @@ DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.a When running MySQL locally, your connection URL typically looks similar to this: ``` -DATABASE_URL="postgresql://root:randompassword@localhost:3306/mydb" +DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" ``` - -```prisma -datasource postgresql { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` +## Introspect your database with Prisma -Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + -```prisma -datasource mysql { - provider = "mysql" - url = env("DATABASE_URL") -} -``` +For the purpose of this guide, we'll use a demo SQL schema with three tables: -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: +```sql copy +CREATE TABLE "public"."User" ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); -``` -DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +CREATE TABLE "public"."Post" ( + id SERIAL PRIMARY KEY NOT NULL, + title VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + "authorId" INTEGER NOT NULL, + FOREIGN KEY ("authorId") REFERENCES "public"."User"(id) +); + +CREATE TABLE "public"."Profile" ( + id SERIAL PRIMARY KEY NOT NULL, + bio TEXT, + "userId" INTEGER UNIQUE NOT NULL, + FOREIGN KEY ("userId") REFERENCES "public"."User"(id) +); ``` -You now need to adjust the connection URL to point to your own database. +> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. -The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): +
    Expand for a graphical overview of the tables -``` -mysql://USER:PASSWORD@HOST:PORT/DATABASE -``` +**User** -Here's a short explanation of each component: +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | -- `USER`: The name of your database user -- `PASSWORD`: The password your database user -- `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database]() +**Post** -As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **โœ”๏ธ** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **โœ”๏ธ** | `false` | +| `authorId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | -``` -DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb -``` +**Profile** -When running MySQL locally, your connection URL typically looks similar to this: +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `bio` | `TEXT` | No | No | **โœ”๏ธ** | - | +| `userId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** |- | -``` -DATABASE_URL="postgresql://root:randompassword@localhost:3306/mydb" -``` +
    - -## Introspect your database with Prisma + For the purpose of this guide, we'll use a demo SQL schema with three tables: ```sql copy -CREATE TABLE "public"."User" ( - id SERIAL PRIMARY KEY NOT NULL, +CREATE TABLE User ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(255), email VARCHAR(255) UNIQUE NOT NULL ); -CREATE TABLE "public"."Post" ( - id SERIAL PRIMARY KEY NOT NULL, +CREATE TABLE Post ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, - "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + createdAt TIMESTAMP NOT NULL DEFAULT now(), content TEXT, published BOOLEAN NOT NULL DEFAULT false, - author INTEGER NOT NULL, - FOREIGN KEY (author) REFERENCES "public"."User"(id) + authorId INTEGER NOT NULL, + FOREIGN KEY (authorId) REFERENCES User(id) ); -CREATE TABLE "public"."Profile" ( - id SERIAL PRIMARY KEY NOT NULL, +CREATE TABLE Profile ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, bio TEXT, - "user" INTEGER UNIQUE NOT NULL, - FOREIGN KEY ("user") REFERENCES "public"."User"(id) + userId INTEGER UNIQUE NOT NULL, + FOREIGN KEY (userId) REFERENCES User(id) ); ``` -> **Note**: Some fields are written in double-quotes to ensure PostgreSQL uses proper casing. If no double-quotes were used, PostgreSQL would just read everything as _lowercase_ characters. -
    Expand for a graphical overview of the tables **User** | Column name | Type | Primary key | Foreign key | Required | Default | | :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | | `name` | `VARCHAR(255)` | No | No | No | - | | `email` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | @@ -322,23 +285,25 @@ CREATE TABLE "public"."Profile" ( | Column name | Type | Primary key | Foreign key | Required | Default | | :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | | `createdAt` | `TIMESTAMP` | No | No | **โœ”๏ธ** | `now()` | | `title` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | | `content` | `TEXT` | No | No | No | - | | `published` | `BOOLEAN` | No | No | **โœ”๏ธ** | `false` | -| `author` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | +| `authorId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | **Profile** | Column name | Type | Primary key | Foreign key | Required | Default | | :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | -| `id` | `SERIAL` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | | `bio` | `TEXT` | No | No | **โœ”๏ธ** | - | -| `user` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | +| `userId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | - |
    +
    + As a next step, you will introspect your database. The result of the introspection will be a [data model]() inside your Prisma schema. Run the following command to introspect your database: @@ -353,48 +318,47 @@ After the introspection has completed, your Prisma schema file was updated: ![](https://imgur.com/EYC3RIK.png) - -It now looks similar to this (note that the fields on the models have been reordered for better readability): +The data model now looks similar to this (note that the fields on the models have been reordered for better readability): ```prisma -generator client { - provider = "prisma-client-js" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - model Post { id Int @default(autoincrement()) @id createdAt DateTime @default(now()) title String content String? published Boolean @default(false) - author User @relation(references: [id]) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId], name: "authorId") } model Profile { - id Int @default(autoincrement()) @id + id Int @default(autoincrement()) @id bio String? - user User @relation(references: [id]) + user User @relation(fields: [userId], references: [id]) + userId Int @unique } model User { - id Int @default(autoincrement()) @id + id Int @default(autoincrement()) @id + email String @unique name String? - email String @unique - post Post[] - profile Profile? + Post Post[] + Profile Profile? } ``` Prisma's data model is a declarative representation of your database schema and serves as foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. -Right now, there's one minor "issue" with the data model. The `post` relation field on `User` is slightly misnamed after the introspection, since it's actually a [list]() of posts โ€“ a better name therefore would be `posts`. This is relevant for the generated Prisma Client API where using `posts` will feel more natural than `post`. +Right now, there's a few minor "issues" with the data model: + +- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](), both fields should be lowercased to `post` and `profile`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list]() of posts โ€“ a better name therefore would be the plural from `posts`. -To make this change, manually rename the `post` field to `posts`: +These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](). + +Because both the generated `Post` and `Profile` fields are [virtual](), you can go and rename them in your Prisma schema: ```prisma model User { @@ -406,41 +370,56 @@ model User { } ``` -> **Note**: The `posts` field is [virtual]() so you can rename it in your Prisma schema without using [`@map`](). +In this example, the database schema did follow the [naming conventions]() for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. -In this example, the database schema has followed all [naming conventions]() for Prisma models. This optimizes the ergonomics of the generated Prisma Client API. +Sometimes though, you may want to make additional changes to the the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake\_case_ notation which is often used in database schemas into ` PascalCase` and `camelCase` notations which feel more natural for JavaScript/TypeScript developers. -Sometimes though, when generated from introspection, relation fields that are named after a foreign key in the database are suffixed with `_id` (e.g. `profile_id`). This can lead to unintuitive situations in the Prisma Client API when a full `Profile` object would be referred to by a field which is called `profile_id`. Here are two example snippets that illustrate this: +Assume you obtained the following model from introspection that's based on _snake\_case_ notation: -```js -const profile = await prisma.user.findOne({ - where: { id: 1 } -}).profile_id() +```prisma +model my_user { + user_id Int @default(autoincrement()) @id + first_name String? + last_name String @unique +} +``` -const user = await prisma.user.create({ +If you generated a Prisma Client API for this model, it would pick up the _snake\_case_ notation in its API: + +```ts +const user = await prisma.my_user.create({ data: { - name: "Alice", - profile_id: { bio: "I like turtles" } + first_name: "Alice", + last_name: "Smith" } }) ``` -In that case, you might want to [configure your Prisma Client API]() and rename the relation field on the model using [`@map`](): +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](): ```prisma -model Profile { - id Int @id @default(autoincrement()) - bio String - user User -} +model MyUser { + user_id Int @default(autoincrement()) @id @map("user_id") + firstName String? @map("first_name") + lastName String @unique @map("last_name") -model User { - id Int @id @default(autoincrement()) - name String - profile Profile @map("profile_id") + @@map("my_user") } ``` +With this approach, you can name your model and its fields whatever you like and use the `@map` (for field names) and `@@map` (for models names) to point to the underlying tables and columns. Your Prisma Client API now looks as follows: + +```ts +const user = await prisma.myUser.create({ + data: { + firstName: "Alice", + lastName: "Smith" + } +}) +``` + +Learn more about this on the [Configuring your Prisma Client API]() page. + ## Install and generate Prisma Client To get started with Prisma Client, you need to install it as a node module: @@ -469,6 +448,32 @@ Now that you generated your Prisma Client library, you can start writing queries For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers). + + +Create a new file called `index.ts` and add the following code to it: + +```js +import { PrismaClient } from "@prisma/client" + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .catch(e => { + throw e + }) + .finally(async () => { + await prisma.disconnect() + }) +``` + + + + + Create a new file called `index.js` and add the following code to it: ```js @@ -489,6 +494,8 @@ main() }) ``` + + Here's a quick overview of the different parts of the code snippet: 1. Import the `PrismaClient` constructor from the `@prisma/client` node module @@ -497,7 +504,7 @@ Here's a quick overview of the different parts of the code snippet: 1. Call the `main` function 1. Close the database connections when the script terminates -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD]() methods like `findMany`, `create` or `update`. The property named after the model, but the first letter is lowercased (so for the `Post` model the property is called `post`, for `Profile` it's called profile). +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD]() methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model the property is called `post`, for `Profile` it's called `profile`). The following examples are all based on the models in the Prisma schema. @@ -510,12 +517,26 @@ async function main() { } ``` + + +Now run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +``` +ts-node index.ts +``` + + + + + Now run the code with this command: ``` node index.js ``` + + This will print an array of `User` records as plain old JavaScript objects. ## Write data into the database @@ -554,12 +575,26 @@ This code creates a new `User` record together with new `Post` and `Profile` rec Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +``` +ts-node index.ts +``` + + + + + Run the code with this command: ``` node index.js ``` + + Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: ```js @@ -574,17 +609,33 @@ async function main() { Now run the code using the same command as before: + + +Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: + +``` +ts-node index.ts +``` + + + + + +Now run the code using the same command as before: + ``` node index.js ``` + + ## Next steps This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. ### Continue exploring the Prisma Client API -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing PostgreSQL-based setup from this guide to try them out. +You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing database setup from this guide to try them out. **Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. @@ -655,6 +706,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Manually adjust your database schema using SQL 1. Re-introspect your database +1. Optionally re-configure your Prisma Client API 1. Re-generate Prisma Client ![](https://imgur.com/7BUqpyv.png) diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index b47bcb5c07..204192566d 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -2,6 +2,8 @@ title: 'Start from scratch (SQL migrations)' metaTitle: '' metaDescription: '' +dbSwitcher: true +langSwitcher: true --- ## Overview @@ -12,10 +14,22 @@ This page walks you through the process of setting up Prisma from scratch with y In order to successfully complete this guide, you need: + + - [Node.js]() installed on your machine - a [PostgreSQL]() database server running - the [`psql`]() command line client for PostgreSQL + + + + +- [Node.js]() installed on your machine +- a [MySQL](https://www.mysql.com/) database server running +- the [`mysql`](https://dev.mysql.com/doc/refman/5.7/en/mysql.html) command line client for MySQL + + + Make sure your have your database [connection URL]() (includes your authentication credentials) at hand! If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](). Alternatively you can [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1) and use it in this guide. @@ -29,7 +43,36 @@ mkdir hello-prisma cd hello-prisma ``` -Next, initialize a Node.js project add the Prisma CLI as a development dependency in your project: + + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +``` +npm init -y +npm install @prisma/cli typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, create a `tsconfig.json` file and add the following configuration to it: + +```json +{ + "compilerOptions": { + "sourceMap": true, + "outDir": "dist", + "strict": true, + "lib": ["esnext"], + "esModuleInterop": true + } +} +``` + + + + + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: ``` npm init -y @@ -38,6 +81,8 @@ npm install @prisma/cli --save-dev This creates a `package.json` with an initial setup for a Node.js app. + + You can now invoke the Prisma CLI by prefixing it with `npx`: ``` @@ -57,8 +102,11 @@ This command created a new directory called `prisma` with the following contents ## Connect your database + To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](): + + ```prisma datasource postgresql { provider = "postgresql" @@ -69,12 +117,12 @@ datasource postgresql { In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: ``` -DATABASE_URL="postgresql://johndoe:johndoe@localhost:5432/mydb?schema=public" +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" ``` You now need to adjust the connection URL to point to your own database. -The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details): +The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): ``` postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA @@ -90,20 +138,77 @@ Here's a short explanation of each component: If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. -As an example, for a PostgreSQL database hosted on Heroku, the [connection string](./core/connectors/postgresql.md#connection-string) might look similar to this: +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: ``` DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" ``` -When running PostgreSQL locally, your user and password as well as the database name typically correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: +When running PostgreSQL locally, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: ``` DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" ``` + + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma +datasource mysql { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: + +``` +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +``` +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database]() + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: + +``` +DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +``` +DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" +``` + + + ## Create database tables with SQL + + In this guide, you'll use plain SQL to create the tables in your database. Create a new file called `schema.sql` and add the following contents to it: ```sql copy @@ -189,6 +294,80 @@ Great, you now created three tables in your database
    +
    + + + +In this guide, you'll use plain SQL to create the tables in your database. Create a new file called `schema.sql` and add the following contents to it: + +```sql copy +CREATE TABLE User ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE Post ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + title VARCHAR(255) NOT NULL, + createdAt TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + authorId INTEGER NOT NULL, + FOREIGN KEY (authorId) REFERENCES User(id) +); + +CREATE TABLE Profile ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + bio TEXT, + userId INTEGER UNIQUE NOT NULL, + FOREIGN KEY (userId) REFERENCES User(id) +); +``` + +You can create the tables using any MySQLL client of your choice. If you're using `mysql`, you can now create the tables using the following command: + +{/* ``` +mysql < schema.sql +``` */} + +Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: + +Great, you now created three tables in your database + +
    Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **โœ”๏ธ** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **โœ”๏ธ** | `false` | +| `authorId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `bio` | `TEXT` | No | No | **โœ”๏ธ** | - | +| `userId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | - | + +
    + +
    + ## Introspect your database with Prisma As a next step, you will introspect your database. The result of the introspection will be a [data model]() inside your Prisma schema. @@ -205,49 +384,49 @@ After the introspection has completed, your Prisma schema file was updated: ![](https://imgur.com/EYC3RIK.png) -It now looks as follows (note that the fields on the models have been reordered for better readability): +The data model now looks as follows (note that the fields on the models have been reordered for better readability): ```prisma -generator client { - provider = "prisma-client-js" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} - model Post { id Int @default(autoincrement()) @id createdAt DateTime @default(now()) title String content String? published Boolean @default(false) - author User @relation(references: [id]) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId], name: "authorId") } model Profile { - id Int @default(autoincrement()) @id + id Int @default(autoincrement()) @id bio String? - user User @relation(references: [id]) + user User @relation(fields: [userId], references: [id]) + userId Int @unique } model User { - id Int @default(autoincrement()) @id + id Int @default(autoincrement()) @id + email String @unique name String? - email String @unique - post Post[] - profile Profile? + Post Post[] + Profile Profile? } ``` Prisma's data model is a declarative representation of your database schema and serves as foundation for the generated Prisma Client library. Your Prisma Client instance will expose queries that are _tailored_ to these models. -Right now, there's one minor "issue" with the data model. The `post` relation field on `User` is slightly misnamed after the introspection, since it's actually a [list]() of posts โ€“ a better name therefore would be `posts`. This is relevant for the generated Prisma Client API where using `posts` will feel more natural than `post`. +Right now, there's a few minor "issues" with the data model: -To make this change, manually rename the `post` field to `posts`: +- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](), both fields should be lowercased to `post` and `profile`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list]() of posts โ€“ a better name therefore would be the plural from `posts`. -```prisma +These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](). + +Because both the generated `Post` and `Profile` fields are [virtual](), you can go and rename them in your Prisma schema: + +```prisma copy model User { id Int @default(autoincrement()) @id name String? @@ -257,7 +436,9 @@ model User { } ``` -> **Note**: The `posts` field is [virtual]() so you can rename it in your Prisma schema without using [`@map`](). Learn more about [configuring your Prisma Client API](). +In this example, the database schema did follow the [naming conventions]() for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. + +Learn more about this on the [Configuring your Prisma Client API]() page. ## Install and generate Prisma Client @@ -285,6 +466,32 @@ Because the `@prisma/client` node module actually is customized to your project, Now that you generated your Prisma Client library, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + + +Create a new file called `index.ts` and add the following code to it: + +```js +import { PrismaClient } from "@prisma/client" + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .catch(e => { + throw e + }) + .finally(async () => { + await prisma.disconnect() + }) +``` + + + + + Create a new file called `index.js` and add the following code to it: ```js @@ -305,6 +512,8 @@ main() }) ``` + + Here's a quick overview of the different parts of the code snippet: 1. Import the `PrismaClient` constructor from the `@prisma/client` node module @@ -328,7 +537,7 @@ Now run the code with this command: node index.js ``` -This should print an empty arrays because there are not `User` records in the databse yet: +This should print an empty arrays because there are no `User` records in the database yet: ```js [] @@ -370,12 +579,26 @@ This code creates a new `User` record together with new `Post` and `Profile` rec Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + + +Run the code with this command: + +``` +npx ts-node index.ts +``` + + + + + Run the code with this command: ``` node index.js ``` + + The output should look similar to this: ```js @@ -390,16 +613,38 @@ The output should look similar to this: createdAt: 2020-03-21T16:45:01.246Z, id: 1, published: false, - title: 'Hello World' + title: 'Hello World', + authorId: 1, } ], profile: { - bio: 'I like turtles' + bio: 'I like turtles', + userId: 1, } } ] ``` + + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts +const allUsers: (User & { + posts: Post[]; +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + + + The query added new records to the `User` and the `Post` tables: **User** @@ -410,17 +655,17 @@ The query added new records to the `User` and the `Post` tables: **Post** -| **id** | **createdAt** | **title** | **content** | **published** | **author** | +| **id** | **createdAt** | **title** | **content** | **published** | **authorId** | | :----- | :------------------------- | :-------------- | :---------- | :------------ | :--------- | | `1` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | **Profile** -| **id** | **bio** | **user** | +| **id** | **bio** | **userId** | | :----- | :------------------ | :-------- | | `1` | `"I like turtles"` | `1` | -> **Note**: The numbers in the `author` column on `Post` and `user` column on `Profile` reference the `id` column of the `User` table: the `id` value `1` column therefore refers to the first (and only) `User` record in the database. +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table: the `id` value `1` column therefore refers to the first (and only) `User` record in the database. Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: @@ -434,12 +679,26 @@ async function main() { } ``` + + +Now run the code using the same command as before: + +``` +npx ts-node index.ts +``` + + + + + Now run the code using the same command as before: ``` node index.js ``` + + You will see the following output: ```js @@ -447,7 +706,8 @@ You will see the following output: id: 1, title: 'Hello World', content: null, - published: true + published: true, + authorId: 1 } ``` @@ -455,20 +715,19 @@ The `Post` record with an `id` of `1` now got updated in the database: **Post** -| **id** | **title** | **content** | **published** | **author** | +| **id** | **title** | **content** | **published** | **authorId** | | :----- | :------------------------------ | :---------- | :------------ | :--------- | | `1` | `"Hello World"` | `null` | `true` | `1` | Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ - ## Next steps This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. ### Continue exploring the Prisma Client API -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing PostgreSQL-based setup from this guide to try them out. +You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing database setup from this guide to try them out. **Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. @@ -541,6 +800,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Manually adjust your database schema using SQL 1. Re-introspect your database +1. Optionally re-configure your Prisma Client API 1. Re-generate Prisma Client ![](https://imgur.com/7BUqpyv.png) From 2b8b56bdbb0dbb96148682eddb4d2c7a6bde975f Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 11:26:48 +0100 Subject: [PATCH 30/76] fix build --- .../03-setup-prisma/02-start-from-scratch-sql-migrations.mdx | 4 ++-- content/index.mdx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index 204192566d..7cddce1af5 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -327,9 +327,9 @@ CREATE TABLE Profile ( You can create the tables using any MySQLL client of your choice. If you're using `mysql`, you can now create the tables using the following command: -{/* ``` +``` mysql < schema.sql -``` */} +``` Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: diff --git a/content/index.mdx b/content/index.mdx index 7110dd877c..8825773bd2 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -12,7 +12,7 @@ Welcome to the Prisma documentation! You can find an overview of the available c ## Table of contents ---- +--- ### Getting started From c357c8307f1968d7cf05d67019b440d2cb63317d Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 11:30:39 +0100 Subject: [PATCH 31/76] fix build --- .../03-setup-prisma/02-start-from-scratch-sql-migrations.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx index 7cddce1af5..b1ef75aa25 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx @@ -325,7 +325,7 @@ CREATE TABLE Profile ( ); ``` -You can create the tables using any MySQLL client of your choice. If you're using `mysql`, you can now create the tables using the following command: +You can create the tables using any MySQL client of your choice. If you're using `mysql`, you can now create the tables using the following command: ``` mysql < schema.sql From fd43e211f765cabc21af63d2c65ed519fb4fe815 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 12:24:23 +0100 Subject: [PATCH 32/76] adjhust to new relation syntax --- .../02-understand-prisma/01-introduction.mdx | 10 ++-- .../03-prisma-in-your-stack/01-rest.md | 4 +- .../03-prisma-in-your-stack/02-graphql.md | 4 +- .../04-is-prisma-an-orm.mdx | 31 +++++----- .../02-understand-prisma/05-data-modeling.mdx | 2 +- .../01-prisma-schema-file.mdx | 7 ++- .../01-prisma-schema/04-data-model.mdx | 56 ++++++++++--------- .../01-prisma-schema/05-models.mdx | 18 ++---- 8 files changed, 66 insertions(+), 66 deletions(-) diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 3e24f8b5a6..ff04285a36 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -43,7 +43,8 @@ model Post { title String content String? published Boolean @default(false) - author User? + author User? @relation(fields: [authorId], references: [id]) + authorId Int? } model User { @@ -70,7 +71,7 @@ On this page, the focus is on the data model. You can learn more about [Data sou The data model is a collection of [models](). A model has two major functions: -- Map to a table in the underlying database +- Represent a table in the underlying database - Provide the foundation for the queries in the Prisma Client API #### Getting a data model @@ -124,7 +125,7 @@ const prisma = new PrismaClient() -Now you can start queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return _plain old JavaScript objects_. +Now you can start sending queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return _plain old JavaScript objects_. Learn more about the available operations in the [Prisma Client API reference](). @@ -185,7 +186,7 @@ const post = await prisma.post.update({ #### Usage with TypeScript -Note that when using TypeScript, the result of this query will be _statically typed_ so that you can't accidentally access a property that doesn't exist (and any typos are caught). Learn more about leveraging Prisma Client's generated types on the [Advanced usage of generated types]() page in the docs. +Note that when using TypeScript, the result of this query will be _statically typed_ so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the [Advanced usage of generated types]() page in the docs. ## Typical Prisma workflows @@ -197,6 +198,7 @@ The typical workflow when using **SQL migrations and introspection** looks as fo 1. Manually adjust your database schema using SQL 1. (Re-)introspect your database +1. Optionally (re-)configure your Prisma Client API ([learn more]()) 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md index 60eb8c164d..26b39b3c7f 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md @@ -48,7 +48,8 @@ model Post { title String content String? published Boolean @default(false) - author User? + author User? @relation(fields: [authorId], references: [id]) + authorId Int? } model User { @@ -82,6 +83,7 @@ Note that the `feed` endpoint in this case returns a nested JSON response of `Po "title": "Hello World", "content": "null", "published": "true", + "authorId": 42, "author": { "id": "42", "name": "Alice", diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md index 06f85334b7..9261285efe 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md @@ -73,6 +73,8 @@ In the resolver of a GraphQL query, Prisma typically reads data from the databas ### Is there a special connection between Prisma and Nexus? -Yes. At Prisma, we love GraphQL and strongly believe in its bright future. While Prisma is compatible with all tools from the GraphQL ecosystem, we want to leverage the amazing things that become possible when Nexus and Prisma are combined and are therefore helping to build it. +Yes. At Prisma, we love GraphQL and strongly believe in its bright future. While Prisma is compatible with all tools from the GraphQL ecosystem, we want to leverage the amazing things that become possible when [Nexus]() and Prisma are combined and are therefore helping to build it. + +As an example, when you use Nexus together with Prisma, Nexus can leverage the information from the Prisma schema and automatically generate queries and mutations for your Prisma models. The [Prisma Labs]() team has been founded as an independent part of the rest of Prisma's engineering organization to work on open-source tools that are not directly tied to the Prisma database tools. Prisma Labs is currently dedicating most of their time to work on Nexus with the vision of making it a fully-fledged backend framework for building GraphQL servers. diff --git a/content/02-understand-prisma/04-is-prisma-an-orm.mdx b/content/02-understand-prisma/04-is-prisma-an-orm.mdx index 15595a448a..941a49376a 100644 --- a/content/02-understand-prisma/04-is-prisma-an-orm.mdx +++ b/content/02-understand-prisma/04-is-prisma-an-orm.mdx @@ -8,20 +8,19 @@ metaDescription: '' To answer the question briefly: _No, Prisma is not an ORM_. -If you're looking for an Object-Relational-Mapper (ORM), Prisma may help you. While Prisma shares the same goals with ORMs, it takes a different approach. +The main goal of Prisma is to make working with databases easier for application developers. In that sense, it shares the same goals with ORMs, but takes a fundamentally different approach. -ORMs and Prisma are both database abstractions that share the goal of making it easy to work with relational databases. +ORMs are libraries that map tables in your database to classes in your programming language. Prisma on the other hand is an auto-generated query builder that exposes queries which are _tailored_ to your models. All Prisma Client queries return plain old JavaScript objects. -Prisma is not considered an ORM because it doesn't map classes to tables the way ORMs do. +To understand how Prisma and ORMs differ conceptually, here's a brief overview of how their building blocks relate to databases: -To understand how they differ, here's a brief overview of how their building blocks relate to databases: - -| Database | ORMs | Prisma | -| ---------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------- | -| Tables | Model classes | Models in the Prisma schema | -| Columns | Properties in model classes | Model fields in the [Prisma schema](https://github.com/prisma/prisma2/blob/master/docs/prisma-schema-file.md) | -| Records | Instances of a model class (objects) | Plain JavaScript objects | -| SQL Schema | Migrations and model classes | Prisma schema | +| Database | ORMs | Prisma | +| ------------ | ------------------------------------ | ------------------------------------- | +| SQL Schema | Migrations and model classes | [Prisma schema]() | +| Tables | Model classes | [Models]() in the Prisma schema | +| Columns | Properties in model classes | Model [fields]() in the Prisma schema | +| Records | Instances of a model class (objects) | Plain JavaScript objects | +| Foreign keys | Foreign keys on model classes | [Relations]() between Prisma models | For a more detailed explanation follow along. @@ -231,17 +230,15 @@ Now that the costs and benefits of ORMs have been covered, you can better unders Prisma is a **database toolkit** that makes working with databases easy for application developers. It currently consists of two main tools: - **Prisma Client**: Auto-generated and type-safe database client -- **Prisma Migrate**: A CLI for declarative data modeling and migrations - -> Note that Prisma Migrate is currently in an experimental state +- **Prisma Migrate** (experimental): A CLI for declarative data modeling and migrations -Both Prisma Client and Migrate rely on the [_Prisma schema_](https://github.com/prisma/prisma2/blob/master/docs/prisma-schema-file.md). The Prisma schema is a declarative representation of your database schema. It serves as the single source truth for both the data model and database schema. +Both Prisma Client and Prisma Migrate rely on the [Prisma schema](). The Prisma schema is a declarative representation of your database schema. It serves as the single source truth for both the database schema and your application models. ### How Prisma compares -Unlike ORMs, with Prisma you don't create model classes nor do you map fields in your codebase to database fields. Instead, you use the generated Prisma Client API like an advanced query builder that returns plain JavaScript objects. Schema changes are synced automatically from the models in the Prisma schemaโ€“which serves as a single source of truthโ€“ to the database schema. +Unlike ORMs, with Prisma you don't create model classes nor do you map fields in your codebase to database fields. Instead, you use the generated Prisma Client API like an advanced query builder that returns plain JavaScript objects. Schema changes are synced automatically from the models in the Prisma schema โ€“ which serves as a single source of truth โ€“ to the database schema. -Models in Prisma mean something slightly different to ORMs. When using ORMs, models are represented as classes. With Prisma, models are defined in the Prisma schema as abstract entities which describe the relationships between tables: +Models in Prisma mean something slightly different to ORMs. When using ORMs, models are represented as _classes_. With Prisma, models are defined in the Prisma schema as abstract entities which describe the relationships between tables: ```prisma model User { diff --git a/content/02-understand-prisma/05-data-modeling.mdx b/content/02-understand-prisma/05-data-modeling.mdx index b1d1d7dd44..282f52f1ea 100644 --- a/content/02-understand-prisma/05-data-modeling.mdx +++ b/content/02-understand-prisma/05-data-modeling.mdx @@ -105,7 +105,7 @@ const user = new User(userData.user_id, userData.name, userData.email, userData. // } ``` -Notice that in these examples, the application models are "dumb", meaning they don't implement any logic but their sole purpose is to carry data as plain old JavaScript objects (POJOs). +Notice that in these examples, the application models are "dumb", meaning they don't implement any logic but their sole purpose is to carry data as _plain old JavaScript objects_. ### Data modeling with ORMs diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx index 97fd74e8db..ad2f0d8b46 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx @@ -25,7 +25,7 @@ Here is an example for a Prisma schema file that specifies a data source (SQLite ```prisma datasource sqlite { - url = "file:./data.db" + url = "file:./dev.db" provider = "sqlite" } @@ -46,9 +46,10 @@ model Post { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - title String - author User published Boolean @default(false) + title String + author User? @relation(fields: [authorId], references: [id]) + authorId Int? } enum Role { diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index b4519b9e3d..8b13b204cc 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -63,19 +63,19 @@ model Profile { } model Post { - id Int @id @default(autoincrement()) - createdAt DateTime @default(now()) + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) title String - published Boolean @default(false) - author User @relation(fields: [authorId], references: [id]) + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) authorId Int - categories Category[] + categories Category[] @relation(references: [id]) } model Category { - id Int @id @default(autoincrement()) + id Int @id @default(autoincrement()) name String - posts Post[] + posts Post[] @relation(references: [id]) } enum Role { @@ -113,7 +113,6 @@ The _data source connector_ determines what _native database type_ each of these Expand below to see the mappings per connector and generator. -
    Scalar mapping to connectors and generators
    @@ -237,16 +236,18 @@ Here's an overview of the extact signatures of all attributes: @@map(_ name: String) // Configuring relations -@relation(_ name: String?, references: FieldReference[]?) +@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?) ``` -The leading underscore in a signature means the _argument name_ can be omitted (read more [below](#arguments)). +> **Note**: The leading underscore in a signature means the _argument name_ can be omitted (read more [below](#arguments)). + +Here's an overview of the _types_ that are used in the attribute signatures: | Type | Description | Example | | :----------------- | :--------------------------------------- | :------------------------------------- | | `FieldReference[]` | An array of [field](#fields) names | `[id]`, `[firstName, lastName]` | -| `String` | A variable length text in `""` | `""`, `"Hello World"`, `"Alice"` | -| `Expression` | An expression can be evaluated by Prisma | `42.0`, `""`, `Bob`, `now()`, `cuid()` | +| `String` | A variable length text in double quotes | `""`, `"Hello World"`, `"Alice"` | +| `Expression` | An expression that can be evaluated by Prisma | `42.0`, `""`, `Bob`, `now()`, `cuid()` | ### Arguments @@ -389,11 +390,12 @@ model User { } ``` -**Specify an ID on sign field `author` without a default value** +**Specify an ID on field `authorId` without a default value** ```prisma model Post { - author User @id + authorId Int @id + author User @relation(fields: [authorId], references: [id]) title String published Boolean @default(false) } @@ -524,22 +526,23 @@ const user = await prisma.user.create({ ```prisma model Post { - author User title String - published Boolean @default(false) + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int - @@id([author, title]) + @@id([authorId, title]) } model User { - id Int @default(autoincrement()) - email String @unique - name String? - posts Post[] + id Int @default(autoincrement()) + email String @unique + name String? + posts Post[] } ``` -When creating new `Post` records, you now must provide a unique combination of values for `author` (foreign key) and `title`: +When creating new `Post` records, you now must provide a unique combination of values for `authorId` (foreign key) and `title`: ```ts const post = await prisma.post.create({ @@ -614,13 +617,14 @@ model User { Note that in this case, it is _allowed_ to have multiple `User` records in the database where the `email` is `NULL` because `NULL` values are considered to distinct from each other. -**Specify a unique attribute on relation field `author`** +**Specify a unique attribute on link field `authorId`** ```prisma model Post { - author User @unique + author User + authorId Int @unique title String - published Boolean @default(false) + published Boolean @default(false) } model User { @@ -868,6 +872,8 @@ It is currently not possible to provide more configuration options to the index: - MySQL - Specify index methods with `USING`; MySQL supports these index methods: B-tree, hash; Prisma uses B-Tree by default +Note that while you can't configure these option in your Prisma schema, you can still configure them on the database-level directly. + ### Mapping column and table names You can use the `@map` and `@@map` attributes to map field, model and enum names as well in your Prisma schema to different column and table names in the underlying database schema. diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx index bf7ad8c1e1..76ced2e817 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx @@ -50,7 +50,7 @@ model users { } ``` -In this case, the naming convention of the Prisma schema is broken. However, you can still adhere to the naming convention without renaming the underlying `users` table in the database by using the `@@map` attribute: +In this case, the naming convention of the Prisma schema is violated. However, you can still adhere to the naming convention without renaming the underlying `users` table in the database by using the `@@map` attribute: ```prisma model User { @@ -94,8 +94,8 @@ Here's an overview of these for the fields from the `User` model [above](#exampl | `email` | `String` | Scalar | - | `@unique` | | `name` | `String` | Scalar | `?` | - | | `role` | `Role` | Scalar (enum) | - | `@default(USER)` | -| `posts` | `Post` | Relation | `?` | - | -| `profile` | `Profile` | Relation | `[]` | - | +| `posts` | `Post` | Relation (virtual) | `?` | - | +| `profile` | `Profile` | Relation (virtual) | `[]` | - | ### Naming fields @@ -107,16 +107,6 @@ Technically, a field can be named anything that adheres to this regular expressi [A-Za-z][A-Za-z0-9_]* ``` -> **Note**: There's currently a [bug](https://github.com/prisma/prisma2/issues/259) that doesn't allow for field names prepended with an underscore. The current regular expression for valid field names therefore is: `[A-Za-z][A-Za-z0-9_]*` - -A note on naming [relation fields](): Sometimes when generated from introspection, relation fields that are named after a foreign key in the database are suffixed with `_id` (e.g. `user_id`). This can lead to unintuitive situations in the Prisma Client API when a full `User` object would be referred to by a field which is called `user_id`. In that case, you might want to [configure your Prisma Client API]() and rename the relation field on the model using `@map`: - -```prisma -model Profile { - user User @map("user_id") -} -``` - ### Field types #### Scalar fields vs relation fields @@ -168,7 +158,7 @@ When **not** annotating a field with the `?` type modifier, the field will be _r ### Model attributes -A field of a model can have one or more _attributes_ which modify the behaviour of the field. Field attributes are always prefixed with a single `@` (as opposed to block attributes which are prefixed with `@@`). You can find an overview of all available attributes [below](#attributes). +A field of a model can have one or more _attributes_ which modify the behaviour of the field. Field attributes are always prefixed with a single `@`, model attributes which are prefixed with `@@`). You can find an overview of all available attributes on the [Data model]() page. ## Models in Prisma Client From 4e9ff8f1099bab00025940de6af0b1264aec46d6 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 19:15:39 +0100 Subject: [PATCH 33/76] adjhust to new relation syntax --- .../02-configuring-the-prisma-client-api.mdx | 36 +++++--- .../02-prisma-client/03-crud.mdx | 5 +- .../02-prisma-client/04-relation-queries.mdx | 91 ++++++++++--------- .../02-prisma-client/05-field-selection.mdx | 9 +- 4 files changed, 77 insertions(+), 64 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx index 046af5996e..5ae88d86ac 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx @@ -53,25 +53,29 @@ model categories { } model post_in_categories { - category_id categories - post_id posts + category_id Int + post_id Int + categories categories @relation(fields: [category_id], references: [category_id]) + posts posts @relation(fields: [post_id], references: [post_id]) @@unique([post_id, category_id], name: "post_id_category_id_unique") } model posts { + author_id Int? content String? - created_at DateTime? + created_at DateTime? @default(now()) post_id Int @default(autoincrement()) @id title String - author_id users? + users users? @relation(fields: [author_id], references: [user_id]) post_in_categories post_in_categories[] } model profiles { bio String? profile_id Int @default(autoincrement()) @id - user_id users + user_id Int @unique + users users @relation(fields: [user_id], references: [user_id]) } model users { @@ -87,7 +91,7 @@ The are a few "issues" with this Prisma schema when the Prisma Client API is gen **Adhering to Prisma's naming conventions** -Prisma has a [naming convention]() of **camelCasing** and using the **singular form** for Prisma models. If these naming conventions are not met, the Prisma schema can become harder to interpret. Consider the following, generated model: +Prisma has a [naming convention]() of **camelCasing** and using the **singular form** for Prisma models. If these naming conventions are not met, the Prisma schema can become harder to interpret and the generated Prisma Client API will feel less natural. Consider the following, generated model: ```prisma model users { @@ -107,32 +111,38 @@ model User { } ``` -**Naming of foreign key relation fields** +Because these fields are [virtual relation fields]() you can manually rename them in your Prisma schema. -Foreign keys are represented as [relation fields]() in the Prisma schema. Here's how all the relations from the SQL schema are represented: +**Naming of physical relation fields** + +Foreign keys are represented as a combination of a [physical relation fields]() and a corresponding [link field]() in the Prisma schema. Here's how all the relations from the SQL schema are currently represented: ```prisma model categories { category_id Int @default(autoincrement()) @id - post_in_categories post_in_categories[] + post_in_categories post_in_categories[] // virtual relation field } model post_in_categories { - category_id categories - post_id posts + category_id Int // link field + post_id Int // link field + categories categories @relation(fields: [category_id], references: [category_id]) // virtual relation field + posts posts @relation(fields: [post_id], references: [post_id]) @@unique([post_id, category_id], name: "post_id_category_id_unique") } model posts { + author_id Int? post_id Int @default(autoincrement()) @id - author_id users? + users users? @relation(fields: [author_id], references: [user_id]) post_in_categories post_in_categories[] } model profiles { profile_id Int @default(autoincrement()) @id - user_id users + user_id Int @unique + users users @relation(fields: [user_id], references: [user_id]) } model users { diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx index d40ad6b972..1106372721 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx @@ -42,7 +42,8 @@ model Post { id Int @id @default(autoincrement()) title String published Boolean @default(true) - author User + author User @relation(fields: [authorId], references: [id]) + authorId Int } enum Role { @@ -59,7 +60,7 @@ await prisma.user.create({ data: { name: 'Alice' } }); await prisma.post.findMany(); ``` -## findOne +## `findOne` The `findOne` query lets you retrieve a single database record of a model based on an _ID_ or _unique_ attribute. You can use the `select` and `include` arguments to determine which fields should be included on the returned model object. diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx index 095a74ba58..ab24bfb4ea 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx @@ -34,19 +34,21 @@ model User { } model Profile { - id Int @id @default(autoincrement()) - user User + id Int @id @default(autoincrement()) + user User @relation(fields: [authorId], references: [id]) + userId Int } model Post { id Int @id @default(autoincrement()) - author User - categories Category[] + author User? @relation(fields: [authorId], references: [id]) + authorId Int? + categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] + posts Post[] @relation(references: [id]) } ``` @@ -72,7 +74,7 @@ const postsByUser = await prisma.post.findMany({ }); ``` -The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query. +The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query (see this [GitHub issue](https://github.com/prisma/prisma2/issues/1984)). This request returns all categories by a specific post: @@ -80,7 +82,7 @@ This request returns all categories by a specific post: const categoriesOfPost: Category[] = await prisma.post.findOne({ where: { id: 1 } }).categories(); ``` -Note that you can chain as many queries as you like. In this example, the chanining start at `Profile` and goes over `User` to `Post`: +Note that you can chain as many queries as you like. In this example, the chanining starts at `Profile` and goes over `User` to `Post`: ```ts const posts: Post[] = await prisma.profile @@ -92,7 +94,7 @@ const posts: Post[] = await prisma.profile The only requirement for chaining is that the previous function call must return only a _single object_ (e.g. as returned by a `findOne` query or a "to-one relation" like `profile.user()`). -The following query is **not possible** because `findMany` does not return a single object but a list: +The following query is **not possible** because `findMany` does not return a single object but a _list_: ```ts // This query is illegal @@ -120,7 +122,7 @@ const posts: Post[] = await prisma.user }); ``` -Note that this query is equivalent to the following one which is initiated via the `post` instead of the `user` field (i.e. it doesn't use the fluent API): +Note that this query is _equivalent_ to the following one which is initiated via the `post` instead of the `user` field (i.e. it doesn't use the fluent API): ```ts const posts = await prisma.post.findMany({ @@ -132,7 +134,7 @@ const posts = await prisma.post.findMany({ console.log(posts); ``` -The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query. +The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query (see this [GitHub issue](https://github.com/prisma/prisma2/issues/1984)). ## Nested writes @@ -140,11 +142,7 @@ Nested writes provide a way for writing relational data in your database. They f Nested writes can be nested arbitrarily deep. -Nested writes are available for [relation fields]() when using the model's `create` or `update` query. The following nested write options are available per query: - -| Query | Option | Description | -| :---- | :----- | :---------- | -| | | +Nested writes are available for [relation fields]() when using the model's `create` or `update` query. The following section shows the nested write options that are available per query. ### One-to-one relations @@ -158,24 +156,26 @@ model User { } model Profile { - id Int @id @default(autoincrement()) - bio String - user User? + id Int @id @default(autoincrement()) + bio String + user User? @relation(fields: [userId], references: [id]) + userId Int? } ``` -One-to-one relation fields (e.g. `profile` on `User` in the sample data model above) +The following nested write options for `Profile` are available in `prisma.user.create(...)` queries: + +- `create`: Create a new user and a new profile +- `connect`: Create a new user and connect it to an existing profile -- `create` - - `create`: Create a new user and a new profile - - `connect`: Create a new user and connect it to an existing profile -- `update` - - `create`: Update an existing user by creating a new profile - - `connect`: Update an an existing user by connecting it to an existing profile - - `update`: Update an existing user by updating their existing profile - - `upsert`: Update an existing user by updating their existing profile or by creating a new profile - - `delete` (only if relation is optional): Update an existing user by deleting their existing profile - - `disconnect` (only if relation is optional): Update an existing user by removing the connection to their existing profile +The following nested write options for `Profile` are available in `prisma.user.update(...)` queries: + +- `create`: Update an existing user by creating a new profile +- `connect`: Update an an existing user by connecting it to an existing profile +- `update`: Update an existing user by updating their existing profile +- `upsert`: Update an existing user by updating their existing profile or by creating a new profile +- `delete` (only if relation is optional): Update an existing user by deleting their existing profile +- `disconnect` (only if relation is optional): Update an existing user by removing the connection to their existing profile **Create a new `User` record with a new `Profile` record**: @@ -345,21 +345,22 @@ model Post { } ``` -One-to-many relation fields (e.g. `posts` on `User` in the sample data model above): +The following nested write options for `Post` are available in `prisma.user.create(...)` queries: + +- `create`: Create a new user and one or more new posts +- `connect`: Create a new user and connect it to one or more existing posts + +The following nested write options for `Post` are available in `prisma.update.update(...)` queries: -- `create` - - `create`: Create a new user and one or more new posts - - `connect`: Create a new user and connect it to one or more existing posts -- `update` - - `create`: Update an existing user by creating one or more new posts - - `connect`: Update an existing user by connecting it to one or more existing posts - - `update`: Update an existing user by updating one or more of their existing posts - - `upsert`: Update an existing user by updating one or more of their existing posts or by creating one or more new posts - - `delete`: Update an existing user by deleting one or more of their existing posts - - `disconnect`: Update an existing by removing the connection(s) to one or more of their existing posts - - `set`: Update an existing user by replacing their existing posts with one or more existing posts - - `updateMany`: Update an existing user by updating one or more of their existing posts - - `deleteMany`: Update an existing user by deleting one or more of their existing posts +- `create`: Update an existing user by creating one or more new posts +- `connect`: Update an existing user by connecting it to one or more existing posts +- `update`: Update an existing user by updating one or more of their existing posts +- `upsert`: Update an existing user by updating one or more of their existing posts or by creating one or more new posts +- `delete`: Update an existing user by deleting one or more of their existing posts +- `disconnect`: Update an existing by removing the connection(s) to one or more of their existing posts +- `set`: Update an existing user by replacing their existing posts with one or more existing posts +- `updateMany`: Update an existing user by updating one or more of their existing posts +- `deleteMany`: Update an existing user by deleting one or more of their existing posts **Create a new `User` record with a new `Post` record**: @@ -543,9 +544,9 @@ const user = await prisma.user.update({ ## Nested reads -With nested reads, you can modify the structures of the model objects that are returned by your Prisma Client queries by including their relations. In [ORM]() terminoloy, this is sometimes called _eager loading_. +With nested reads, you can modify the structures of the model objects that are returned by your Prisma Client queries by _including_ their relations. In [ORM]() terminoloy, this is sometimes called _eager loading_. -You can load relations of your models with the [`include`]() and [`select`]() options which you can pass to _any_ Prisma Client query (except for the batch operations `updateMany` and `deleteMany`), . `include` is more commonly used for relations, `select` is used for selecting specific fields. +You can load relations of your models with the [`include`]() and [`select`]() options which you can pass to _any_ Prisma Client query (except for the batch operations `updateMany` and `deleteMany`). `include` is more commonly used for relations, `select` is used for selecting specific fields. **Include the `posts` and `profile` relation when loading `User` records** diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx index 44a73193e1..b0953e1b5c 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx @@ -25,7 +25,8 @@ model Post { id Int @id @default(autoincrement()) title String published Boolean @default(true) - author User + author User @relation(fields: [authorId], references: [id]) + authorId Int } enum Role { @@ -36,7 +37,7 @@ enum Role { ## Selection sets -To understand which fields are being returned by a certain API call, you need to be aware of its **selection set**. +To understand which fields are being returned by a certain Prisma Client query, you need to be aware of its **selection set**. The selection set defines the **set of fields on a model instance that is returned in a Prisma Client API call**. @@ -45,7 +46,7 @@ Consider the following example `findOne` invocation: ```ts const result = await prisma.user.findOne({ where: { id: 1 }, -}); +}) ``` The `result` of this API call is a plain old JavaScript object that might look similar to this: @@ -65,7 +66,7 @@ All the fields that are contained in this object are scalar fields, enums or arr ## The default selection set -If the selection set is not manipulated (via `select` or `include`), a Prisma Client API call returns the **default selection set** for a model. It includes all [_scalar_](./data-modeling.md#scalar-types) fields (including [enums](./data-modeling.md#enums) and arrays/scalar lists) fields of the model. +If the selection set is not manipulated (via `select` or `include`), a Prisma Client API call returns the **default selection set** for a model. It includes all [scalar]() fields (including [enums]() and arrays/scalar lists) fields of the model. Considering the sample datamodel from above: From 97dd603698bdf58d1685079de7ba67aeca6a2fc1 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 19:25:26 +0100 Subject: [PATCH 34/76] relation docs --- .../01-prisma-schema/06-relations.mdx | 113 +++++++----------- 1 file changed, 42 insertions(+), 71 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index b7f64745bb..df777b9ae5 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -21,26 +21,26 @@ The examples on this page are based on the following schema file: ```prisma model User { id Int @id @default(autoincrement()) - posts Post[] // virtual relation field - profile Profile? // virtual relation field + posts Post[] + profile Profile? } model Profile { id Int @id @default(autoincrement()) - user User @relation(fields: [userId], references: [id]) // physical relation field - userId Int // link field + user User @relation(fields: [userId], references: [id]) + userId Int // scalar relation field } model Post { id Int @id @default(autoincrement()) - author User @relation(fields: [authorId], references: [id]) // physical relation field - authorId Int // link field - categories Category[] @relation(references: [id]) // virtual relation field + author User @relation(fields: [authorId], references: [id]) + authorId Int // scalar relation field + categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] @relation(references: [id]) // virtual relation field + posts Post[] @relation(references: [id]) } ``` @@ -50,7 +50,7 @@ model Category { ### Cardinality -There are three different [cardinalities](https://en.wikipedia.org/wiki/Cardinality_(data_modeling)) of relations in Prisma: +There are three different [cardinalities]() of relations in Prisma: - One-to-one (also called 1-1-relation) - One-to-many (also called 1-n-relation) @@ -66,7 +66,7 @@ In the example above, there are the following relations: Relation fields are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. -A relation field is always either [physically]() backed by a foreign key in the underlying database or it is [virtual]() (which means that it's not "visible" in the schema of the underlying database). +Every very relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required. Consider these two models: @@ -88,16 +88,16 @@ model Post { These models have the following fields: -| Model | Field | Type | Relation field | -| :----- | :--------- | :------- | :--------------------------------- | -| `User` | `id` | `Int` | No | -| | `email` | `String` | No | -| | `role` | `Role` | No | -| | `posts` | `Post[]` | **Yes** (_virtual_) | -| `Post` | `id` | `Int` | No | -| | `title` | `String` | No | -| | `authorId` | `Int` | No (_link field_) | -| | `author` | `User` | **Yes** (_physical / foreign key_) | +| Model | Field | Type | Relation field | +| :----- | :--------- | :------- | :--------------------------- | +| `User` | `id` | `Int` | No | +| | `email` | `String` | No | +| | `role` | `Role` | No | +| | `posts` | `Post[]` | **Yes** | +| `Post` | `id` | `Int` | No | +| | `title` | `String` | No | +| | `authorId` | `Int` | No (_relation scalar field_) | +| | `author` | `User` | **Yes** (_annotated_) | Both `posts` and `author` are relation fields because their types are not scalar types but other models. @@ -146,7 +146,7 @@ model Category { } ``` -Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. +Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. Note that this m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). @@ -206,57 +206,30 @@ A link field always has a scalar type and is the direct representation of a fore ```prisma model User { id Int @id @default(autoincrement()) - posts Post[] // virtual relation field - profile Profile? // virtual relation field + posts Post[] + profile Profile? } model Profile { id Int @id @default(autoincrement()) - user User @relation(fields: [userId], references: [id]) // physical relation field - userId Int // link field (that gets referenced in the `@relation` attribute above) + user User @relation(fields: [userId], references: [id]) + userId Int // scalar relation field (referenced in the `@relation` attribute above) } model Post { id Int @id @default(autoincrement()) - author User @relation(fields: [authorId], references: [id]) // physical relation field - authorId Int // link field (that gets referenced in the `@relation` attribute above) - categories Category[] // virtual relation field + author User @relation(fields: [authorId], references: [id]) + authorId Int // scalar relation field (referenced in the `@relation` attribute above) + categories Category[] } ``` -Note that if the physical relation field is [required](), its link field counterpart also must be required. If the physical relation field is [optional](), the link field also must be optional. - -### Virtual relation fields - -Virtual relation fields are relation fields in the Prisma schema that are not "manifested" in the database schema. - -There are two different kinds of virtual relation fields. - -For **1-1 and 1-n relations**, one side of the relation represents a foreign key, the other side is a virtual relation field: - - - -![](https://imgur.com/nycymr8.png) - -For **implicit m-n-relations**, both relation fields are virtual since neither of them _directly_ maps to a foreign key: +Note that if the annotated relation field is [required](), its relation scalar field counterpart also must be required. If the annotated relation field is [optional](), the relation scalar field also must be optional. -![](https://imgur.com/DxuOs88.png) - -Prisma always requires both sides of a relation to be present, this means that one virtual relation field always needs to be added per relation. When [formatting the Prisma schema](), the formatter automatically inserts any missing virtual relation fields for you to save some typing work. - -Virtual relation fields are also present in the generated [Prisma Client API]() which makes working with relations more convenient as you can traverse relationships in your code in both directions, for example: - -```js -// Traverse relation from `Post` to `User` via fluent API -const user = await prisma.post.findOne({ where: { id: 1 } }).author(); - -// Traverse relation from `User` to `Post` via fluent API -const user = await prisma.user.findOne({ where: { id: 1 } }).posts(); -``` ## The @relation attribute -The `@relation` attribute can only be applied to the [relation fields]() of a Prisma model, not to its [scalar fields](). +The `@relation` attribute can only be applied to the [relation fields]() of a Prisma model, not to its [scalar fields](). It is _always_ required on [physical relation fields]() and _sometimes_ required on [virtual relation fields](). @@ -302,7 +275,7 @@ model User { model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int + userId Int // scalar relation field (referenced in the `@relation` attribute above) } ``` @@ -409,7 +382,6 @@ This is what the relation looks like in the database: ![](https://imgur.com/N5wHT6D.png) - However, you can still determine yourself on which side of the relation the foreign key should be stored. To store the foreign key on `User` you need to add the `@relation` attribute to its relation field and add a corresponding link field: **Both relation fields required but using `@relation` to determine the foreign key** @@ -466,11 +438,11 @@ model User { model Post { id Int @id @default(autoincrement()) author User @relation(fields: [authorId], references: [author]) - authorId Int + authorId Int } ``` -Notice that the `posts` field on `User` is [virtual](), meaning that it's not manifested in the underlying database schema. On the other side of the relation, the [physical relation field]() `author` and the [link field]() `authorId` represent the foreign key in the underlying database. +Notice that the `posts` field on `User` is [virtual](), meaning that it's not manifested in the underlying database schema. On the other side of the relation, the [physical relation field]() `author` and the [link field]() `authorId` represent the foreign key in the underlying database. This 1-n-relation expresses the following: @@ -514,7 +486,7 @@ model User { model Post { id Int @id @default(autoincrement()) author User? @relation(fields: [authorId], references: [author]) - authorId Int? + authorId Int? } ``` @@ -528,8 +500,8 @@ model User { model Post { id Int @id @default(autoincrement()) - author User? @relation(fields: [authorId], references: [author]) - authorId Int? + author User? @relation(fields: [authorId], references: [author]) + authorId Int? } ``` @@ -545,12 +517,12 @@ In the example above, there's one _implicit_ m-n-relation betwen `Post` and `Cat ```prisma model Post { id Int @id @default(autoincrement()) - categories Category[] @relation(references: [id]) + categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] @relation(references: [id]) + posts Post[] @relation(references: [id]) } ``` @@ -733,7 +705,6 @@ model User { } ``` - This relation expresses the following: - "a user has zero or one _husband_ " @@ -865,9 +836,9 @@ model Post { id Int @id @default(autoincrement()) title String? author User @relation(fields: [authorId], references: [id]) - authorId Int + authorId Int pinnedBy User? @relation(fields: [pinnedById], references: [id]) - pinnedById Int? + pinnedById Int? } ``` @@ -892,8 +863,8 @@ model Post { id Int @id @default(autoincrement()) title String? author User @relation("WrittenPosts", fields: [authorId], references: [id]) - authorId Int + authorId Int pinnedBy User? @relation(name: "PinnedPost", fields: [pinnedById], references: [id]) - pinnedById Int? + pinnedById Int? } ``` From ce24bf8efb714add9580bad95c056bfb59e966f0 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 19:31:57 +0100 Subject: [PATCH 35/76] relation docs --- .../01-prisma-schema/06-relations.mdx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index df777b9ae5..caf47e3968 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -28,19 +28,19 @@ model User { model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int // scalar relation field + userId Int // scalar relation field (linked in the `@relation` attribute above) } model Post { id Int @id @default(autoincrement()) author User @relation(fields: [authorId], references: [id]) - authorId Int // scalar relation field + authorId Int // scalar relation field (linked in the `@relation` attribute above) categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] @relation(references: [id]) + posts Post[] @relation(references: [id]) } ``` @@ -64,9 +64,9 @@ In the example above, there are the following relations: ### Relation fields -Relation fields are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. +Relation [fields]() are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. -Every very relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required. +Every relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required which gets linked by one of the two relation fields. This relation scalar is the direct representation of the _foreign key_ in the underlying database. Consider these two models: @@ -82,7 +82,7 @@ model Post { id Int @id @default(autoincrement()) title String author User @relation(fields: [authorId], references: [id]) - authorId Int + authorId Int // relation scalar field (linked in the `@relation` attribute above) } ``` @@ -101,7 +101,7 @@ These models have the following fields: Both `posts` and `author` are relation fields because their types are not scalar types but other models. -Also note that the physical relation field `author` needs to reference the link field `authorId` on the `Post` model inside the `@relation` attribute. +Also note that the annotated relation field `author` needs to link the scalar relation field `authorId` on the `Post` model inside the `@relation` attribute. ### Implicit vs explicit many-to-many relations From 8dd9e7852fb63c4f4659e08608255016746ee9f8 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 19:45:06 +0100 Subject: [PATCH 36/76] relation docs --- .../01-prisma-schema/06-relations.mdx | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index caf47e3968..a9668ac7c3 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -8,11 +8,34 @@ metaDescription: '' This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. +A relation is a _connection_ between two models in the Prisma schcema. A relation must always be defined with two _relation fields_, one on each the model. In the case of one-to-one and one-to-many relations, an additional _relation scalar field_ must be added: + +```prisma. +model User { + id Int @id @default(autoincrement()) + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + author User @relation(fields: [authorId], references: [id]) + authorId Int // scalar relation field (linked in the `@relation` attribute above) +} +``` + +> **Note**: In SQL, relations between models are _physically_ represented via _foreign keys_ in the underlying database. A foreign key is only stored on _one_ side of a relation. As opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. +> This means that one side of the relation represents the _physical foreign key_ in the underlying database, the other relation field is a _virtual relation field_ (in the case of [implicit many-to-many relations]()), both relation fields are virtual. + + + ## Example From 9c4907041594d1a768b12c99eecfc63d84248e61 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 22:48:33 +0100 Subject: [PATCH 37/76] relation docs --- .../01-prisma-schema/06-relations.mdx | 292 ++++++++++++++---- 1 file changed, 224 insertions(+), 68 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index a9668ac7c3..6489519793 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -8,7 +8,7 @@ metaDescription: '' This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. -A relation is a _connection_ between two models in the Prisma schcema. A relation must always be defined with two _relation fields_, one on each the model. In the case of one-to-one and one-to-many relations, an additional _relation scalar field_ must be added: +A relation is a _connection_ between two models in the Prisma schema. A relation must always be defined with two _relation fields_, one on each the model. In the case of one-to-one and one-to-many relations, an additional _relation scalar field_ must be added: ```prisma. model User { @@ -19,21 +19,21 @@ model User { model Post { id Int @id @default(autoincrement()) author User @relation(fields: [authorId], references: [id]) - authorId Int // scalar relation field (linked in the `@relation` attribute above) + authorId Int // relation scalar field (used in the `@relation` attribute above) } ``` -> **Note**: In SQL, relations between models are _physically_ represented via _foreign keys_ in the underlying database. A foreign key is only stored on _one_ side of a relation. As opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. -> This means that one side of the relation represents the _physical foreign key_ in the underlying database, the other relation field is a _virtual relation field_ (in the case of [implicit many-to-many relations]()), both relation fields are virtual. +> **Note**: In SQL, relations between models are represented via _foreign keys_ in the underlying database. A foreign key is only stored on _one_ side of a relation. As opposed to how relations are modeled in SQL, **Prisma always requires explicit relation fields on _both_ sides of the relation to be set on your Prisma models**. +> +> This means that one side of the relation represents the _foreign key_ in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level). - - @@ -51,23 +51,23 @@ model User { model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int // scalar relation field (linked in the `@relation` attribute above) + userId Int // relation scalar field (used in the `@relation` attribute above) } model Post { id Int @id @default(autoincrement()) author User @relation(fields: [authorId], references: [id]) - authorId Int // scalar relation field (linked in the `@relation` attribute above) + authorId Int // relation scalar field (used in the `@relation` attribute above) categories Category[] @relation(references: [id]) } model Category { id Int @id @default(autoincrement()) - posts Post[] @relation(references: [id]) + posts Post[] @relation(references: [id]) } ``` -> **Note**: This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [link fields]()) so you can focus on the relation fields. +> **Note**: This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [relation scalars]()) so you can focus on the relation fields. ## Terminology @@ -89,7 +89,7 @@ In the example above, there are the following relations: Relation [fields]() are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. -Every relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required which gets linked by one of the two relation fields. This relation scalar is the direct representation of the _foreign key_ in the underlying database. +Every relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required which gets linked by one of the two relation fields in the `@relation` attribute. This relation scalar is the direct representation of the _foreign key_ in the underlying database. Consider these two models: @@ -105,7 +105,7 @@ model Post { id Int @id @default(autoincrement()) title String author User @relation(fields: [authorId], references: [id]) - authorId Int // relation scalar field (linked in the `@relation` attribute above) + authorId Int // relation scalar field (used in the `@relation` attribute above) } ``` @@ -124,7 +124,7 @@ These models have the following fields: Both `posts` and `author` are relation fields because their types are not scalar types but other models. -Also note that the annotated relation field `author` needs to link the scalar relation field `authorId` on the `Post` model inside the `@relation` attribute. +Also note that the annotated relation field `author` needs to link the relation scalar field `authorId` on the `Post` model inside the `@relation` attribute. ### Implicit vs explicit many-to-many relations @@ -146,10 +146,12 @@ model Category { } model CategoriesOnPosts { - post Post - category Category + post Post @relation(fields: [postId], references: [id]) + postId Int // relation scalar field (used in the `@relation` attribute above) + category Category @relation(fields: [categoryId], references: [id]) + categoryId Int // relation scalar field (used in the `@relation` attribute above) - @@id([post, category]) + @@id([postId, categoryId]) } ``` @@ -171,17 +173,17 @@ model Category { Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. -Note that this m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). +This m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). ### Relation tables -A relation table (also sometimes called _JOIN_, _link_ or _pivot_ table) connects two or more other tables and therefore creates a _relation_ between them. Creating relation tables is a common data modeling practice in SQL to represent relationships between different entities. +A relation table (also sometimes called _JOIN_, _link_ or _pivot_ table) connects two or more other tables and therefore creates a _relation_ between them. Creating relation tables is a common data modeling practice in SQL to represent relationships between different entities. In essence it means that "one m-n relation is modeled as two 1-n relations in the database". -When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both relation fields are both [physical relation fields]() that each _reference_ a link field. +When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both annotated relation fields with a corresponding relation scalar field. -Relation tables are also often used to add "meta-information" to a relation. For example, _when_ the relation was created. +Relation tables are also often used to add "meta-information" to a relation. For example, to store _when_ the relation was created. Here is an example for a relation table called `CategoriesOnPosts`: @@ -211,56 +213,119 @@ model CategoriesOnPosts { In this example, the `createdAt` field stores additional information about the relation between `Post` and `Category` (i.e. it stores the point in time when "the post was added to the catgegory"). -Note that the same rules as for [1-n-relations]() apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations): +Note that the same rules as for [1-n-relations]() apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations), which means one side of the relation needs to be annotated with the `@relation` attribute. + +When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). + +### Annotated relation fields and relation scalar fields -- The relation field on one side must be [virtual]() (here these are `posts` and `categories`) -- The relation field on the other side must be [physical]() and _reference_ a [link field]() +1-1 and 1-n relations require one side of the relation to be _annotated_ with the `@relation` attribute, they're therefore commonly referred to as _annotated relation fields_. -When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but get your data model from introspection, you can s +The side of the relation which is annotated with the `@relation` attribute represents the side that stores the foreign key in the underlying database. The "actual" field that represents the foreign key is required on that side of the relation as well, it's called _relation scalar field_ and must be used in the `@relation` attribute on the annotated relation field. A scalar field _becomes_ a relation scalar field when it's used in the `fields` of an `@relation` attribute. -### Physical relation fields (foreign key) +Because a relation scalar field always _belongs_ to a relation field, the two are often named the same but the relation scalar is suffixed with `Id`. For example, assume an annotated relation field is called `author`, the corresponding relation scalar would be called `authorId` according to this convention. -Physical relation relation fields are relation fields that are _physically_ backed by a foreign key in the underlying database. **They always require the `@relation attribute which must point to a link field**. +Note that relation scalar fields are read-only in the generated [Prisma Client API](). If you want to update a relation in your code, you can do so using [nested writes](). -### Link fields +In **1-1 relations**, you can decide yourself which side of the relation you want to annotate with the `@relation` attribute (and therefore holds the foreign key). -A link field always has a scalar type and is the direct representation of a foreign key in the underlying database. It must be _referenced_ inside the `@relation` attribute of its physical relation field: +This example annotates the relation field on the `Profile` model: ```prisma model User { id Int @id @default(autoincrement()) - posts Post[] profile Profile? } model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int // scalar relation field (referenced in the `@relation` attribute above) + userId Int // relation scalar field (used in the `@relation` attribute above) +} +``` + +In the code above, the `userId` relation scalar is a direct representation of the foreign key in the underlying database. + +This example annotates the relation field on the `Profile` model: + +```prisma +model User { + id Int @id @default(autoincrement()) + profile Profile? @relation(fields: [profileId], references: [id]) + profileId Int? // relation scalar field (used in the `@relation` attribute above) +} + +model Profile { + id Int @id @default(autoincrement()) + user User +} +``` + +In the code above, `profileId` is a direct representation of the foreign key in the underlying database. + +In **1-n-relations**, you must annotate the non-list field with the `@relation` attribute: + +```prisma +model User { + id Int @id @default(autoincrement()) + email String @unique + role Role @default(USER) + posts Post[] } model Post { - id Int @id @default(autoincrement()) - author User @relation(fields: [authorId], references: [id]) - authorId Int // scalar relation field (referenced in the `@relation` attribute above) - categories Category[] + id Int @id @default(autoincrement()) + title String + author User @relation(fields: [authorId], references: [id]) + authorId Int // relation scalar field (used in the `@relation` attribute above) +} +``` + +Note that for **1-1 and 1-n relations**, the annotated relation field and its relation scalar field must either _both be optional_ or _both be required_. So, the following would be illegal because `user` is optional but `userId` is required: + +```prisma +model User { + id Int @id @default(autoincrement()) + profile Profile? +} + +model Profile { + id Int @id @default(autoincrement()) + user User? @relation(fields: [userId], references: [id]) // ILLEGAL + userId Int // relation scalar field (used in the `@relation` attribute above) } ``` -Note that if the annotated relation field is [required](), its relation scalar field counterpart also must be required. If the annotated relation field is [optional](), the relation scalar field also must be optional. +With [multi-field IDs](), there might also be multiple relation scalars on the same model which are both used in the `@relation`attribute: + +```prisma +model User { + firstName String + lastName String + profile Profile? + + @@id([firstName, lastName]) +} +model Profile { + id Int @id @default(autoincrement()) + user User @relation(fields: [authorFirstName, authorLastName], references: [firstName, lastName]) + authorFirstName String // relation scalar field (used in the `@relation` attribute above) + authorLastName String // relation scalar field (used in the `@relation` attribute above) +} +``` ## The @relation attribute -The `@relation` attribute can only be applied to the [relation fields]() of a Prisma model, not to its [scalar fields](). +The `@relation` attribute can only be applied to the [relation fields](), not to [scalar fields](). -It is _always_ required on [physical relation fields]() and _sometimes_ required on [virtual relation fields](). +It must be added to _every_ relation in your Prisma schema. In [implicit m-n relations](), it is required on both sides of the relation. In 1-1 and 1-n relations, it is only required on one side. -Here are some cases when the `@relation` attribute is required, e.g. when: +Here are some example scenarios when the `@relation` attribute is needed, e.g. when: +- you define a 1-1 or 1-n relation, it is required on _one side_ of the relation (with the corresponding relation scalar field) - you need to disambiguate a relation (that's e.g. the case when you have two relations between the same models) - you define a [self-relation](#self-relations) - - you need to control how the relation table is represented in the underlying database (e.g. use a specific name for a relation table) ### Signature @@ -274,12 +339,8 @@ Here are some cases when the `@relation` attribute is required, e.g. when: | Argument | Type | Required | Description | Example | | :----------- | :----------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | | `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | -| `fields` | `FieldReference[]` | On physical relation fields | A list of [fields]() of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | -| `references` | `FieldReference[]` | On physical relation fields | A list of [fields]() of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | - - +| `fields` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | +| `references` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | ## One-to-one relations @@ -298,10 +359,12 @@ model User { model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int // scalar relation field (referenced in the `@relation` attribute above) + userId Int // relation scalar field (used in the `@relation` attribute above) } ``` +In the code above, the `userId` relation scalar is a direct representation of the foreign key in the underlying database. + This 1-1-relation expresses the following: - "a user can have zero or one profiles" (because the `profile` field is [optional]() on `User`) @@ -316,13 +379,46 @@ CREATE TABLE "User" ( CREATE TABLE "Profile" ( id SERIAL PRIMARY KEY, "userId" INTEGER NOT NULL UNIQUE, - FOREIGN KEY ("useIdr") REFERENCES "User"(id) + FOREIGN KEY ("userId") REFERENCES "User"(id) ); ``` -Notice the `UNIQUE` constraint on the foreign key `userId`. If this `UNIQUE` constrain was missing, the relation would be considered a 1-n relation. +Notice the `UNIQUE` constraint on the foreign key `userId`. If this `UNIQUE` constraint was missing, the relation would be considered a 1-n relation. + +You can also define this relation using [multi-field IDs](): + +```prisma +model User { + firstName String + lastName String + profile Profile? + + @@id([firstName, lastName]) +} + +model Profile { + id Int @id @default(autoincrement()) + user User @relation(fields: [userFirstName, userLastName], references: [firstName, lastName]) + userFirstName String // relation scalar field (used in the `@relation` attribute above) + userLastName String // relation scalar field (used in the `@relation` attribute above) +} +``` + +In this case, there are _two_ relation scalar fields on `Profile`. This is what the models map to in SQL: -The link field `userId` on `Profile` model in the Prisma schema above maps to the `userId` column in the database. +```sql +CREATE TABLE "User" ( + firstName TEXT, + lastName TEXT, + PRIMARY KEY ("firstName","lastName") +); +CREATE TABLE "Profile" ( + id SERIAL PRIMARY KEY, + "userFirstName" TEXT NOT NULL UNIQUE, + "userLastName" TEXT NOT NULL UNIQUE, + FOREIGN KEY ("userFirstName", "userLastName") REFERENCES "User"("firstName", "lastName") +); +``` ### Making both sides required in one-to-one relations @@ -383,7 +479,7 @@ If you're using [introspection](), you can make 1-1-relations required by manual ### Determining the side of the foreign key -Consider again the above 1-1-relation between `User` and `Profile` where `profile` is optional on `User`: +Consider again the above 1-1-relation between `User` and `Profile`. The relation field on the `Profile` model is annotated with the `@relation` attribute: ```prisma model User { @@ -395,17 +491,32 @@ model User { model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) - userId Int + userId Int // relation scalar field (used in the `@relation` attribute above) +} +``` + +You can also annotate the other side of the relation with the `@relation` attribute. The following example annotates the relation field on the `User` model: + +```prisma +model User { + id Int @id @default(autoincrement()) + profile Profile? @relation(fields: [profileId], references: [id]) + profileId Int? // relation scalar field (used in the `@relation` attribute above) +} + +model Profile { + id Int @id @default(autoincrement()) + user User } ``` -Because the `Profile` model has a [physical relation field]() (called `user`) and a [link field]() (called `userId`), it represents the foreign key in the underlying database. The `profile` relation field on `User` is [virtual](). +In the code above, `profileId` is a direct representation of the foreign key in the underlying database. This is what the relation looks like in the database: ![](https://imgur.com/N5wHT6D.png) -However, you can still determine yourself on which side of the relation the foreign key should be stored. To store the foreign key on `User` you need to add the `@relation` attribute to its relation field and add a corresponding link field: +However, you can still determine yourself on which side of the relation the foreign key should be stored. To store the foreign key on `User` you need to add the `@relation` attribute to its relation field and add a corresponding relation scalar field: **Both relation fields required but using `@relation` to determine the foreign key** @@ -413,7 +524,7 @@ However, you can still determine yourself on which side of the relation the fore model User { id Int @id @default(autoincrement()) profile Profile @relation(fields: [profileId], references: [id]) // references `id` of `Profile` - profileId Int + profileId Int // relation scalar field (used in the `@relation` attribute above) } model Profile { @@ -465,7 +576,7 @@ model Post { } ``` -Notice that the `posts` field on `User` is [virtual](), meaning that it's not manifested in the underlying database schema. On the other side of the relation, the [physical relation field]() `author` and the [link field]() `authorId` represent the foreign key in the underlying database. +> **Note** The `posts` field does not "manifest" in the underlying database schema. On the other side of the relation, the [annotated relation field]() `author` and the [relation scalar]() `authorId` represent the side of the relation that stores the foreign key in the underlying database. This 1-n-relation expresses the following: @@ -487,16 +598,57 @@ CREATE TABLE "Post" ( Since there's no `UNIQUE` constraint on the `author` column (foreign key), you can create multiple `Post` records that point to the same `User` record therefore creating a one-to-many relationship between the two tables. +You can also define this relation using [multi-field IDs](): + +```prisma +model User { + firstName String + lastName String + post Post[] + + @@id([firstName, lastName]) +} + +model Post { + id Int @id @default(autoincrement()) + author User @relation(fields: [authorFirstName, authorLastName], references: [firstName, lastName]) + authorFirstName String // relation scalar field (used in the `@relation` attribute above) + authorLastName String // relation scalar field (used in the `@relation` attribute above) +} +``` + +In this case, there are _two_ relation scalar fields on `Post`. This is what the models map to in SQL: + +```sql +CREATE TABLE "User" ( + firstName TEXT, + lastName TEXT, + PRIMARY KEY ("firstName","lastName") +); +CREATE TABLE "Post" ( + id SERIAL PRIMARY KEY, + "authorFirstName" TEXT NOT NULL UNIQUE, + "authorLastName" TEXT NOT NULL UNIQUE, + FOREIGN KEY ("authorFirstName", "authorLastName") REFERENCES "User"("firstName", "lastName") +); +``` + ### Required vs optional relation fields in one-to-many relations -A 1-n-relation always has one [virtual relation field]() (which must be a [list]()) and a [physical relation field]() that references a [link field](). In the example above, `posts` on the `User` model is virtual, `author` represents a foreign key and `authorId` is a link field. + + +A 1-n-relation always has two relation fields: -The relation fields in a relation can take the following forms: +- a [list]() relation field which is _not_ annotated with `@relation` +- the [annotated relation field]() (including its relation scalar) -- the physical relation field can be either optional or required -- if the physical relation field is required, the link field must be required -- if the physical relation field is optional, the link field must be optional -- the virtual relation field must be a list and is always required +The relation fields in a 1-n relation can take the following forms: + +- the annotated relation field can be either optional or required + - if the annotated relation field is required, the relation scalar must be required + - if the annotated relation field is optional, the relation scalar must be optional +- the other side of the relation must a list and is always required So, the following variant of the example above would be _allowed_: @@ -549,7 +701,7 @@ model Category { } ``` -Notice that the `posts` field on `Category` and the `categories` field on `Post` both are [virtual](), meaning that they're not manifested in the underlying database schema. Instead, the implicit many-to-many relation is maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. +Implicit many-to-many relations are maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. Both fields require the `@relation` attribute to specify the fields they _reference_ on the other model. @@ -614,9 +766,9 @@ model Category { model CategoriesOnPosts { post Post @relation(fields: [postId], references: [id]) - postId Int + postId Int // relation scalar field (used in the `@relation` attribute above) category Category @relation(fields: [catgoryId], references: [id]) - catgoryId Int + catgoryId Int // relation scalar field (used in the `@relation` attribute above) createdAt DateTime @default(now()) @@id([postId, categoryId]) @@ -735,9 +887,13 @@ This relation expresses the following: Note that one-to-one self-relations can not be made required on both sides, one field has to be optional. -In this case, the `wife` relation field is [virtual](). The `husband` field on the other hand is a [physical relation field](), this means it is backed by a foreign key in the underlying database. Here, `id` is the [link field]() that's referenced by `husband`. +Self-relations always require the `@relation` attribute on both sides of the relation. On both ends, you need provide the same relation _name_. + +The `husband` field on the other hand is the [annotated relation field]() (although here the term is ambiguous because both relation fields are annotated with the `@relation` attribute, however here this refers too the field that also has the `fields` and `references` arguments). + +The annotated field is backed by a foreign key in the underlying database. Here, `id` is the [relation scalar]() that's referenced by `husband`. -You can also switch the virtual and physical relation fields: +You can again determine which side of the relation should store the foreign key in the underlying database: ```prisma model User { @@ -757,7 +913,7 @@ model User { } ``` -Now the foreign key is stored on `wife` and `husband` is virtual. +Now the foreign key is stored on `wife`, `husband` is provided on a Prisma-level (e.g. it will be available in the Prisma Client API). This relation is represented as follows in SQL: From 303cca3415fc8b5b936480d986a2563ecc67db61 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sat, 28 Mar 2020 23:59:33 +0100 Subject: [PATCH 38/76] relation docs --- .../03-is-prisma-an-orm.mdx} | 0 ...data-modeling.mdx => 04-data-modeling.mdx} | 0 ...-hood.mdx => 05-prisma-under-the-hood.mdx} | 0 .../01-prisma-schema/06-relations.mdx | 33 +++++++++++++++++++ content/index.mdx | 20 +++++------ 5 files changed, 43 insertions(+), 10 deletions(-) rename content/02-understand-prisma/{04-is-prisma-an-orm.mdx => 03-prisma-in-your-stack/03-is-prisma-an-orm.mdx} (100%) rename content/02-understand-prisma/{05-data-modeling.mdx => 04-data-modeling.mdx} (100%) rename content/02-understand-prisma/{06-prisma-under-the-hood.mdx => 05-prisma-under-the-hood.mdx} (100%) diff --git a/content/02-understand-prisma/04-is-prisma-an-orm.mdx b/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx similarity index 100% rename from content/02-understand-prisma/04-is-prisma-an-orm.mdx rename to content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx diff --git a/content/02-understand-prisma/05-data-modeling.mdx b/content/02-understand-prisma/04-data-modeling.mdx similarity index 100% rename from content/02-understand-prisma/05-data-modeling.mdx rename to content/02-understand-prisma/04-data-modeling.mdx diff --git a/content/02-understand-prisma/06-prisma-under-the-hood.mdx b/content/02-understand-prisma/05-prisma-under-the-hood.mdx similarity index 100% rename from content/02-understand-prisma/06-prisma-under-the-hood.mdx rename to content/02-understand-prisma/05-prisma-under-the-hood.mdx diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 6489519793..b19d008f74 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -1047,3 +1047,36 @@ model Post { pinnedById Int? } ``` + + \ No newline at end of file diff --git a/content/index.mdx b/content/index.mdx index 8825773bd2..da2c099389 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -6,9 +6,9 @@ metaDescription: '' ## Overview -Welcome to the Prisma documentation! You can find an overview of the available content in the sections below. The fastest way to get started with Prisma is the [**Quickstart**](). +Welcome to the Prisma documentation! You can find an overview of the available content in the sections below. The fastest way to get started with Prisma is the [**Quickstart**](./getting-started/quickstart). -> **If you're using Prisma 1, please refer to the [Prisma 1 documentation]().** +> **If you're using Prisma 1, please refer to the [Prisma 1 documentation](https://www.prisma.io/docs/1.34).** ## Table of contents @@ -18,10 +18,10 @@ Welcome to the Prisma documentation! You can find an overview of the available c The **Getting started** section contains _practical guides_ to help you get started with Prisma. -- [Quickstart]() +- [Quickstart](./getting-started/quickstart) - Setup Prisma - - [Add Prisma to an existing project]() - - [Start from scratch (SQL migrations)]() + - [Add Prisma to an existing project](./getting-started/add-prisma-to-an-existing-project) + - [Start from scratch (SQL migrations)](./getting-started/setup-prisma/start-from-scratch-sql-migrations) --- @@ -29,12 +29,12 @@ The **Getting started** section contains _practical guides_ to help you get star The **Understand Prisma** section contains _conceptual_ information about Prisma. -- [Introduction]() -- [Why Prisma?]() +- [Introduction](./understand-prisma/introduction) +- [Why Prisma?](./understand-prisma/why-prisma) - Prisma in your stack - - [REST]() - - [GraphQL]() -- [Is Prisma an ORM?]() + - [REST](./understand-prisma/prisma-in-your-stack/rest) + - [GraphQL](./understand-prisma/prisma-in-your-stack/graphql) + - [Is Prisma an ORM?]() - [Data modeling]() - [Under the hood]() From f821b03fa3add000ef8969087e19236715e5e320 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 00:32:52 +0100 Subject: [PATCH 39/76] continue docs --- ...der-the-hood.mdx => 05-under-the-hood.mdx} | 0 content/index.mdx | 130 ++++++++++-------- 2 files changed, 74 insertions(+), 56 deletions(-) rename content/02-understand-prisma/{05-prisma-under-the-hood.mdx => 05-under-the-hood.mdx} (100%) diff --git a/content/02-understand-prisma/05-prisma-under-the-hood.mdx b/content/02-understand-prisma/05-under-the-hood.mdx similarity index 100% rename from content/02-understand-prisma/05-prisma-under-the-hood.mdx rename to content/02-understand-prisma/05-under-the-hood.mdx diff --git a/content/index.mdx b/content/index.mdx index da2c099389..2f17f96cb6 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -20,7 +20,7 @@ The **Getting started** section contains _practical guides_ to help you get star - [Quickstart](./getting-started/quickstart) - Setup Prisma - - [Add Prisma to an existing project](./getting-started/add-prisma-to-an-existing-project) + - [Add Prisma to an existing project](./getting-started/setup-prisma/add-to-an-existing-project) - [Start from scratch (SQL migrations)](./getting-started/setup-prisma/start-from-scratch-sql-migrations) --- @@ -34,9 +34,9 @@ The **Understand Prisma** section contains _conceptual_ information about Prisma - Prisma in your stack - [REST](./understand-prisma/prisma-in-your-stack/rest) - [GraphQL](./understand-prisma/prisma-in-your-stack/graphql) - - [Is Prisma an ORM?]() -- [Data modeling]() -- [Under the hood]() + - [Is Prisma an ORM?](./understand-prisma/prisma-in-your-stack/is-prisma-an-orm) +- [Data modeling](./understand-prisma/data-modeling) +- [Under the hood](./understand-prisma/under-the-hood) --- @@ -46,46 +46,47 @@ The **Reference** section contains _technical_ information about Prisma. - Tools and interfaces - Prisma schema - - [Prisma schema file]() - - [Data sources]() - - [Generators]() - - [Data model]() - - [Models]() - - [Relations]() + - [Prisma schema file](./reference/tools-and-interfaces/prisma-schema/prisma-schema-file) + - [Data sources](./reference/tools-and-interfaces/prisma-schema/data-sources) + - [Generators](./reference/tools-and-interfaces/prisma-schema/generators) + - [Data model](./reference/tools-and-interfaces/prisma-schema/data-model) + - [Models](./reference/tools-and-interfaces/prisma-schema/models) + - [Relations](./reference/tools-and-interfaces/prisma-schema/relations) - Prisma Client - - [Generating Prisma Client]() - - [Configuring the Prisma Client API]() - - [CRUD]() - - [Relation queries]() - - [Field selection]() - - [Raw database access]() - - [Connection management]() - - [Advanced usage of generated types]() - - [Filtering]() + - [Generating Prisma Client](./reference/tools-and-interfaces/prisma-client/generating-prisma-client) + - [Configuring the Prisma Client API](./reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api) + - [CRUD](./reference/tools-and-interfaces/prisma-client/crud) + - [Relation queries](./reference/tools-and-interfaces/prisma-client/relation-queries) + - [Field selection](./reference/tools-and-interfaces/prisma-client/field-selection) + - [Raw database access](./reference/tools-and-interfaces/prisma-client/raw-database-access) + - [Connection management](./reference/tools-and-interfaces/prisma-client/connection-management) + - [Advanced usage of generated types](./reference/tools-and-interfaces/prisma-client/advancd-usage-of-generated-types) + + - [Logging](./reference/tools-and-interfaces/prisma-client/logging) + - [Debugging](./reference/tools-and-interfaces/prisma-client/debugging) + - [Error formatting](./reference/tools-and-interfaces/prisma-client/error-formatting) + - [Transactions](./reference/tools-and-interfaces/prisma-client/transactions) + - [Deployment](./reference/tools-and-interfaces/prisma-client/deployment) + - [Query engine](./reference/tools-and-interfaces/prisma-client/query-engine) + - [Module bundlers](./reference/tools-and-interfaces/prisma-client/module-bundlers) + - [API](./reference/tools-and-interfaces/prisma-client/api) + - [Database polyfills](./reference/tools-and-interfaces/prisma-client/database-polyfills) + - [Prisma Migrate]./reference/tools-and-interfaces/prisma-migrate() + - [Introspection](./reference/tools-and-interfaces/introspection) - Prisma CLI - - [Installation]() - - [Command reference]() + - [Installation](./reference/tools-and-interfaces/prisma-cli/installation) + - [Command reference](./reference/tools-and-interfaces/prisma-cli/command-reference) - Database connectors - - [Features]() - - [Connection URLs]() - - [PostgreSQL]() - - [MySQL]() - - [SQLite]() + - [Features](./reference/tools-and-interfaces/database-connectors/features) + - [Connection URLs](./reference/tools-and-interfaces/database-connectors/connection-urls) + - [PostgreSQL](./reference/tools-and-interfaces/database-connectors/postgresql) + - [MySQL](./reference/tools-and-interfaces/database-connectors/mysql) + - [SQLite](./reference/tools-and-interfaces/database-connectors/sqlite) - More - - [Editor setup]() - - [Telemetry]() + - [Editor setup](./reference/tools-and-interfaces/more/editor-setup) + - [Telemetry](./reference/tools-and-interfaces/more/telemetry) --- @@ -94,17 +95,34 @@ The **Reference** section contains _technical_ information about Prisma. The **Guides** section contains _step-by-step tutorials_ on various topics. - Database workflows - - [Setting up a database]() - - [Import and export data]() - - [Primary keys]() - - [Unique constraints]() - - [Foreign keys]() - - [Cascading deletes]() - - [Data validation]() + - Setting up a database + - [PostgreSQL](./guides/database-workflows/setting-up-a-database/postgresql) + - [MySQL](./guides/database-workflows/setting-up-a-database/mysql) + - [SQLite](./guides/database-workflows/setting-up-a-database/sqlite) + - Import and export data + - [PostgreSQL](./guides/database-workflows/import-and-export-datae/postgresql) + - [MySQL](./guides/database-workflows/import-and-export-data/mysql) + - [SQLite](./guides/database-workflows/import-and-export-data/sqlite) + - Unique constraints and indexes + - [PostgreSQL](./guides/database-workflows/unique-constraints-and-indexes/postgresql) + - [MySQL](./guides/database-workflows/unique-constraints-and-indexes/mysql) + - [SQLite](./guides/database-workflows/unique-constraints-and-indexes/sqlite) + - Foreign keys + - [PostgreSQL](./guides/database-workflows/foreign-keys/postgresql) + - [MySQL](./guides/database-workflows/foreign-keys/mysql) + - [SQLite](./guides/database-workflows/foreign-keys/sqlite) + - Cascading deletes + - [PostgreSQL](./guides/database-workflows/cascading-deletes/postgresql) + - [MySQL](./guides/database-workflows/cascading-deletes/mysql) + - [SQLite](./guides/database-workflows/cascading-deletes/sqlite) + - Data validation + - [PostgreSQL](./guides/database-workflows/data-validation/postgresql) + - [MySQL](./guides/database-workflows/data-validation/mysql) + - [SQLite](./guides/database-workflows/data-validation/sqlite) - Deployment - - [Deploying to AWS Lambda]() - - [Deploying to ZEIT Now]() - - [Deploying to Netlify]() + - [Deploying to AWS Lambda](./guides/deployment/deploying-to-aws-lambda) + - [Deploying to ZEIT Now](./guides/deployment/deploying-to-zeit-now) + - [Deploying to Netlify](./guides/deployment/deploying-to-netlify) --- @@ -112,10 +130,10 @@ The **Guides** section contains _step-by-step tutorials_ on various topics. The **More** section contains _meta information_ about Prisma and the documentation itself. -- [About the docs]() -- [Prisma style guide]() -- [Supported databases]() -- [Creating bug reports]() -- [FAQ]() -- [Limitations]() -- [Roadmap]() +- [About the docs](./more/about-the-docs) +- [Prisma style guide](./more//style-guide) +- [Supported databases](./more/supported-databases) +- [Creating bug reports](./more/creating-bug-reports) +- [FAQ](./more/faq) +- [Limitations](./more/limitations) +- [Roadmap](./more/roadmap) From 52d1641e1cecb576aed05ddd165abdbcc41acdb5 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 10:52:47 +0200 Subject: [PATCH 40/76] continue docs content --- .../{02-quickstart.mdx => 01-quickstart.mdx} | 52 ++++---- .../01-add-to-an-existing-project.mdx | 10 +- .../02-start-from-scratch-sql.mdx} | 10 +- .../index.mdx | 0 .../01-prisma-schema-file.mdx | 6 +- .../02-prisma-client/01-api.mdx | 115 ++++++++++++++++++ ...nt.mdx => 02-generating-prisma-client.mdx} | 0 ... 03-configuring-the-prisma-client-api.mdx} | 0 .../{03-crud.mdx => 04-crud.mdx} | 0 ...on-queries.mdx => 05-relation-queries.mdx} | 0 ...d-selection.mdx => 06-field-selection.mdx} | 0 ...-access.mdx => 07-raw-database-access.mdx} | 0 ...ement.mdx => 08-connection-management.mdx} | 0 ... 09-advanced-usage-of-generated-types.mdx} | 0 .../{09-filtering.mdx => 10-filtering.mdx} | 0 .../{10-ordering.mdx => 11-ordering.mdx} | 0 .../{11-pagination.mdx => 12-pagination.mdx} | 0 .../{12-logging.mdx => 13-logging.mdx} | 0 .../{13-debugging.mdx => 14-debugging.mdx} | 0 ...formatting.mdx => 15-error-formatting.mdx} | 0 ...5-transactions.mdx => 16-transactions.mdx} | 0 .../{16-deployment.mdx => 17-deployment.mdx} | 0 ...7-query-engine.mdx => 18-query-engine.mdx} | 0 .../02-prisma-client/19-api.mdx | 9 -- ...le-bundlers.mdx => 19-module-bundlers.mdx} | 0 content/index.mdx | 18 +-- 26 files changed, 165 insertions(+), 55 deletions(-) rename content/01-getting-started/{02-quickstart.mdx => 01-quickstart.mdx} (79%) rename content/01-getting-started/{03-setup-prisma => 02-setup-prisma}/01-add-to-an-existing-project.mdx (98%) rename content/01-getting-started/{03-setup-prisma/02-start-from-scratch-sql-migrations.mdx => 02-setup-prisma/02-start-from-scratch-sql.mdx} (98%) rename content/01-getting-started/{03-setup-prisma => 02-setup-prisma}/index.mdx (100%) create mode 100644 content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{01-generating-prisma-client.mdx => 02-generating-prisma-client.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{02-configuring-the-prisma-client-api.mdx => 03-configuring-the-prisma-client-api.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{03-crud.mdx => 04-crud.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{04-relation-queries.mdx => 05-relation-queries.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{05-field-selection.mdx => 06-field-selection.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{06-raw-database-access.mdx => 07-raw-database-access.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{07-connection-management.mdx => 08-connection-management.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{08-advanced-usage-of-generated-types.mdx => 09-advanced-usage-of-generated-types.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{09-filtering.mdx => 10-filtering.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{10-ordering.mdx => 11-ordering.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{11-pagination.mdx => 12-pagination.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{12-logging.mdx => 13-logging.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{13-debugging.mdx => 14-debugging.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{14-error-formatting.mdx => 15-error-formatting.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{15-transactions.mdx => 16-transactions.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{16-deployment.mdx => 17-deployment.mdx} (100%) rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{17-query-engine.mdx => 18-query-engine.mdx} (100%) delete mode 100644 content/03-reference/01-tools-and-interfaces/02-prisma-client/19-api.mdx rename content/03-reference/01-tools-and-interfaces/02-prisma-client/{18-module-bundlers.mdx => 19-module-bundlers.mdx} (100%) diff --git a/content/01-getting-started/02-quickstart.mdx b/content/01-getting-started/01-quickstart.mdx similarity index 79% rename from content/01-getting-started/02-quickstart.mdx rename to content/01-getting-started/01-quickstart.mdx index 0d2084fa21..9d97ee03dc 100644 --- a/content/01-getting-started/02-quickstart.mdx +++ b/content/01-getting-started/01-quickstart.mdx @@ -20,16 +20,16 @@ This page explains how to get started with Prisma in five minutes. You will lear -For the demo purposes of this guide, you will use a local [SQLite]() database file. This guide does _not_ cover the Prisma setup process. If you're looking to set up Prisma with your own database, you have these options: +For the demo purposes of this guide, you will use a local [SQLite](https://www.sqlite.org/) database file. This guide does _not_ cover the Prisma setup process. If you're looking to set up Prisma with your own database, you have these options: -- [Add Prisma to an existing project]() -- [Setup Prisma from scratch with your own database]() +- [Setup a new project with Prisma from scratch](./setup-prisma/start-from-scratch-sql) +- [Add Prisma to an existing project](./setup-prisma/add-to-an-existing-project) ## Prerequisites -The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. +The only prerequisite for this guide that you need to have [**Node.js**](https://nodejs.org/en/) (version 10 or higher) installed on your machine. TypeScript will be added as a local dependency to the project, so no need to install it. @@ -37,7 +37,7 @@ TypeScript will be added as a local dependency to the project, so no need to ins -The only prerequisite for this guide that you need to have [**Node.js**]() (version 10 or higher) installed on your machine. +The only prerequisite for this guide that you need to have [**Node.js**](https://nodejs.org/en/) (version 10 or higher) installed on your machine. @@ -74,7 +74,7 @@ This downloaded a directory called `starter`. The starter project consists of six files: - `package.json`: Defines your npm dependencies -- `prisma/schema.prisma`: Prisma configuration file defining your [models]() +- `prisma/schema.prisma`: [Prisma schema file](../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) defining your models - `prisma/.env`: Defines your database connection URL as an environment variable - `prisma/dev.db`: A SQLite database file - `scr/index.ts`: A plain, executable TypeScript script @@ -94,7 +94,7 @@ Note that the dependencies defined in your project are: The starter project consists of five files: - `package.json`: Defines your npm dependencies -- `prisma/schema.prisma`: Prisma configuration file defining your [models]() +- `prisma/schema.prisma`: [Prisma schema file](../reference/tools-and-interfaces/prisma-schema/ - `prisma/.env`: Defines your database connection URL as an environment variable - `prisma/dev.db`: A SQLite database file - `scr/index.js`: A plain, executable Node.js script @@ -263,7 +263,7 @@ Each object inside `allUsers` now includes a `posts` field which represents the -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](../reference/tools-and-interfaces/prisma-client/advanced-usage-of-generated-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: ```ts const allUsers: (User & { @@ -308,7 +308,7 @@ async function main() { } ``` -This code creates a new `Post` record and _connects_ it in a [nested write]() to an existing `User` record. +This code creates a new `Post` record and _connects_ it in a [nested write](../reference/tools-and-interfaces/prisma-client/relation-queries#nested-writes) to an existing `User` record. Run the code with this command: @@ -410,11 +410,11 @@ Fantastic, you just wrote new data into your database for the first time using P ## Next steps -This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction](../understand-prisma/introduction) page to get a high-level overview of Prisma. ### Continue exploring the Prisma Client API -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing SQLite-based setup from this guide to try them out. +You can send a variety of different queries with the Prisma Client API. Check out the [API reference](../reference/tools-and-interfaces/prisma-client/api) and use your existing SQLite-based setup from this guide to try them out. **Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. @@ -475,8 +475,8 @@ const deletedUser = await prisma.user.delete({ To learn how to connect Prisma to your own database, you can follow the respective setup guide: -- [Add Prisma to an existing project]() -- [Setup Prisma from scratch with your own database]() +- [Setup a new project with Prisma from scratch](./setup-prisma/start-from-scratch-sql) +- [Add Prisma to an existing project](./setup-prisma/add-to-an-existing-project) --- @@ -511,13 +511,13 @@ Then, introspect your database with this command from the Prisma CLI: npx prisma introspect ``` -This updates your [Prisma schema]()) in `prisma/schema.prisma`. +This updates your [Prisma schema](../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) in `prisma/schema.prisma`. -Note that after the introspection, you might want to [configure your Prisma Client API](). +Note that after the introspection, you might want to [configure your Prisma Client API](../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api).
    Alternative: Use Prisma Migrate (experimental) -Changing your database schema using Prisma Migrate typically happens with the following steps. +Changing your database schema using [Prisma Migrate](../reference/tools-and-interfaces/prisma-migrate) typically happens with the following steps. First, adjust the data model in your Prisma schema, e.g. by adding a new model: @@ -573,23 +573,23 @@ You can now run queries against the new `Profile` table, e.g. using `prisma.prof ### Try a Prisma example -The [`prisma-examples`]() repository contains a number of ready-to-run examples: +The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: **TypeScript** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/typescript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/typescript/grpc) | Backend only | Simple gRPC API | **JavaScript (Node.js)** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/javascript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/javascript/grpc) | Backend only | Simple gRPC API | diff --git a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx similarity index 98% rename from content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx rename to content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index 9aa44136ae..0da456ae3a 100644 --- a/content/01-getting-started/03-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -1,5 +1,5 @@ --- -title: 'Add Prisma to an existing project' +title: 'Add to an existing project' metaTitle: '' metaDescription: '' dbSwitcher: true @@ -27,7 +27,7 @@ In order to successfully complete this guide, you need: - an existing Node.js (version 10 or higher) project with a `package.json` -- [Node.js]() installed on your machine +- [Node.js](https://nodejs.org/en/) installed on your machine - a [PostgreSQL]() database server running and a database with at least one table @@ -35,7 +35,7 @@ In order to successfully complete this guide, you need: - an existing Node.js (version 10 or higher) project with a `package.json` -- [Node.js]() installed on your machine +- [Node.js](https://nodejs.org/en/) installed on your machine - a [MySQL]() database server running and a database with at least one table @@ -571,7 +571,7 @@ async function main() { } ``` -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write]() query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. @@ -715,7 +715,7 @@ To evolve the app, you need to follow the same flow of the tutorial: ### Try a Prisma example -The [`prisma-examples`]() repository contains a number of ready-to-run examples: +The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: **TypeScript** diff --git a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx similarity index 98% rename from content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx rename to content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index b1ef75aa25..733d14f045 100644 --- a/content/01-getting-started/03-setup-prisma/02-start-from-scratch-sql-migrations.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -1,5 +1,5 @@ --- -title: 'Start from scratch (SQL migrations)' +title: 'Start from scratch' metaTitle: '' metaDescription: '' dbSwitcher: true @@ -16,7 +16,7 @@ In order to successfully complete this guide, you need: -- [Node.js]() installed on your machine +- [Node.js](https://nodejs.org/en/) installed on your machine - a [PostgreSQL]() database server running - the [`psql`]() command line client for PostgreSQL @@ -24,7 +24,7 @@ In order to successfully complete this guide, you need: -- [Node.js]() installed on your machine +- [Node.js](https://nodejs.org/en/) installed on your machine - a [MySQL](https://www.mysql.com/) database server running - the [`mysql`](https://dev.mysql.com/doc/refman/5.7/en/mysql.html) command line client for MySQL @@ -575,7 +575,7 @@ async function main() { } ``` -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write]() query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. @@ -809,7 +809,7 @@ To evolve the app, you need to follow the same flow of the tutorial: ### Try a Prisma example -The [`prisma-examples`]() repository contains a number of ready-to-run examples: +The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: **TypeScript** diff --git a/content/01-getting-started/03-setup-prisma/index.mdx b/content/01-getting-started/02-setup-prisma/index.mdx similarity index 100% rename from content/01-getting-started/03-setup-prisma/index.mdx rename to content/01-getting-started/02-setup-prisma/index.mdx diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx index ad2f0d8b46..6f2dae979f 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx @@ -24,9 +24,9 @@ You can also [use environment variables]() inside the schema file to provide con Here is an example for a Prisma schema file that specifies a data source (SQLite), a generator (Prisma Client) and a data model definition with two models and one enum: ```prisma -datasource sqlite { - url = "file:./dev.db" - provider = "sqlite" +datasource postgresql { + url = env("DATABASE_URL") + provider = "postgresql" } generator client { diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx new file mode 100644 index 0000000000..ae1ecf6648 --- /dev/null +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx @@ -0,0 +1,115 @@ +--- +title: 'API reference' +metaTitle: '' +metaDescription: '' +--- + +## Overview + +Prisma Client is an auto-generated and type-safe query builder that's _tailored_ to your data. The easiest way to get started with Prisma Client is by following the **[Quickstart](../../../getting-started/quickstart)**. + +The setup instruction below provide a high-level overview of the steps need to set up Prisma Client. If you want to get started using Prisma Client with your own database, you have the following two options: + +- [Setup a new project with Prisma from scratch](../../../setup-prisma/start-from-scratch-sql) +- [Add Prisma to an existing project](../../../setup-prisma/add-to-an-existing-project) + + +## Setup + +### 1. Prerequisites + +In order to set up Prisma Client, you need a [Prisma schema file]() with your database connection, the Prisam Client generator and at least one [model](): + +```prisma +datasource postgresql { + url = env("DATABASE_URL") + provider = "postgresql" +} + +generator client { + provider = "prisma-client-js" +} + +model User { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + email String @unique + name String? +} +``` + +Also make sure to [install the Prisma CLI](): + +``` +npm install @prisma/cli --save-dev +npx prisma +``` + +### 2. Installation + +You can install Prisma Client in your project with this command: + +``` +npm install @prisma/client +``` + +Note that this command also run the `prisma generate` command which generates the Prisma Client into the `node_modules/@prisma/client` directory. + +### 3. Use Prisma Client to send queries to your database + +```js +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); +// use `prisma` in your application to read and write data in your DB +``` + +or + +```js +const { PrismaClient } = require('@prisma/client'); + +const prisma = new PrismaClient(); +// use `prisma` in your application to read and write data in your DB +``` + +Once you instantiated `PrismaClient`, you can start sending queries in your code: + +```ts +// run inside `async` function +const newUser = await prisma.user.create({ + data: { + name: "Alice", + email: "alice@prisma.io" + } +}) +const users = await prisma.user.findMany() +``` + +### 4. Evolving your application + +Whenever you make changes to your database that are reflected in the Prisma schema, you need to manually re-generate Prisma Client to update the generated code in the `node_modules/@prisma/client` directory: + +``` +prisma generate +``` + + +## Reference + +- [Generating Prisma Client](./generating-prisma-client) +- [Configuring the Prisma Client API](./configuring-the-prisma-client-api) +- [CRUD](./crud) +- [Relation queries](./relation-queries) +- [Field selection](./field-selection) +- [Raw database access](./raw-database-access) +- [Connection management](./connection-management) +- [Advanced usage of generated types](./advanced-usage-of-generated-types) +- [Logging](./logging) +- [Debugging](./debugging) +- [Error formatting](./error-formatting) +- [Transactions](./transactions) +- [Deployment](./deployment) +- [Query engine](./query-engine) +- [Module bundlers](./module-bundlers) +- [Database polyfills](./database-polyfills) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-generating-prisma-client.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/01-generating-prisma-client.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/02-configuring-the-prisma-client-api.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/03-crud.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/04-relation-queries.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/05-field-selection.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-raw-database-access.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/06-raw-database-access.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-connection-management.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/07-connection-management.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-advanced-usage-of-generated-types.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/08-advanced-usage-of-generated-types.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-filtering.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/10-filtering.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/09-filtering.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/10-filtering.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/10-ordering.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/11-ordering.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/10-ordering.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/11-ordering.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/11-pagination.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/12-pagination.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/11-pagination.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/12-pagination.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/12-logging.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/12-logging.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-debugging.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/13-debugging.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-error-formatting.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/14-error-formatting.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-transactions.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/15-transactions.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-deployment.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/16-deployment.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-query-engine.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/17-query-engine.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-api.mdx deleted file mode 100644 index 7f7b9f9cb8..0000000000 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-api.mdx +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: 'Prisma Client API' -metaTitle: '' -metaDescription: '' ---- - -## Overview - -Coming ๐Ÿ”œ diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx similarity index 100% rename from content/03-reference/01-tools-and-interfaces/02-prisma-client/18-module-bundlers.mdx rename to content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx diff --git a/content/index.mdx b/content/index.mdx index 2f17f96cb6..722a6d1541 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -54,16 +54,19 @@ The **Reference** section contains _technical_ information about Prisma. - [Relations](./reference/tools-and-interfaces/prisma-schema/relations) - Prisma Client - [Generating Prisma Client](./reference/tools-and-interfaces/prisma-client/generating-prisma-client) + - [API reference](./reference/tools-and-interfaces/prisma-client/api) - [Configuring the Prisma Client API](./reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api) - [CRUD](./reference/tools-and-interfaces/prisma-client/crud) - [Relation queries](./reference/tools-and-interfaces/prisma-client/relation-queries) - [Field selection](./reference/tools-and-interfaces/prisma-client/field-selection) - [Raw database access](./reference/tools-and-interfaces/prisma-client/raw-database-access) - [Connection management](./reference/tools-and-interfaces/prisma-client/connection-management) - - [Advanced usage of generated types](./reference/tools-and-interfaces/prisma-client/advancd-usage-of-generated-types) - + - [Pagination]() + --> - [Logging](./reference/tools-and-interfaces/prisma-client/logging) - [Debugging](./reference/tools-and-interfaces/prisma-client/debugging) - [Error formatting](./reference/tools-and-interfaces/prisma-client/error-formatting) @@ -71,7 +74,6 @@ The **Reference** section contains _technical_ information about Prisma. - [Deployment](./reference/tools-and-interfaces/prisma-client/deployment) - [Query engine](./reference/tools-and-interfaces/prisma-client/query-engine) - [Module bundlers](./reference/tools-and-interfaces/prisma-client/module-bundlers) - - [API](./reference/tools-and-interfaces/prisma-client/api) - [Database polyfills](./reference/tools-and-interfaces/prisma-client/database-polyfills) - [Prisma Migrate]./reference/tools-and-interfaces/prisma-migrate() - [Introspection](./reference/tools-and-interfaces/introspection) @@ -90,6 +92,8 @@ The **Reference** section contains _technical_ information about Prisma. --- + --- -### More + From 854d159a4209aa438e47096101e929000dd0c534 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 11:25:44 +0200 Subject: [PATCH 41/76] update links in GSE --- content/01-getting-started/01-quickstart.mdx | 4 +- .../01-add-to-an-existing-project.mdx | 66 +++++++++---------- .../02-start-from-scratch-sql.mdx | 55 ++++++++-------- .../01-prisma-schema/04-data-model.mdx | 2 +- .../02-connection-urls.mdx | 2 +- 5 files changed, 64 insertions(+), 65 deletions(-) diff --git a/content/01-getting-started/01-quickstart.mdx b/content/01-getting-started/01-quickstart.mdx index 9d97ee03dc..5b68455b92 100644 --- a/content/01-getting-started/01-quickstart.mdx +++ b/content/01-getting-started/01-quickstart.mdx @@ -220,7 +220,7 @@ This should print following result to output: ] ``` -One of the main features of Prisma Client is the ease for working with relations. You can retrieve the `posts` of each user by using the `include` option. Adjust your code to look as follows: +One of the main features of Prisma Client is the ease for working with relations. You can retrieve the `posts` of each user by using the [`include`](../reference/tools-and-interfaces/prisma-client/field-selection#include) option. Adjust your code to look as follows: ```js copy async function main() { @@ -565,7 +565,7 @@ Finally, re-generate Prisma Client with this command: npx prisma generate ``` -This updates the generated Prisma Client library in [`node_modules/@prisma/client`](). +This updates the generated Prisma Client library in [`node_modules/@prisma/client`](../reference/tools-and-interfaces/prisma-client/generating-prisma-client#the-prisma-client-npm-module). You can now run queries against the new `Profile` table, e.g. using `prisma.profile.findMany()`. diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index 0da456ae3a..e38ba521c1 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -28,7 +28,7 @@ In order to successfully complete this guide, you need: - an existing Node.js (version 10 or higher) project with a `package.json` - [Node.js](https://nodejs.org/en/) installed on your machine -- a [PostgreSQL]() database server running and a database with at least one table +- a [PostgreSQL](https://www.postgresql.org/) database server running and a database with at least one table @@ -36,19 +36,19 @@ In order to successfully complete this guide, you need: - an existing Node.js (version 10 or higher) project with a `package.json` - [Node.js](https://nodejs.org/en/) installed on your machine -- a [MySQL]() database server running and a database with at least one table +- a [MySQL](https://www.mysql.com/) database server running and a database with at least one table -Make sure your have your database [connection URL]() (includes your authentication credentials) at hand! +Make sure you have your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) (includes your authentication credentials) at hand! -If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](). +If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](../quickstart). ## Setup Prisma As a first step, navigate into it your project directory that contains the `package.json`. -Next, add the Prisma CLI as a development dependency in your project: +Next, add the Prisma CLI as a development dependency to your project: ``` npm install @prisma/cli --save-dev @@ -60,7 +60,7 @@ You can now invoke the Prisma CLI by prefixing it with `npx`: npx prisma ``` -Next, set up your Prisma project by creating your [Prisma schema]() file with the following command: +Next, set up your Prisma project by creating your [Prisma schema](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) file with the following command: ``` npx prisma init @@ -69,11 +69,11 @@ npx prisma init This command created a new directory called `prisma` with the following contents: - `schema.prisma`: The Prisma schema with your database connection and the Prisma Client generator -- `.env`: A [dotenv]() file for defining environment variables (used for your database connection) +- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file for defining environment variables (used for your database connection) ## Connect your database -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](): +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls): @@ -84,7 +84,7 @@ datasource postgresql { } ``` -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: ``` DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" @@ -103,12 +103,12 @@ Here's a short explanation of each component: - `USER`: The name of your database user - `PASSWORD`: The password your database user - `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) -- `DATABASE`: The name of the [database]() -- `SCHEMA`: The name of the [schema]() inside the database +- `DATABASE`: The name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) +- `SCHEMA`: The name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) inside the database If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. -As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: ``` DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" @@ -140,7 +140,7 @@ datasource mysql { } ``` -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: ``` DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" @@ -159,9 +159,9 @@ Here's a short explanation of each component: - `USER`: The name of your database user - `PASSWORD`: The password your database user - `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database]() +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) -As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: +As an example, for a MySQL database hosted on AWS RDS, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: ``` DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb @@ -304,7 +304,7 @@ CREATE TABLE Profile ( -As a next step, you will introspect your database. The result of the introspection will be a [data model]() inside your Prisma schema. +As a next step, you will introspect your database. The result of the introspection will be a [data model](../../reference/tools-and-interfaces/prisma-schema/data-model) inside your Prisma schema. Run the following command to introspect your database: @@ -334,10 +334,10 @@ model Post { } model Profile { - id Int @default(autoincrement()) @id - bio String? - user User @relation(fields: [userId], references: [id]) - userId Int @unique + id Int @default(autoincrement()) @id + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique } model User { @@ -353,12 +353,12 @@ Prisma's data model is a declarative representation of your database schema and Right now, there's a few minor "issues" with the data model: -- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](), both fields should be lowercased to `post` and `profile`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list]() of posts โ€“ a better name therefore would be the plural from `posts`. +- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](../../reference/tools-and-interfaces/prisma-schema/models#naming-models), both fields should be lowercased to `post` and `profile`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](../../reference/tools-and-interfaces/prisma-schema/models#type-modifiers) of posts โ€“ a better name therefore would be the plural from `posts`. -These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](). +These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api). -Because both the generated `Post` and `Profile` fields are [virtual](), you can go and rename them in your Prisma schema: +Because both the generated `Post` and `Profile` fields are _virtual_ (i.e. they're _not backed by a foreign key in the database_), you can manually rename them in your Prisma schema: ```prisma model User { @@ -370,7 +370,7 @@ model User { } ``` -In this example, the database schema did follow the [naming conventions]() for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. +In this example, the database schema did follow the [naming conventions](../../reference/tools-and-interfaces/prisma-schema/models#naming-models) for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. Sometimes though, you may want to make additional changes to the the names of the columns and tables that are exposed in the Prisma Client API. A common example is to translate _snake\_case_ notation which is often used in database schemas into ` PascalCase` and `camelCase` notations which feel more natural for JavaScript/TypeScript developers. @@ -395,7 +395,7 @@ const user = await prisma.my_user.create({ }) ``` -If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](): +If you don't want to use the table and column names from your database in your Prisma Client API, you can configure them with [`@map` and `@@map`](../../reference/tools-and-interfaces/prisma-schema/data-model#mapping-column-table-and-enum-names): ```prisma model MyUser { @@ -418,7 +418,7 @@ const user = await prisma.myUser.create({ }) ``` -Learn more about this on the [Configuring your Prisma Client API]() page. +Learn more about this on the [Configuring your Prisma Client API](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api) page. ## Install and generate Prisma Client @@ -428,7 +428,7 @@ To get started with Prisma Client, you need to install it as a node module: npm install @prisma/client ``` -Notice that the [`@prisma/client` node module]() is a bit different from "conventional" node modules (e.g. a library like [`lodash`]()). When installing the module with `npm install @prisma/client`, npm only downloads an empty package into the `node_modules/@prisma/client` directory. The package is then "filled" with the actual library with the following command of the Prisma CLI: +Notice that the [`@prisma/client` node module](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api#the-prisma-client-npm-module) is a bit different from "conventional" node modules (e.g. a library like [`lodash`](https://lodash.com/)). When installing the module with `npm install @prisma/client`, npm only downloads an empty package into the `node_modules/@prisma/client` directory. The package is then "filled" with the actual library with the following command of the Prisma CLI: ``` npx prisma generate @@ -504,7 +504,7 @@ Here's a quick overview of the different parts of the code snippet: 1. Call the `main` function 1. Close the database connections when the script terminates -Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD]() methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model the property is called `post`, for `Profile` it's called `profile`). +Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a `User` model, your `PrismaClient` instance exposes a property called `user` on which you can call [CRUD](../../reference/tools-and-interfaces/prisma-client/crud) methods like `findMany`, `create` or `update`. The property is named after the model, but the first letter is lowercased (so for the `Post` model the property is called `post`, for `Profile` it's called `profile`). The following examples are all based on the models in the Prisma schema. @@ -571,9 +571,9 @@ async function main() { } ``` -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields](../../reference/tools-and-interfaces/prisma-schema/relations#relation-fields) respectively. -Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. +Notice that you're passing the [`include`](../../reference/tools-and-interfaces/prisma-client/field-selection#include) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. @@ -631,11 +631,11 @@ node index.js ## Next steps -This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction](../../understand-prisma/introduction) page to get a high-level overview of Prisma. ### Continue exploring the Prisma Client API -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing database setup from this guide to try them out. +You can send a variety of different queries with the Prisma Client API. Check out the [API reference](../../reference/tools-and-interfaces/prisma-client/api) and use your existing database setup from this guide to try them out. **Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 733d14f045..19e7bc9a20 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -17,8 +17,8 @@ In order to successfully complete this guide, you need: - [Node.js](https://nodejs.org/en/) installed on your machine -- a [PostgreSQL]() database server running -- the [`psql`]() command line client for PostgreSQL +- a [PostgreSQL](https://www.postgresql.org/) database server running +- the [`psql`](https://www.postgresql.org/docs/9.3/app-psql.html) command line client for PostgreSQL @@ -30,9 +30,9 @@ In order to successfully complete this guide, you need: -Make sure your have your database [connection URL]() (includes your authentication credentials) at hand! +Make sure your have your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) (includes your authentication credentials) at hand! -If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](). Alternatively you can [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1) and use it in this guide. +If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](../quickstart). Alternatively you can [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1) and use it in this guide. ## Create project setup @@ -89,7 +89,7 @@ You can now invoke the Prisma CLI by prefixing it with `npx`: npx prisma ``` -Next, set up your Prisma project by creating your [Prisma schema]() file with the following command: +Next, set up your Prisma project by creating your [Prisma schema](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) file with the following command: ``` npx prisma init @@ -98,12 +98,11 @@ npx prisma init This command created a new directory called `prisma` with the following contents: - `schema.prisma`: The Prisma schema with your database connection and the Prisma Client generator -- `.env`: A [dotenv]() file for defining environment variables (used for your database connection) +- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file for defining environment variables (used for your database connection) ## Connect your database - -To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](): +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls): @@ -114,7 +113,7 @@ datasource postgresql { } ``` -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: ``` DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" @@ -133,12 +132,12 @@ Here's a short explanation of each component: - `USER`: The name of your database user - `PASSWORD`: The password your database user - `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) -- `DATABASE`: The name of the [database]() -- `SCHEMA`: The name of the [schema]() inside the database +- `DATABASE`: The name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) +- `SCHEMA`: The name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) inside the database If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. -As an example, for a PostgreSQL database hosted on Heroku, the [connection URL]() might look similar to this: +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: ``` DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" @@ -170,7 +169,7 @@ datasource mysql { } ``` -In this case, the `url` is [set via an environment variable]() which is defined in `prisma/.env`: +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: ``` DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" @@ -189,9 +188,9 @@ Here's a short explanation of each component: - `USER`: The name of your database user - `PASSWORD`: The password your database user - `PORT`: The port where your database server is running (typically `3306` for MySQL) -- `DATABASE`: The name of the [database]() +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) -As an example, for a MySQL database hosted on AWS RDS, the [connection URL]() might look similar to this: +As an example, for a MySQL database hosted on AWS RDS, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: ``` DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb @@ -370,7 +369,7 @@ Great, you now created three tables in your database ## Introspect your database with Prisma -As a next step, you will introspect your database. The result of the introspection will be a [data model]() inside your Prisma schema. +As a next step, you will introspect your database. The result of the introspection will be a [data model](](../../reference/tools-and-interfaces/prisma-schema/data-model)) inside your Prisma schema. Run the following command to introspect your database: @@ -419,12 +418,12 @@ Prisma's data model is a declarative representation of your database schema and Right now, there's a few minor "issues" with the data model: -- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](), both fields should be lowercased to `post` and `profile`. -- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list]() of posts โ€“ a better name therefore would be the plural from `posts`. +- The `Post` and `Profile` relation fields on `User` are both uppercased. To adhere to Prisma's [naming conventions](../../reference/tools-and-interfaces/prisma-schema/models#naming-models), both fields should be lowercased to `post` and `profile`. +- Even after lowercasing, the `post` field on `User` is still slightly misnamed. That's because it actually refers to a [list](../../reference/tools-and-interfaces/prisma-schema/models#type-modifiers) of posts โ€“ a better name therefore would be the plural from `posts`. -These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](). +These changes are relevant for the generated Prisma Client API where using `posts` and `profile` will feel more natural and idiomatic to JavaScript/TypeScript developers. You can therefore [configure your Prisma Client API](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api). -Because both the generated `Post` and `Profile` fields are [virtual](), you can go and rename them in your Prisma schema: +Because both the generated `Post` and `Profile` fields are _virtual_ (i.e. they're _not backed by a foreign key in the database_), you can manually rename them in your Prisma schema: ```prisma copy model User { @@ -436,9 +435,9 @@ model User { } ``` -In this example, the database schema did follow the [naming conventions]() for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. +In this example, the database schema did follow the [naming conventions](../../reference/tools-and-interfaces/prisma-schema/models#naming-models) for Prisma models (only the virtual relation fields that were generated from introspection did not adhere to them and needed adjustment). This optimizes the ergonomics of the generated Prisma Client API. -Learn more about this on the [Configuring your Prisma Client API]() page. +Learn more about this on the [Configuring your Prisma Client API](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api) page. ## Install and generate Prisma Client @@ -448,7 +447,7 @@ To get started with Prisma Client, you need to install it as a node module: npm install @prisma/client ``` -Notice that the [`@prisma/client` node module]() is a bit different from "conventional" node modules (e.g. a library like [`lodash`]()). When installing the module with `npm install @prisma/client`, npm only downloads an empty package into the `node_modules/@prisma/client` directory. The package is then "filled" with the actual library with the following command of the Prisma CLI: +Notice that the [`@prisma/client` node module](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api#the-prisma-client-npm-module) is a bit different from "conventional" node modules (e.g. a library like [`lodash`](https://lodash.com/)). When installing the module with `npm install @prisma/client`, npm only downloads an empty package into the `node_modules/@prisma/client` directory. The package is then "filled" with the actual library with the following command of the Prisma CLI: ``` npx prisma generate @@ -575,9 +574,9 @@ async function main() { } ``` -This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields]() respectively. +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields](../../reference/tools-and-interfaces/prisma-schema/relations#relation-fields) respectively. -Notice that you're passing the [`include`]() option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. +Notice that you're passing the [`include`](../../reference/tools-and-interfaces/prisma-client/field-selection#include) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. @@ -627,7 +626,7 @@ The output should look similar to this: -Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](../../reference/tools-and-interfaces/prisma-client/advanced-usage-of-generated-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: ```ts const allUsers: (User & { @@ -723,11 +722,11 @@ Fantastic, you just wrote new data into your database for the first time using P ## Next steps -This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction]() page to get a high-level overview of Prisma. +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction](../../understand-prisma/introduction) page to get a high-level overview of Prisma. ### Continue exploring the Prisma Client API -You can send a variety of different queries with the Prisma Client API. Check out the [API reference]() and use your existing database setup from this guide to try them out. +You can send a variety of different queries with the Prisma Client API. Check out the [API reference](../../reference/tools-and-interfaces/prisma-client/api) and use your existing database setup from this guide to try them out. **Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index 8b13b204cc..d877ad2118 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -874,7 +874,7 @@ It is currently not possible to provide more configuration options to the index: Note that while you can't configure these option in your Prisma schema, you can still configure them on the database-level directly. -### Mapping column and table names +### Mapping column, table and enum names You can use the `@map` and `@@map` attributes to map field, model and enum names as well in your Prisma schema to different column and table names in the underlying database schema. diff --git a/content/03-reference/02-database-connectors/02-connection-urls.mdx b/content/03-reference/02-database-connectors/02-connection-urls.mdx index 00be723298..7f14fd1172 100644 --- a/content/03-reference/02-database-connectors/02-connection-urls.mdx +++ b/content/03-reference/02-database-connectors/02-connection-urls.mdx @@ -58,7 +58,7 @@ datasource postgresql { } ``` -You can then either set the environment variable in your terminal or by providing a [dotenv]() file called `.env`. This will automatically be picked up by the Prisma CLI. +You can then either set the environment variable in your terminal or by providing a [dotenv](https://github.com/motdotla/dotenv) file called `.env`. This will automatically be picked up by the Prisma CLI. **.env** From edd560ca86ceb1133cd503f662dadd26b44417a5 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 11:40:41 +0200 Subject: [PATCH 42/76] update links in Introduction --- .../01-add-to-an-existing-project.mdx | 1 - .../02-understand-prisma/01-introduction.mdx | 32 +++++++++---------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index e38ba521c1..28753da711 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -175,7 +175,6 @@ DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" - ## Introspect your database with Prisma diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index ff04285a36..5f10b1a390 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -8,25 +8,25 @@ metaDescription: '' This page gives a high-level overview of what Prisma is and how it works. -If you want to get started with a _practical introduction_ and learn about the Prisma Client API, head over to the [Quickstart](). +If you want to get started with a _practical introduction_ and learn about the Prisma Client API, head over to the [**Quickstart**](../getting-started/quickstart). -To learn more about the _motivation_ for Prisma, check out the [Why Prisma?](./why-prisma) page. +To learn more about the _motivation_ for Prisma, check out the [**Why Prisma?**](./why-prisma) page. ## What is Prisma? -Prisma is an [open source]() database toolkit. It mainly consists of the following parts: +Prisma is an [open source](https://github.com/prisma/prisma) database toolkit. It mainly consists of the following parts: - **Prisma Client**: Auto-generated and type-safe query builder for Node.js & TypeScript - **Prisma Migrate** (_experimental_): Declarative schema migration system - **Prisma Studio** (_experimental_): GUI to view and edit data in your database -Prisma Client can be used in _any_ Node.js or TypeScript backend application. This can be a [REST API](), a [GraphQL API]() a gRPC API or anything else that needs a database. +Prisma Client can be used in _any_ Node.js or TypeScript backend application. This can be a [REST API](./prisma-in-your-stack/rest), a [GraphQL API](./prisma-in-your-stack/graphql) a gRPC API or anything else that needs a database. ## How does Prisma work? ### The Prisma schema -Every project that use a tool from the Prisma toolkit starts with a [Prisma schema file](). The Prisma schema allows developers to define their _application models_ in an intuitive data modeling language. It also contains the connection to a database and defines a _generator_: +Every project that use a tool from the Prisma toolkit starts with a [Prisma schema file](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file). The Prisma schema allows developers to define their _application models_ in an intuitive data modeling language. It also contains the connection to a database and defines a _generator_: ```prisma datasource db { @@ -55,7 +55,7 @@ model User { } ``` -> **Note**: The Prisma schema has powerful data modeling features. For example, it allows you to define [virtual relation fields]() which will make it easier to work with [relations in the Prisma Client API](). In the case above, the `posts` field on `User` is virtual. +> **Note**: The Prisma schema has powerful data modeling features. For example, it allows you to define "Prisma-level" [relation fields](../../reference/tools-and-interfaces/prisma-schema/relations#) which will make it easier to work with [relations in the Prisma Client API](../../reference/tools-and-interfaces/prisma-client/relation-queries). In the case above, the `posts` field on `User` is defined only on "Prisma-level", meaning it does not manifest as a foreign key in the underlying database. In this schema, you configure three things: @@ -65,11 +65,11 @@ In this schema, you configure three things: ### The Prisma data model -On this page, the focus is on the data model. You can learn more about [Data sources]() and [Generators]() on the respective docs pages. +On this page, the focus is on the data model. You can learn more about [Data sources](../../reference/tools-and-interfaces/prisma-schema/data-sources) and [Generators](../../reference/tools-and-interfaces/prisma-schema/generators) on the respective docs pages. #### Functions of Prisma models -The data model is a collection of [models](). A model has two major functions: +The data model is a collection of [models](../../reference/tools-and-interfaces/prisma-schema/models). A model has two major functions: - Represent a table in the underlying database - Provide the foundation for the queries in the Prisma Client API @@ -78,10 +78,10 @@ The data model is a collection of [models](). A model has two major functions: There are two major workflows for "getting" a data model into your Prisma schema: -- Generate the data model from [introspecting]() a database -- Manually writing the data model and mapping it to the database with [Prisma Migrate]() +- Generate the data model from [introspecting](../../reference/tools-and-interfaces/introspection) a database +- Manually writing the data model and mapping it to the database with [Prisma Migrate](../../reference/tools-and-interfaces/prisma-migrate) -Once the data model is defined, you can [generate Prisma Client]() which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields). +Once the data model is defined, you can [generate Prisma Client](../../reference/tools-and-interfaces/prisma-client/generating-prisma-client) which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields). ### Accessing your database with Prisma Client @@ -101,7 +101,7 @@ After you change your data model, you'll need to manually re-generate Prisma Cli prisma generate ``` -Note that cecause the Prisma Client node module contains specific context about _your_ Prisma schema, it's sometimes referred to as a ["smart node module"](). +Note that cecause the Prisma Client node module contains specific context about _your_ Prisma schema, it's sometimes referred to as a ["smart node module"](../../reference/tools-and-interfaces/prisma-client/generating-prisma-client#how-prisma-client-compares-to-conventional-node-modules). #### Using Prisma Client to send queries to your database @@ -127,7 +127,7 @@ const prisma = new PrismaClient() Now you can start sending queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return _plain old JavaScript objects_. -Learn more about the available operations in the [Prisma Client API reference](). +Learn more about the available operations in the [Prisma Client API reference](../../reference/tools-and-interfaces/prisma-client/api). ##### Retrieve all `User` records from the database @@ -186,7 +186,7 @@ const post = await prisma.post.update({ #### Usage with TypeScript -Note that when using TypeScript, the result of this query will be _statically typed_ so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the [Advanced usage of generated types]() page in the docs. +Note that when using TypeScript, the result of this query will be _statically typed_ so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the [Advanced usage of generated types](../../reference/tools-and-interfaces/prisma-client/advanced-usage-of-generated-types) page in the docs. ## Typical Prisma workflows @@ -198,7 +198,7 @@ The typical workflow when using **SQL migrations and introspection** looks as fo 1. Manually adjust your database schema using SQL 1. (Re-)introspect your database -1. Optionally (re-)configure your Prisma Client API ([learn more]()) +1. Optionally (re-)configure your Prisma Client API ([learn more](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api)) 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database @@ -208,7 +208,7 @@ The typical workflow when using **SQL migrations and introspection** looks as fo With **Prisma Migrate**, the workflow looks slightly different: -1. Manually adjust your [Prisma data model]() +1. Manually adjust your [Prisma data model](../../reference/tools-and-interfaces/prisma-schema/data-model) 1. Migrate your database using the `prisma migrate` CLI commands 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database From 545eb3fd5971392dd3d468b35f52175ea93d29bb Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 11:49:00 +0200 Subject: [PATCH 43/76] update links in Understand Prisma --- content/02-understand-prisma/02-why-prisma.mdx | 4 ++-- .../03-prisma-in-your-stack/01-rest.md | 2 +- .../03-prisma-in-your-stack/02-graphql.md | 12 ++++++------ .../03-prisma-in-your-stack/03-is-prisma-an-orm.mdx | 8 +++----- content/02-understand-prisma/04-data-modeling.mdx | 8 ++++---- 5 files changed, 16 insertions(+), 18 deletions(-) diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx index 9cdc639b38..1db068be9f 100644 --- a/content/02-understand-prisma/02-why-prisma.mdx +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -28,7 +28,7 @@ Furthermore, submitting SQL queries as plain strings means you don't get any aut ### SQL query builders: High control, medium productivity -A common solution that retains a high level of control and provides better productivity is to use a SQL query builder (e.g. [knex.js]()). These sort of tools provide a programmatic abstraction to construct SQL queries. +A common solution that retains a high level of control and provides better productivity is to use a SQL query builder (e.g. [knex.js](http://knexjs.org/)). These sort of tools provide a programmatic abstraction to construct SQL queries. The biggest drawback with SQL query builders is that application developers still need to think about their data in terms of SQL. This incurs a cognitive and practical cost of translating relational data into objects. Another issue is that it's too easy to shoot yourself in the foot if you don't know exactly what you're doing in your SQL queries. @@ -50,7 +50,7 @@ This is way more convenient and comes closer to the mental model developers have As an application developer, the mental model you have for your data is that of an _object_. The mental model for data in SQL on the other hand are _tables_. -The divide between these two different representations of data is often referred to as the [object-relational impedance mismatch](). The object-relational impedance mismatch also is a major reason why many developers don't like working with traditional ORMs. +The divide between these two different representations of data is often referred to as the [object-relational impedance mismatch](https://en.wikipedia.org/wiki/Object-relational_impedance_mismatch). The object-relational impedance mismatch also is a major reason why many developers don't like working with traditional ORMs. As an example, consider how data is organized and relationships are handled with each apprach: diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md index 26b39b3c7f..42700ceb43 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md @@ -60,7 +60,7 @@ model User { } ``` -You can now implement route controller (e.g. using Express) that use the generated [Prisma Client API]() to perform a database operation when an incoming HTTP request arrives. This page only shows few sample code snippets, if you want to run these code snippets, you can use the [REST API example](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express). +You can now implement route controller (e.g. using Express) that use the generated [Prisma Client API](../../../reference/tools-and-interfaces/prisma-client/api) to perform a database operation when an incoming HTTP request arrives. This page only shows few sample code snippets, if you want to run these code snippets, you can use the [REST API example](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express). #### `GET` diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md index 9261285efe..5d7f1f9ccc 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md @@ -35,11 +35,11 @@ In addition to these standalone and single-purpose libraries, there are several | Framework | Stack | Built by | Prisma | Description | | :----------------------------------------- | :----------- | :------------------------------------------------ | :--------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | -| [Nexus](https://www.nexusjs.org/#/) | Backend only | [Prisma Labs](https://github.com/prisma-labs/) | Prisma is optional | "Delightful GraphQL Application Framework" | -| [Redwood.js](https://redwoodjs.com) | Fullstack | [Tom Preston-Werner](https://github.com/mojombo/) | Built on top of Prisma | "Bringing full-stack to the JAMstack. " | -| [Blitz](https://github.com/blitz-js/blitz) | Fullstack | [Brandon Bayer](https://github.com/flybayer) | Built on top of Prisma | "Framework for building monolithic, full-stack, serverless React apps with zero data-fetching and zero client-side state management." | +| [Nexus](https://www.nexusjs.org/#/) | Backend only | [Prisma Labs](https://github.com/prisma-labs/) | Prisma is optional | _Delightful GraphQL Application Framework_ | +| [Redwood.js](https://redwoodjs.com) | Fullstack | [Tom Preston-Werner](https://github.com/mojombo/) | Built on top of Prisma | _Bringing full-stack to the JAMstack. _ | +| [Blitz](https://github.com/blitz-js/blitz) | Fullstack | [Brandon Bayer](https://github.com/flybayer) | Built on top of Prisma | _Framework for building monolithic, full-stack, serverless React apps with zero data-fetching and zero client-side state management._ | -> **Note**: If you notive any GraphQL libraries/frameworks missing from the list, please let us know. +> **Note**: If you notice any GraphQL libraries/frameworks missing from the list, please let us know. ## Prisma & GraphQL examples @@ -73,8 +73,8 @@ In the resolver of a GraphQL query, Prisma typically reads data from the databas ### Is there a special connection between Prisma and Nexus? -Yes. At Prisma, we love GraphQL and strongly believe in its bright future. While Prisma is compatible with all tools from the GraphQL ecosystem, we want to leverage the amazing things that become possible when [Nexus]() and Prisma are combined and are therefore helping to build it. +Yes. At Prisma, we love GraphQL and strongly believe in its bright future. While Prisma is compatible with all tools from the GraphQL ecosystem, we want to leverage the amazing things that become possible when [Nexus](https://www.nexusjs.org/#/) and Prisma are combined and are therefore helping to build it. As an example, when you use Nexus together with Prisma, Nexus can leverage the information from the Prisma schema and automatically generate queries and mutations for your Prisma models. -The [Prisma Labs]() team has been founded as an independent part of the rest of Prisma's engineering organization to work on open-source tools that are not directly tied to the Prisma database tools. Prisma Labs is currently dedicating most of their time to work on Nexus with the vision of making it a fully-fledged backend framework for building GraphQL servers. +The [Prisma Labs](https://github.com/prisma-labs) team has been founded as an independent part of the rest of Prisma's engineering organization to work on open-source tools that are not directly tied to the Prisma database tools. Prisma Labs is currently dedicating most of their time to work on Nexus with the vision of making it a fully-fledged backend framework for building GraphQL servers. diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx b/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx index 941a49376a..016c6ec8ef 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx +++ b/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx @@ -232,7 +232,7 @@ Prisma is a **database toolkit** that makes working with databases easy for appl - **Prisma Client**: Auto-generated and type-safe database client - **Prisma Migrate** (experimental): A CLI for declarative data modeling and migrations -Both Prisma Client and Prisma Migrate rely on the [Prisma schema](). The Prisma schema is a declarative representation of your database schema. It serves as the single source truth for both the database schema and your application models. +Both Prisma Client and Prisma Migrate rely on the [Prisma schema](../../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file). The Prisma schema is a declarative representation of your database schema. It serves as the single source truth for both the database schema and your application models. ### How Prisma compares @@ -293,7 +293,7 @@ generator client { 2. Run `prisma2 introspect` 3. Run `prisma2 generate` -Prisma will generate Prisma Client inside the `node_modules` folder, from which it can be imported in your application. For more extensive usage documentation, see the [Prisma Client API docs](https://github.com/prisma/prisma2/blob/master/docs/prisma-client-js/api.md). +Prisma will generate Prisma Client inside the `node_modules` folder, from which it can be imported in your application. For more extensive usage documentation, see the [Prisma Client API](../../reference/tools-and-interfaces/prisma-client/api) docs. To summarise, Prisma Client can be integrated into projects with an existing database and tooling as part of a parallel adoption strategy. New projects will use a different workflow detailed next. @@ -354,6 +354,4 @@ The workflow with ORMs is centered around model classes and instances to encapsu Prisma's fundamental differences are the declarative schema as a single source of truth and the use of plain JavaScript objects in Prisma Client. -These differences and your use case all affect the workflow and cost of adoption. - -Hopefully understanding how they differ can help you make an informed decision. +These differences and your use case all affect the workflow and cost of adoption. Hopefully understanding how they differ can help you make an informed decision. diff --git a/content/02-understand-prisma/04-data-modeling.mdx b/content/02-understand-prisma/04-data-modeling.mdx index 282f52f1ea..f2aa4036a6 100644 --- a/content/02-understand-prisma/04-data-modeling.mdx +++ b/content/02-understand-prisma/04-data-modeling.mdx @@ -156,7 +156,7 @@ The resulting `user` object is an instance of Sequelize's `Model` class (because Depending on which parts of Prisma you want to use in your application, the data modeling flow looks slightly different. The following two sections explain the workflows for using [**only Prisma Client**](#using-only-prisma-client) and using [**Prisma Client and Prisma Migrate (experimental)**](#using-prisma-client-and-prisma-migrate-experimental). -No matter which approach though, with Prisma you never create application models in your programming language by manually defining classes, interfaces or structs. Instead, the application models are defined in your [Prisma schema](): +No matter which approach though, with Prisma you never create application models in your programming language by manually defining classes, interfaces or structs. Instead, the application models are defined in your [Prisma schema](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file): - **Only Prisma Client**: Application models in the Prisma schema are _generated based on the introspection of your database schema_. Data modeling happens primarily on the database-level. - **Prisma Client and Prisma Migrate (experimental)**: Data modeling happens in the Prisma schema by _manually adding application models_ to it. Prisma Migrate maps these application models to tables in the underlying database. @@ -174,7 +174,7 @@ model User { Once the application models are in your Prisma schema (whether they were added through introspection or manually by you), the next step typically is to generate Prisma Client which provides a programmatic and type-safe API to read and write data in the shape of your application models. -Prisma Client JS uses TypeScript [type aliases](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases) to represent your application models in your code. For example, the `User` model would be represented as follows in the generated Prisma Client JS libary: +Prisma Client uses TypeScript [type aliases](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases) to represent your application models in your code. For example, the `User` model would be represented as follows in the generated Prisma Client libary: ```ts export declare type User = { @@ -215,9 +215,9 @@ Here is an overview of the main workflow: ### Using Prisma Client and Prisma Migrate (experimental) -> **Warning**: Prisma Migrate is currently in an experimental state. It is ready to be tested and can be used in non-critical projects. However, it is not yet ready for production usage! +> **Warning**: Prisma Migrate is currently in an experimental state. It is ready to be tested and can be used in non-critical projects. However, it is not yet considered ready for production usage. -When using Prisma Migrate, you're not using SQL for any operations that change the database schema and you typically don't use Prisma's introspection feature either. Instead, you define your application models manually in the Prisma schema and use the `prisma2 migrate` subcommand to change the schema of the your database. +When using [Prisma Migrate](../../reference/tools-and-interfaces/prisma-migrate), you're not using SQL for any operations that change the database schema and you typically don't use Prisma's introspection feature either. Instead, you define your application models manually in the Prisma schema and use the `prisma2 migrate` subcommand to change the schema of the your database. Here is an overview of the main workflow: From 956c8449ed1a797538a02180d64c84a19951770b Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 12:41:46 +0200 Subject: [PATCH 44/76] update links in schema reference --- .../05-under-the-hood.mdx | 8 +- .../01-prisma-schema-file.mdx | 16 +-- .../01-prisma-schema/03-generators.mdx | 8 +- .../01-prisma-schema/04-data-model.mdx | 86 ++++++++-------- .../01-prisma-schema/05-models.mdx | 28 +++--- .../01-prisma-schema/06-relations.mdx | 99 ++++++++++--------- .../02-prisma-client/13-logging.mdx | 2 +- .../05-prisma-cli/01-installation.mdx | 4 +- 8 files changed, 130 insertions(+), 121 deletions(-) diff --git a/content/02-understand-prisma/05-under-the-hood.mdx b/content/02-understand-prisma/05-under-the-hood.mdx index aebbe71866..a8d5c66122 100644 --- a/content/02-understand-prisma/05-under-the-hood.mdx +++ b/content/02-understand-prisma/05-under-the-hood.mdx @@ -10,7 +10,7 @@ This page gives an overview of the Prisma internals and how it works "under the Note that **this page does not contain any practical information that is relevant for _using_ Prisma**. It rather aims at providing a _mental model_ for what the Prisma toolkit _actually_ is and how the different tools that are available to developers are structured. -If you're new to Prisma, be sure to check out the [Quickstart]() and [Intrododuction]() pages first. +If you're new to Prisma, be sure to check out the [Quickstart](../getting-started/quickstart) and [Introduction](./introduction) pages first. ## Modules and interfaces @@ -29,8 +29,8 @@ Prisma provides a number of features which are implemented in the form of _modul - **Query**: Send queries to your database - **Migrate**: Perform schema migrations in your database -- **Introspect**: Read a database schema and translate into [Prisma data model]() -- **Schema**: Construct and modify a [Prisma schema file]() +- **Introspect**: Read a database schema and translate into [Prisma data model](../../reference/tools-and-interfaces/prisma-schema/data-model) +- **Schema**: Construct and modify a [Prisma schema file](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) - **Generate**: Generate clients for Prisma data sources ### Interface @@ -48,6 +48,6 @@ At the core of each module, there typically is a [Prisma engine](https://github. A Prisma engine is the **direct interface to the database**, any higher-level interfaces always communicate with the database _through_ the engine-layer. -As an example, Prisma Client connects to the [query engine]() in order to read and write data in a database: +As an example, Prisma Client connects to the [query engine](../../reference/tools-and-interfaces/prisma-client/query-engine) in order to read and write data in a database: ![](https://i.imgur.com/Nwwx5Cv.png) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx index 6f2dae979f..1b1a97793a 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx @@ -8,20 +8,20 @@ metaDescription: '' The Prisma schema file (short: _schema file_, _Prisma schema_ or _schema_) is the main configuration file for your Prisma setup. It is typically called `schema.prisma` and consists of the following parts: -- [**Data sources**](): Specify the details of the data sources Prisma should connect to (e.g. a PostgreSQL database) -- [**Generators**](): Specifies what clients should be generated based on the data model (e.g. Prisma Client) -- [**Data model definition**](): Specifies your application models (the shape of the data per data source) +- [**Data sources**](./data-sources): Specify the details of the data sources Prisma should connect to (e.g. a PostgreSQL database) +- [**Generators**](./generators): Specifies what clients should be generated based on the data model (e.g. Prisma Client) +- [**Data model definition**](./data-model): Specifies your application [models](./models) (the shape of the data per data source) and their [relations](./relations) Whenever a `prisma2` command is invoked, the CLI typically reads some information from the schema file, e.g.: - `prisma2 generate`: Reads _all_ above mentioned information from the Prisma schema to generate the correct data source client code (e.g. Prisma Client). - `prisma2 migrate save --experimental`: Reads the data sources and data model definition to create a new migration. -You can also [use environment variables]() inside the schema file to provide configuration options when a CLI command is invoked. +You can also [use environment variables](#using-environment-variables) inside the schema file to provide configuration options when a CLI command is invoked. ## Example -Here is an example for a Prisma schema file that specifies a data source (SQLite), a generator (Prisma Client) and a data model definition with two models and one enum: +Here is an example for a Prisma schema file that specifies a data source (PostgreSQL), a generator (Prisma Client) and a data model definition with two models (with one relation) and one enum: ```prisma datasource postgresql { @@ -60,9 +60,9 @@ enum Role { ## Naming -The default name for the schema file is `schema.prisma`. When your schema file is named like this, the Prisma 2 CLI will detect it automatically in the directory where you invoke the CLI command (or any of its subdirectories). +The default name for the schema file is `schema.prisma`. When your schema file is named like this, the Prisma CLI will detect it automatically in the directory where you invoke the CLI command (or any of its subdirectories). -If the file is named differently, you can provide the `--schema` argument to the Prisma 2 CLI with the path to the schema file, e.g.: +If the file is named differently, you can provide the `--schema` argument to the Prisma CLI with the path to the schema file, e.g.: ``` prisma2 generate --schema ./database/myschema.prisma @@ -74,7 +74,7 @@ The schema file is written in Prisma Schema Language (PSL). You can find a full ### VS Code -Syntax highlighting for PSL is available via a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) (which also lets you auto-format the contents of your Prisma schema and indicates syntax errors with red squiggly lines). Learn more about [setting up Prisma in your editor](). +Syntax highlighting for PSL is available via a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) (which also lets you auto-format the contents of your Prisma schema and indicates syntax errors with red squiggly lines). Learn more about [setting up Prisma in your editor](../../more/editor-setup). ### GitHub diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx index 4a449452db..a71820fe23 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx @@ -20,11 +20,11 @@ A `generator` block accepts the following fields: ## Binary targets -Prisma relies on several [engine binaries](https://github.com/prisma/prisma-engines). For example, Prisma Client uses the [query engine binary file]() under the hood to communicate with a database. Prisma Migrate uses the [migration engine binary file]() to run schema migrations against a database. +Prisma relies on several [engine binaries](https://github.com/prisma/prisma-engines). For example, Prisma Client uses the [query engine binary file](../prisma-client/query-engine) under the hood to communicate with a database. Prisma Migrate uses the migration engine binary file to run schema migrations against a database. These _engines_ are implemented in Rust and are used by Prisma in the form of executable _binary files_. -Being aware of the binary file is especially important when [deploying]() your application to production! +Being aware of the binary file is especially important when [deploying](../prisma-client/deployment) your application to production! > **Note**: You can learn more about binary targets in the [spec](https://github.com/prisma/specs/blob/master/binaries/Readme.md). @@ -54,8 +54,8 @@ The following tables list all supported operating systems with the name of the b #### Linux (Ubuntu) -| Build OS | Build name | Build OS | OpenSSL | -| :-------------------- | :--------------------- | :------: | ------- | +| Build OS | Build name | OpenSSL | +| :-------------------- | :--------------------- | :------: | | Ubuntu 14.04 (trusty) | `debian-openssl-1.0.x` | 1.0.x | | Ubuntu 16.04 (xenial) | `debian-openssl-1.0.x` | 1.0.x | | Ubuntu 18.04 (bionic) | `debian-openssl-1.1.x` | 1.1.x | diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index d877ad2118..ad44e4182f 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -8,7 +8,7 @@ metaDescription: '' The data model definition defines your _application models_ (also called _Prisma models_). These models represent the _entities of your application domain_ and map to the _tables_ in your database. -Models are the foundation for all available queries in the [Prisma Client API](). When used with TypeScript, Prisma Client provides generated type definitions for your models and any [variations]() of them to make database access entirely type safe. +Models are the foundation for all available queries in the [Prisma Client API](../prisma-client/api). When used with TypeScript, Prisma Client provides generated type definitions for your models and any [variations](../prisma-client/advanced-usage-of-generated-types) of them to make database access entirely type safe. ### Application domain examples @@ -23,16 +23,16 @@ A few examples for application domains and "typical" models are: On a _technical_ level, these models serve two main purposes: - They represent the tables in the underlying database. -- They are the foundation for the available queries in the generated [Prisma Client API](). +- They are the foundation for the available queries in the generated [Prisma Client API](../prisma-client/api). ### Data modeling primitives You can create your data model using the following primitives: -- `model`: Defines a [Prisma model]() -- `enum`: Defines an [enum]() (only available if enums are supported natively by your database) +- `model`: Defines a [Prisma model](./models) +- `enum`: Defines an [enum](#enums) (only available if enums are supported natively by your database) -Additionally, you can configure your models with [attributes]() and [functions](). +Additionally, you can configure your models with [attributes](#attributes) and [functions](#functions). ## Example @@ -88,14 +88,14 @@ enum Role { Depending on the use case, the data model is typically created in either of two ways: -- **Manually written**: You can write your data model manually and map it to your database using [Prisma Migrate]() (experimental). In this case, the data model is the single source of truth for the models of your application. -- **Generated from introspection**: When you have an existing database or prefer migrating your database schema with SQL, you generate the data model by [introspecting]() your database. In this case, the database schema is the single source of truth for the models of your application. +- **Manually written**: You can write your data model manually and map it to your database using [Prisma Migrate](../prisma-migrate) (experimental). In this case, the data model is the single source of truth for the models of your application. +- **Generated from introspection**: When you have an existing database or prefer migrating your database schema with SQL, you generate the data model by [introspecting](../introspection) your database. In this case, the database schema is the single source of truth for the models of your application. > **Note**: Since Prisma Migrate is currently in an experimental state, the officially recommended way for using Prisma is the introspection-based approach. ## Models -You can find information about models [here](). +You can find information about models [here](./models). ## Scalar types @@ -128,7 +128,7 @@ Expand below to see the mappings per connector and generator. **Generators** -| Type | Prisma Client JS | +| Type | Prisma Client | | ---------- | ---------------- | | `String` | `string` | | `Boolean` | `boolean` | @@ -140,13 +140,13 @@ Expand below to see the mappings per connector and generator. ## Enums -You can define enums in your data model if they're supported by the [data source]() you use: +You can define enums in your data model if they're supported by the [data source](./data-sources) you use: - PostgreSQL: [Supported](https://www.postgresql.org/docs/9.1/datatype-enum.html) - MySQL: [Supported](https://dev.mysql.com/doc/refman/8.0/en/enum.html) - SQLite: Not supported -Enums are considered [scalar](#scalar-types) types in the Prisma data model. They're therefore [by default]() included as return values in [Prisma Client API]() calls. +Enums are considered [scalar](#scalar-types) types in the Prisma data model. They're therefore [by default](../prisma-client/field-selection#the-default-selection-set) included as return values in [Prisma Client queries](../prisma-client/crud). Enums are defined via the `enum` block. @@ -192,7 +192,7 @@ model User { ## Attributes -Attributes modify the behavior of a [field](#fields) or block (e.g. [models](#models)). There are two ways to add attributes to your data model: +Attributes modify the behavior of a [field](./models#fields) or block (e.g. [models](./models)). There are two ways to add attributes to your data model: - _Field_ attributes are prefixed with `@` - _Block_ attributes are prefixed with `@@` @@ -209,7 +209,7 @@ Here's a quick overview of the available field attributes: | `@unique` | `UNIQUE` | - | Defines a unique constraint for this field. | | `@@unique` | `UNIQUE` | A list of field references | Defines a compound unique constraint for the specified fields. | | `@@index` | `INDEX` | A list of field references | Defines an index. | -| `@relation` | `FOREIGN KEY` / `REFERENCES` | A name and/or a list of field references | Defines meta information about the relation. [Learn more](). | +| `@relation` | `FOREIGN KEY` / `REFERENCES` | A name and/or a list of field references | Defines meta information about the relation. [Learn more](./relations#the-relation-attribute). | | `@map` | n/a | The name of the target database column | Maps a field name from the Prisma schema to a different column name. | | `@@map` | n/a | The name of the target database table | Maps a model name from the Prisma schema to a differenttable name. | | `@updatedAt` | n/a | - | Automatically stores the time when a record was last updated. | @@ -253,37 +253,37 @@ Here's an overview of the _types_ that are used in the attribute signatures: Note that some attributes take arguments. Arguments in attributes are always named, but in most cases the argument _name_ can be ommitted. -The following pairs of default values are all equivalent: +The following pairs of default values are all equivalent. -The name of the `fields` argument on the `@@id` attribute can be omitted: +**The name of the `fields` argument on the `@@id` attribute can be omitted** ```prisma @@id(fields: [title, author]) @@id([title, author]) ``` -The name of the `value` argument on the `@default` attribute can be omitted: +**The name of the `value` argument on the `@default` attribute can be omitted** ```prisma id Int @id @default(value: autoincrement()) id Int @id @default(autoincrement()) ``` -The name of the `fields` argument on the `@@unique` attribute can be omitted: +**The name of the `fields` argument on the `@@unique` attribute can be omitted** ```prisma @@unique(fields: [title, author]) @@unique([title, author]) ``` -The name of the `fields` argument on the `@@index` attribute can be omitted: +**The name of the `fields` argument on the `@@index` attribute can be omitted** ```prisma @@index(fields: [title, author]) @@index([title, author]) ``` -The name of the `name` argument on the `@relation` attribute can be omitted (`references` is required though): +**The name of the `name` argument on the `@relation` attribute can be omitted (`references` is required though)** ```prisma @relation(name: "UserOnPost", references: [id]) @@ -295,7 +295,7 @@ The name of the `name` argument on the `@relation` attribute can be omitted (`re @relation("UserOnPost") ``` -The name of the `name` argument on the `@map` and `@@map` attributes can be omitted: +**The name of the `name` argument on the `@map` and `@@map` attributes can be omitted** ```prisma @map(name: "is_admin") @@ -329,9 +329,9 @@ The signatures of the `@@id` attribute looks as follows: #### Single-field IDs -To determine which field of a model represents the ID, you can annotate it with the `@id` attribute. Note that a field that's annotated with `@id` can not be [optional](#optional-vs-required). +To determine which field of a model represents the ID, you can annotate it with the `@id` attribute. Note that a field that's annotated with `@id` can not be [optional](./models#optional-vs-required). -`@id` attributes can be defined on fields of any [type](#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). The only exception are [virtual back-relation fields](). +`@id` attributes can be defined on fields of any [type](./models#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). The only exception are "virtual" [relation fields](./relations#relation-fields) that are defined only on a Prisma-level but do not manifest in the database. ##### Single-field IDs without default values @@ -355,7 +355,7 @@ const newUser = await prisma.user.create({ ##### Single-field IDs with default values -In most cases, you want to have the ID initialized by your database. To do so, you can annotate it with the `@default` attribute and initialize the field with a [function](). +In most cases, you want to have the ID initialized by your database. To do so, you can annotate it with the `@default` attribute and initialize the field with a [function](#functions). These are the available functions and the types they're compatible with: @@ -369,15 +369,15 @@ Note that using these functions will have different effects with respect to your | Function | PostgreSQL | MySQL | SQLite | Prisma | | :---------------- | :-------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------- | :------------------------------ | -| `cuid()` | n/a | n/a | n/a | Implemented by [query engine]() | -| `uuid()` | n/a | n/a | n/a | Implemented by [query engine]() | +| `cuid()` | n/a | n/a | n/a | Implemented by [query engine](../prisma-client/query-engine) | +| `uuid()` | n/a | n/a | n/a | Implemented by [query engine](../prisma-client/query-engine) | | `autoincrement()` | Uses the [`SERIAL`](https://www.postgresql.org/docs/9.1/datatype-numeric.html#DATATYPE-SERIAL) type | Uses the [`AUTO_INCREMENT`](https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html) attribute | Uses the [`AUTOINCREMENT`](https://www.sqlite.org/autoinc.html) keyword | n/a | This table shows how each of these functions is implemented. -`cuid()` and `uuid()` are implemented by Prisma and therefore are not "visible" in the underlying database schema. You can still use them when using [introspection]() by [manually changing your Prisma schema]() and [generating Prisma Client](), in that case the values will be generated by Prisma's [query engine](). +`cuid()` and `uuid()` are implemented by Prisma and therefore are not "visible" in the underlying database schema. You can still use them when using [introspection](../introspection) by [manually changing your Prisma schema](../prisma-client/configuring-the-prisma-client-api) and [generating Prisma Client](../prisma-client/generating-prisma-client), in that case the values will be generated by Prisma's [query engine](../prisma-client/query-engine). -`autoincrement()` on the other hand is always "implememented" on the database-level, meaning it's visible in the database schema and can be recognized through introspection. +`autoincrement()` on the other hand is always "implememented" on the database-level, meaning it does manifest in the database schema and can be recognized through introspection. ##### Examples @@ -407,7 +407,7 @@ model User { } ``` -Note that in this case you can only create new `Post` records by using Prisma Client's [nested writes]() to immediately connect the new `Post` record with a new or existing `User` record, e.g.: +Note that in this case you can only create new `Post` records by using Prisma Client's [nested writes](./prisma-client/relation-queries#nested-writes) to immediately connect the new `Post` record with a new or existing `User` record, e.g.: ```ts const post = await prisma.post.create({ @@ -469,7 +469,7 @@ model User { To determine which fields of a model represent the multi-field ID, you can include them in the `@@id` attribute that's defined on your model. -`@@id` attributes can include fields of any [type](#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). +`@@id` attributes can include fields of any [type](./models#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). ##### Examples @@ -581,7 +581,7 @@ The signatures of the `@@unique` attribute looks as follows: #### Single-field unique attributes -To add a unique attribute to a field of a model, you can annotate it with the `@unique` attribute. A field that's annotated with `@unique` can be [optional or required](#optional-vs-required). If the field is optional, `null` values are always considered to be distinct from each other and any other values. +To add a unique attribute to a field of a model, you can annotate it with the `@unique` attribute. A field that's annotated with `@unique` can be [optional or required](./models#optional-vs-required). If the field is optional, `null` values are always considered to be distinct from each other and any other values. The only exception where a field annotated with `@unique` _must_ be required is when it is the only unique constraint on a model that has no ID: @@ -592,7 +592,7 @@ model User { } ``` -`@unique` attributes can be defined on fields of any [type](#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). The only exception are [virtual back-relation fields](). +`@unique` attributes can be defined on fields of any [type](./models#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). The only exception are "virtual" [relation fields](./relations#relation-fields) that are defined only on a Prisma-level but do not manifest in the database. ##### Examples @@ -647,7 +647,7 @@ model User { To add multi-field unique attribue to a model, you have to annotate it with the `@@unique` attribute and provide the list of referenced fields as an argument. -`@@unique` attributes can include fields of any [type](#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). +`@@unique` attributes can include fields of any [type](./models#field-types) in your Prisma schema (e.g. `Int`, `String`, enums, relation fields, ...). ##### Examples @@ -698,9 +698,9 @@ model User { ### Default values -You can define default values for the fields of your models using the `@default` attribute. `@default` attributes are typically represented by `DEFAULT` values in the underlying database (with a few exceptions like `cuid()` and `uuid()` which are provided by Prisma's [query engine]() and are therefore not "visible" in the underlying database schema). +You can define default values for the fields of your models using the `@default` attribute. `@default` attributes are typically represented by `DEFAULT` values in the underlying database (with a few exceptions like `cuid()` and `uuid()` which are provided by Prisma's [query engine](../prisma-client/query-engine) and are therefore not "visible" in the underlying database schema). -The `@default` attribute takes as argument an _expression_, this can be a static, hardcoded value e.g. `5`, `true`, `"Hello"` or a function, e.g. `now()`, `uuid()`, `cuid()`. Note that there is a special function in the Prisma schema called `dbgenerated()` which is used in [introspection]() results for default values that can not yet be represented in the Prisma schema. +The `@default` attribute takes as argument an _expression_, this can be a static, hardcoded value e.g. `5`, `true`, `"Hello"` or a function, e.g. `now()`, `uuid()`, `cuid()`. Note that there is a special function in the Prisma schema called `dbgenerated()` which is used in [introspection](../introspection) results for default values that can not yet be represented in the Prisma schema. Default values can be defined on any scalar type but not on relation fields. @@ -714,7 +714,7 @@ The signatures of the `@default` attribute looks as follows: #### Static default values -For [scalar types](), you can use any static value that corresponds to the type of a field as a default value: +For [scalar types](#scalar-types), you can use any static value that corresponds to the type of a field as a default value: | Type | Examples | | :--------- | :------------------------------- | @@ -751,23 +751,23 @@ These are the available functions and the types they're compatible with: | `now()` | `DateTime` | Set a timestamp of the time when a record is created. | | `cuid()` | `String` | Generate a globally unique identifier based on the [`cuid`](https://github.com/ericelliott/cuid) spec. | | `uuid()` | `String` | Generate a globally unique identifier based on the [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) spec. | -| `dbgenerated()` | Any | Represents default values that can't be expressed in the Prisma schema. Only available after [introspection](). | +| `dbgenerated()` | Any | Represents default values that can't be expressed in the Prisma schema. Only available after [introspection](../introspection). | Note that using these functions will have different effects with respect to your database and Prisma internals: | Function | PostgreSQL | MySQL | SQLite | Prisma | | :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------- | :------------------------------ | -| `cuid()` | n/a | n/a | n/a | Implemented by [query engine]() | -| `uuid()` | n/a | n/a | n/a | Implemented by [query engine]() | +| `cuid()` | n/a | n/a | n/a | Implemented by [query engine](../prisma-client/query-engine) | +| `uuid()` | n/a | n/a | n/a | Implemented by [query engine](../prisma-client/query-engine) | | `autoincrement()` | Uses the [`SERIAL`](https://www.postgresql.org/docs/9.1/datatype-numeric.html#DATATYPE-SERIAL) type | Uses the [`AUTO_INCREMENT`](https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html) attribute | Uses the [`AUTOINCREMENT`](https://www.sqlite.org/autoinc.html) keyword | n/a | -| `now()` | [`CURRENT_TIMESTAMP`](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT) and aliases like `now()` | [`CURRENT_TIMESTAMP`](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-timestamp) and aliases like `now()` | [`CURRENT_TIMESTAMP`]() and aliases like `date('now')` | +| `now()` | [`CURRENT_TIMESTAMP`](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT) and aliases like `now()` | [`CURRENT_TIMESTAMP`](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-timestamp) and aliases like `now()` | `CURRENT_TIMESTAMP` and aliases like `date('now')` | | `dbgenerated()` | Any expression | Any expression | Any expression | n/a | This table shows how each of these functions is implemented. -`cuid()` and `uuid()` are implemented by Prisma and therefore are not "visible" in the underlying database schema. You can still use them when using [introspection]() by [manually changing your Prisma schema]() and [generating Prisma Client](), in that case the values will be generated by Prisma's [query engine]() +`cuid()` and `uuid()` are implemented by Prisma and therefore are not "visible" in the underlying database schema. You can still use them when using [introspection](../introspection) by [manually changing your Prisma schema](../prisma-client/configuring-the-prisma-client-api) and [generating Prisma Client](../prisma-client/generating-prisma-client), in that case the values will be generated by Prisma's [query engine](../prisma-client/query-engine) -`autoincrement()`, `now` and `dbgenerated()` on the other hand are always "implememented" on the database-level, meaning they're visible in the database schema and can be recognized through introspection. +`autoincrement()`, `now` and `dbgenerated()` on the other hand are always "implememented" on the database-level, meaning they manifest in the database schema and can be recognized through introspection. #### Examples @@ -878,7 +878,7 @@ Note that while you can't configure these option in your Prisma schema, you can You can use the `@map` and `@@map` attributes to map field, model and enum names as well in your Prisma schema to different column and table names in the underlying database schema. -Read more about this on the [Configuring the Prisma Client API]() page. +Read more about this on the [Configuring the Prisma Client API](../prisma-client/configuring-the-prisma-client-api) page. #### Signature @@ -940,7 +940,7 @@ enum Role { ### Configuring relations -You can learn everything about configuration relations on the [Relations]() page in the docs. +You can learn everything about configuration relations on the [Relations](./relations) page in the docs. ## Functions diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx index 76ced2e817..a2fd440092 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx @@ -6,9 +6,9 @@ metaDescription: '' ## Overview -This is an extension of the [Data model]() page that discusses _models_ in the data model definition in detail. +This is an extension of the [Data model](./data-model) page that discusses _models_ in the data model definition in detail. -Models represent the entities of your application domain. They are defined using `model` blocks in the data model. In the [example data model](), `User`, `Profile`, `Post` and `Category` are models. Here's the `User` model from the example on the again for reference: +Models represent the entities of your application domain. They are defined using `model` blocks in the data model. In the [example data model](./data-model#example), `User`, `Profile`, `Post` and `Category` are models. Here's the `User` model from the example on the again for reference: ```prisma model User { @@ -74,16 +74,16 @@ model User { } ``` -`@@map` and `@map` are often used to [configure your Prisma Client API]() by decoupling it from the naming of tables and columns in the underlying database. +`@@map` and `@map` are often used to [configure your Prisma Client API](../prisma-client/configuring-the-prisma-client-api) by decoupling it from the naming of tables and columns in the underlying database. ## Fields The properties of a model are called _fields_. Fields map to _columns_ and consist of several parts: - [Name](#naming-fields) -- [Type](#types) +- [Type](#field-types) - [Type modifier](#type-modifiers) (optional) -- [Attributes](#attributes) (optional) +- [Attributes](./data-model#attributes) (optional) Here's an overview of these for the fields from the `User` model [above](#example): @@ -99,7 +99,7 @@ Here's an overview of these for the fields from the `User` model [above](#exampl ### Naming fields -Field names _must_ start with a letter and are typically spelled in [camelCase](http://wiki.c2.com/?CamelCase). +Field names _must_ start with a letter and are typically spelled in [camelCase](http://wiki.c2.com/?CamelCase). Technically, a field can be named anything that adheres to this regular expression: @@ -113,8 +113,8 @@ Technically, a field can be named anything that adheres to this regular expressi The type of a field determines its _structure_. A type falls in either of two categories: -- [Scalar type](#scalar-types) (includes [enums](#enums)) -- [Model](#models) ("relation field") +- [Scalar type](./data-model#scalar-types) (includes [enums](./data-model#enums)) +- Model (the field is then called [relation field](./relations#relation-fields)) Prisma supports the following scalar types: @@ -158,13 +158,13 @@ When **not** annotating a field with the `?` type modifier, the field will be _r ### Model attributes -A field of a model can have one or more _attributes_ which modify the behaviour of the field. Field attributes are always prefixed with a single `@`, model attributes which are prefixed with `@@`). You can find an overview of all available attributes on the [Data model]() page. +A field of a model can have one or more _attributes_ which modify the behaviour of the field. Field attributes are always prefixed with a single `@`, model attributes which are prefixed with `@@`). You can find an overview of all available attributes on the [Data model](./data-model) page. ## Models in Prisma Client ### Queries (CRUD) -Every model in the data model definition will result in a number of CRUD queries in the generated [Prisma Client API](): +Every model in the data model definition will result in a number of CRUD queries in the generated [Prisma Client API](../prisma-client/api): - `findMany` - `findOne` @@ -190,9 +190,11 @@ const allUsers = await prisma.user.findMany(); ### Type definitions -Prisma Client not only provides a query API for models, it also generates type definitions that reflect your model structures. These are part of the generated [`@prisma/client`]() node module in a file called `index.d.ts`. +Prisma Client not only provides a query API for models, it also generates type definitions that reflect your model structures. These are part of the generated [`@prisma/client`](../prisma-client/generating-prisma-client#the-prisma-client-npm-module) node module in a file called `index.d.ts`. -When using TypeScript, these type definitions ensure that all your database queries are entirely type safe and validated at compile-time (even partial queries using [`select`]() or [`include`]()). When using plain JavaScript, the type definitions are still included in the generated `@prisma/client` node module, enabling features like [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)/autocompletion in your editor. +When using TypeScript, these type definitions ensure that all your database queries are entirely type safe and validated at compile-time (even partial queries using [`select`](..//prisma-client/field-selection#select) or [`include`](..//prisma-client/field-selection#include)). + +Even when using plain JavaScript, the type definitions are still included in the generated `@prisma/client` node module, enabling features like [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)/autocompletion in your editor. For example, the type definition for the `User` model from above would look as follows: @@ -205,7 +207,7 @@ export type User = { }; ``` -Note that the relation fields `posts` and `profile` are not included in the type definion by default. However, if you need variations of the `User` type you can still define them using some of [Prisma Client's generated helper types]() (in this case, these helper types would be called `UserGetIncludePayload` and `UserGetSelectPayload`). +Note that the relation fields `posts` and `profile` are not included in the type definion by default. However, if you need variations of the `User` type you can still define them using some of [Prisma Client's generated helper types](../prisma-client/generating-prisma-client) (in this case, these helper types would be called `UserGetIncludePayload` and `UserGetSelectPayload`). ### Requirements diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index b19d008f74..f48557df91 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -This is an extension of the [Data model]() page which describes how to handle relations between Prisma models in the Prisma schema. +This is an extension of the [Data model](./data-model) page which describes how to handle relations between Prisma models in the Prisma schema. A relation is a _connection_ between two models in the Prisma schema. A relation must always be defined with two _relation fields_, one on each the model. In the case of one-to-one and one-to-many relations, an additional _relation scalar field_ must be added: @@ -27,15 +27,6 @@ model Post { > > This means that one side of the relation represents the _foreign key_ in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level). - ## Example @@ -67,7 +58,7 @@ model Category { } ``` -> **Note**: This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [relation scalars]()) so you can focus on the relation fields. +> **Note**: This schema is the same as the [example data model](./data-model#example) but has all [scalar fields](./data-model#scalar-types) removed (except for the required [relation scalars](#annotated-relation-fields-and-relation-scalar-fields)) so you can focus on the [relation fields](#relation-fields). ## Terminology @@ -87,7 +78,7 @@ In the example above, there are the following relations: ### Relation fields -Relation [fields]() are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. +Relation [fields](./models#fields) are fields on a Prisma [model](./models) that do _not_ have a [scalar type](./data-model#scalar-types). Instead, their type is another model. Every relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required which gets linked by one of the two relation fields in the `@relation` attribute. This relation scalar is the direct representation of the _foreign key_ in the underlying database. @@ -173,15 +164,34 @@ model Category { Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. -This m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). +If a [multi-field ID](./data-model#multi-field-ids) was used on `User`, the models would look as follows: -If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). +```prisma +model User { + firstName String + lastName String + Post Post[] @relation(references: [id]) + + @@id([firstName, lastName]) +} + +model Post { + id Int @id + User User[] @relation(references: [firstName, lastName]) +} +``` + +This m-n-relation still manifests in a relation table in the underlying database. However, this relation table is managed by Prisma. + +Using an implicit instead of an explicit m-n relations makes the [Prisma Client API](../prisma-client/api) for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes](../prisma-client/relation-queries#nested-writes)). + +If you're not using Prisma Migrate but obtain your data model from [introspection](../introspection), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations). ### Relation tables A relation table (also sometimes called _JOIN_, _link_ or _pivot_ table) connects two or more other tables and therefore creates a _relation_ between them. Creating relation tables is a common data modeling practice in SQL to represent relationships between different entities. In essence it means that "one m-n relation is modeled as two 1-n relations in the database". -When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both annotated relation fields with a corresponding relation scalar field. +When using Prisma, you can create relation tables by defining [models](./models) similar to how you would model them as tables. The main difference is that the fields of the relation table are both annotated relation fields with a corresponding relation scalar field. Relation tables are also often used to add "meta-information" to a relation. For example, to store _when_ the relation was created. @@ -213,9 +223,9 @@ model CategoriesOnPosts { In this example, the `createdAt` field stores additional information about the relation between `Post` and `Category` (i.e. it stores the point in time when "the post was added to the catgegory"). -Note that the same rules as for [1-n-relations]() apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations), which means one side of the relation needs to be annotated with the `@relation` attribute. +Note that the same rules as for [1-n-relations](#one-to-many-relations) apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations), which means one side of the relation needs to be annotated with the `@relation` attribute. -When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). +When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but obtain your data model from [introspection](../introspection), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations). ### Annotated relation fields and relation scalar fields @@ -225,7 +235,7 @@ The side of the relation which is annotated with the `@relation` attribute repre Because a relation scalar field always _belongs_ to a relation field, the two are often named the same but the relation scalar is suffixed with `Id`. For example, assume an annotated relation field is called `author`, the corresponding relation scalar would be called `authorId` according to this convention. -Note that relation scalar fields are read-only in the generated [Prisma Client API](). If you want to update a relation in your code, you can do so using [nested writes](). +Note that relation scalar fields are read-only in the generated [Prisma Client API](../prisma-client/api). If you want to update a relation in your code, you can do so using [nested writes](../prisma-client/relation-queries#nested-writes). In **1-1 relations**, you can decide yourself which side of the relation you want to annotate with the `@relation` attribute (and therefore holds the foreign key). @@ -296,7 +306,7 @@ model Profile { } ``` -With [multi-field IDs](), there might also be multiple relation scalars on the same model which are both used in the `@relation`attribute: +With [multi-field IDs](./data-model#multi-field-ids), there might also be multiple relation scalars on the same model which are both used in the `@relation`attribute: ```prisma model User { @@ -317,9 +327,9 @@ model Profile { ## The @relation attribute -The `@relation` attribute can only be applied to the [relation fields](), not to [scalar fields](). +The `@relation` attribute can only be applied to the [relation fields](#relation-fields), not to [scalar fields](./data-model#scalar-types). -It must be added to _every_ relation in your Prisma schema. In [implicit m-n relations](), it is required on both sides of the relation. In 1-1 and 1-n relations, it is only required on one side. +It must be added to _every_ relation in your Prisma schema. In [implicit m-n relations](#implicit-many-to-many-relations), it is required on both sides of the relation. In 1-1 and 1-n relations, it is only required on one side. Here are some example scenarios when the `@relation` attribute is needed, e.g. when: @@ -339,8 +349,8 @@ Here are some example scenarios when the `@relation` attribute is needed, e.g. w | Argument | Type | Required | Description | Example | | :----------- | :----------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | | `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | -| `fields` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | -| `references` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | +| `fields` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | +| `references` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | ## One-to-one relations @@ -367,7 +377,7 @@ In the code above, the `userId` relation scalar is a direct representation of th This 1-1-relation expresses the following: -- "a user can have zero or one profiles" (because the `profile` field is [optional]() on `User`) +- "a user can have zero or one profiles" (because the `profile` field is [optional](./models#type-modifiers) on `User`) - "a profile must always be connected to one user" In SQL, this is typically modeled as follows: @@ -385,7 +395,7 @@ CREATE TABLE "Profile" ( Notice the `UNIQUE` constraint on the foreign key `userId`. If this `UNIQUE` constraint was missing, the relation would be considered a 1-n relation. -You can also define this relation using [multi-field IDs](): +You can also define this relation using [multi-field IDs](./data-model#multi-field-ids): ```prisma model User { @@ -440,14 +450,14 @@ model Profile { This 1-1-relation now expresses the following: -- "a user must always have one profile" (because the `profile` field is [required]() on `User`) +- "a user must always have one profile" (because the `profile` field is [required](./models#optional-vs-required) on `User`) - "a profile must always be connected to one user" -Making the `profile` field on `User` required does not impact the schema in the underlying database since relational databases are not able to model such a constraint. This constraint is implemented and enforced by Prisma's [query engine](). +Making the `profile` field on `User` required does not impact the schema in the underlying database since relational databases are not able to model such a constraint. This constraint is implemented and enforced by Prisma's [query engine](../prisma-client/query-engine). > **Note**: One-to-one [self-relations](#self-relations) must not be made required on both sides, at least one side always must be declared optional. -It's important to note that in the case of required 1-1-relations, the only way to create a new record for either `User` or `Profile` is by using [nested writes](): +It's important to note that in the case of required 1-1-relations, the only way to create a new record for either `User` or `Profile` is by using [nested writes](../prisma-client/relation-queries#nested-writes): ```ts const user = await prisma.user.create({ @@ -475,7 +485,7 @@ const user = await prisma.profile.create({ }) ``` -If you're using [introspection](), you can make 1-1-relations required by manually adjusting your [Prisma schema]() and making both relation fields required, then you can [re-generate Prisma Client]() which will now make sure that the required 1-1-relation is enforced by the query engine. +If you're using [introspection](../introspection), you can make 1-1-relations required by manually adjusting your [Prisma schema](./prisma-schema-file) and making both relation fields required, then you can [re-generate Prisma Client](../prisma-client/generating-prisma-client) which will now make sure that the required 1-1-relation is enforced by the query engine. ### Determining the side of the foreign key @@ -576,7 +586,7 @@ model Post { } ``` -> **Note** The `posts` field does not "manifest" in the underlying database schema. On the other side of the relation, the [annotated relation field]() `author` and the [relation scalar]() `authorId` represent the side of the relation that stores the foreign key in the underlying database. +> **Note** The `posts` field does not "manifest" in the underlying database schema. On the other side of the relation, the [annotated relation field](#annotated-relation-fields-and-relation-scalar-fields) `author` and its relation scalar `authorId` represent the side of the relation that stores the foreign key in the underlying database. This 1-n-relation expresses the following: @@ -598,7 +608,7 @@ CREATE TABLE "Post" ( Since there's no `UNIQUE` constraint on the `author` column (foreign key), you can create multiple `Post` records that point to the same `User` record therefore creating a one-to-many relationship between the two tables. -You can also define this relation using [multi-field IDs](): +You can also define this relation using [multi-field IDs](./data-model#multi-field-ids): ```prisma model User { @@ -635,13 +645,10 @@ CREATE TABLE "Post" ( ### Required vs optional relation fields in one-to-many relations - - A 1-n-relation always has two relation fields: -- a [list]() relation field which is _not_ annotated with `@relation` -- the [annotated relation field]() (including its relation scalar) +- a [list](./models#type-modifiers) relation field which is _not_ annotated with `@relation` +- the [annotated relation field](#annotated-relation-fields-and-relation-scalar-fields) (including its relation scalar) The relation fields in a 1-n relation can take the following forms: @@ -683,7 +690,7 @@ model Post { ## Many-to-many -Many-to-many (m-n) relations refer to relations where zero or more records on one side of the relation can be connected to zero or more records on the other side. m-n-relations are typically modelled via [relation tables]() in a relational database. m-n-relations can be either [explicit]() or [implicit]() in the Prisma schema. +Many-to-many (m-n) relations refer to relations where zero or more records on one side of the relation can be connected to zero or more records on the other side. m-n-relations are typically modelled via [relation tables](#relation-tables) in a relational database. m-n-relations can be either [explicit](#explicit-many-to-many-relations) or [implicit](#implicit-many-to-many-relations) in the Prisma schema. ### Example @@ -701,11 +708,11 @@ model Category { } ``` -Implicit many-to-many relations are maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. +Implicit many-to-many relations are maintained by Prisma with a [relation table](#relation-tables) that's not reflected in the Prisma schema. Both fields require the `@relation` attribute to specify the fields they _reference_ on the other model. -As another example, assume `Category` had a [multi-field ID](): +As another example, assume `Category` had a [multi-field ID](./data-model#multi-field-ids): ```prisma model Post { @@ -729,7 +736,7 @@ This m-n-relation expresses the following: The `@relation` attribute on the `Post` model now references the multi-field ID composed of `name` and `position`. -In SQL, the first of the two implicit m-n-relations maps to the following tables (following Prisma's [conventions for relation tables]()): +In SQL, the first of the two implicit m-n-relations maps to the following tables (following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations)): ```sql CREATE TABLE "Category" ( @@ -799,7 +806,7 @@ CREATE UNIQUE INDEX "CategoryToPost_category_post_unique" ON "CategoryToPost"("c ### Conventions for relation tables in implicit m-n-relations -If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's conventions for relation tables. For the folowing example, assume you want to create a relation table to get an implicit many-to-many relation for two models called `Post` and `Category`. +If you're not using Prisma Migrate but obtain your data model from [introspection](../introspection), you can still make use of implicit many-to-many relations by following Prisma's conventions for relation tables. For the folowing example, assume you want to create a relation table to get an implicit many-to-many relation for two models called `Post` and `Category`. #### Table name @@ -889,9 +896,9 @@ Note that one-to-one self-relations can not be made required on both sides, one Self-relations always require the `@relation` attribute on both sides of the relation. On both ends, you need provide the same relation _name_. -The `husband` field on the other hand is the [annotated relation field]() (although here the term is ambiguous because both relation fields are annotated with the `@relation` attribute, however here this refers too the field that also has the `fields` and `references` arguments). +The `husband` field on the other hand is the [annotated relation field](#annotated-relation-fields-and-relation-scalar-fields) (although here the term is ambiguous because both relation fields are annotated with the `@relation` attribute, however here this refers too the field that also has the `fields` and `references` arguments). -The annotated field is backed by a foreign key in the underlying database. Here, `id` is the [relation scalar]() that's referenced by `husband`. +The annotated field is backed by a foreign key in the underlying database. Here, `id` is the [relation scalar](#annotated-relation-fields-and-relation-scalar-fields) that's referenced by `husband`. You can again determine which side of the relation should store the foreign key in the underlying database: @@ -941,7 +948,7 @@ This relation expresses the following: - "a user has zero or one _teachers_ " - "a user can have zero or more _students_" -Note that you can also require each user to have a teacher by making the `teacher` field [required](). +Note that you can also require each user to have a teacher by making the `teacher` field [required](./models#optional-vs-required). This relation is represented as follows in SQL: @@ -969,7 +976,7 @@ This relation expresses the following: - "a user can be followed by zero or more users" - "a user can follow zero or more users" -Note that this n-n-relation is [implicit](). This means Prisma maintains a [relation table]() for it in the underlying database: +Note that this n-n-relation is [implicit](#implicit-many-to-many-relations). This means Prisma maintains a [relation table](#relation-tables) for it in the underlying database: ```sql CREATE TABLE "User" ( @@ -1069,7 +1076,7 @@ For **implicit m-n-relations**, both relation fields are virtual since neither o Prisma always requires both sides of a relation to be present, this means that one virtual relation field always needs to be added per relation. When [formatting the Prisma schema](), the formatter automatically inserts any missing virtual relation fields for you to save some typing work. -Virtual relation fields are also present in the generated [Prisma Client API]() which makes working with relations more convenient as you can traverse relationships in your code in both directions, for example: +Virtual relation fields are also present in the generated [Prisma Cl../prisma-client/apiient API]() which makes working with relations more convenient as you can traverse relationships in your code in both directions, for example: ```js // Traverse relation from `Post` to `User` via fluent API diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx index 30666e316c..5a6fcf033b 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -You can view the generated database queries that Prisma Client JS sends to your database as well as warnings and other information by configuring different _log levels_ in the `PrismaClient` constructor. You can do this via the `log` option: +You can view the generated database queries that Prisma Client sends to your database as well as warnings and other information by configuring different _log levels_ in the `PrismaClient` constructor. You can do this via the `log` option: ```ts const prisma = new PrismaClient({ diff --git a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx index c1a826c949..81c9641a0e 100644 --- a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx +++ b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx @@ -6,11 +6,11 @@ metaDescription: '' ## Overview -The Prisma 2 CLI is available as an [npm package](). It is **recommended to install the Prisma 2 CLI locally** in your project's `package.json` to avoid version conflicts. +The Prisma CLI is available as an [npm package](). It is **recommended to install the Prisma CLI locally** in your project's `package.json` to avoid version conflicts. ## Local installation (recommended) -The Prisma 2 CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. +The Prisma CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. #### npm From f7b4565e67477c8935a93017661a9bf3d08f0e59 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 12:53:43 +0200 Subject: [PATCH 45/76] update links in prisma client reference --- .../01-prisma-schema/04-data-model.mdx | 2 +- .../02-prisma-client/01-api.mdx | 10 +++--- .../02-generating-prisma-client.mdx | 4 +-- .../03-configuring-the-prisma-client-api.mdx | 32 +++++++++---------- 4 files changed, 23 insertions(+), 25 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index ad44e4182f..ede702a3a0 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -617,7 +617,7 @@ model User { Note that in this case, it is _allowed_ to have multiple `User` records in the database where the `email` is `NULL` because `NULL` values are considered to distinct from each other. -**Specify a unique attribute on link field `authorId`** +**Specify a unique attribute on relation scalar field `authorId`** ```prisma model Post { diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx index ae1ecf6648..f7d95dd884 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx @@ -8,17 +8,16 @@ metaDescription: '' Prisma Client is an auto-generated and type-safe query builder that's _tailored_ to your data. The easiest way to get started with Prisma Client is by following the **[Quickstart](../../../getting-started/quickstart)**. -The setup instruction below provide a high-level overview of the steps need to set up Prisma Client. If you want to get started using Prisma Client with your own database, you have the following two options: +The setup instruction below provide a high-level overview of the steps needed to set up Prisma Client. If you want to get started using Prisma Client with your own database, follow one of these guides: - [Setup a new project with Prisma from scratch](../../../setup-prisma/start-from-scratch-sql) - [Add Prisma to an existing project](../../../setup-prisma/add-to-an-existing-project) - ## Setup ### 1. Prerequisites -In order to set up Prisma Client, you need a [Prisma schema file]() with your database connection, the Prisam Client generator and at least one [model](): +In order to set up Prisma Client, you need a [Prisma schema file](..//prisma-schema/prisma-schema-file) with your database connection, the Prisma Client generator and at least one model: ```prisma datasource postgresql { @@ -38,7 +37,7 @@ model User { } ``` -Also make sure to [install the Prisma CLI](): +Also make sure to [install the Prisma CLI](../prisma-cli/installation): ``` npm install @prisma/cli --save-dev @@ -88,13 +87,12 @@ const users = await prisma.user.findMany() ### 4. Evolving your application -Whenever you make changes to your database that are reflected in the Prisma schema, you need to manually re-generate Prisma Client to update the generated code in the `node_modules/@prisma/client` directory: +Whenever you make changes to your database that are reflected in the Prisma schema, you need to manually re-generate Prisma Client to update the generated code in the [`node_modules/@prisma/client`](./generating-prisma-client#the-prisma-client-npm-module) directory: ``` prisma generate ``` - ## Reference - [Generating Prisma Client](./generating-prisma-client) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx index f4f3a636ae..a8f2700263 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -This page explains how to generate Prisma Client. Generating Prisma Client requires the Prisma CLI installed on your machine (learn more [here]()). +This page explains how to generate Prisma Client. Generating Prisma Client requires the Prisma CLI installed on your machine (learn more [here](../prisma-cli/installation)). Prisma Client is an auto-generated database client that's tailored to your database schema. By default, it lives inside your `node_modules` directory in `node_modules/@prisma/client`. This location can be adjusted if needed. @@ -63,7 +63,7 @@ As an example for such a module, consider the [`lodash`](https://lodash.com/) np The `@prisma/client` node module is different. It is a "facade package" (basically a stub) that doesn't contain any functional code, such as types or the Prisma Client runtime. -While you do need to install it _once_ with `npm install @prisma/client`, it is likely that the code inside the `node_modules/@prisma/client` directory changes more often as you're evolving your application. This is because the directory contains code that is _generated_ based on your Prisma schema. When your Prisma schema changes (e.g. because you perform a [schema migration]()), you need to re-execute `prisma generate` which takes care of updating the code in `node_modules/@prisma/client` so that it reflects the schema changes. +While you do need to install it _once_ with `npm install @prisma/client`, it is likely that the code inside the `node_modules/@prisma/client` directory changes more often as you're evolving your application. This is because the directory contains code that is _generated_ based on your Prisma schema. When your Prisma schema changes (e.g. because you perform a [schema migration](../prisma-migrate)), you need to re-execute `prisma generate` which takes care of updating the code in `node_modules/@prisma/client` so that it reflects the schema changes. Because the `node_modules/@prisma/client` directory contains some code that is _specific_ to _your_ project, it is sometimes called a "smart node module": diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx index 5ae88d86ac..0b50031ce8 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx @@ -6,9 +6,9 @@ metaDescription: '' ## Overview -The Prisma Client API is generated based on the models in your [Prisma schema](). Models are _typically_ 1:1 mappings of your database tables. +The Prisma Client API is generated based on the models in your [Prisma schema](../prisma-schema/prisma-schema-file). Models are _typically_ 1:1 mappings of your database tables. -In some cases, especially when using [introspection](), it might be useful to _decouple_ the naming of database tables and columns from the names that are used in your Prisma Client API. This can be done via the `@map` and `@@map` attributes in your Prisma schema. +In some cases, especially when using [introspection](../introspection), it might be useful to _decouple_ the naming of database tables and columns from the names that are used in your Prisma Client API. This can be done via the [`@map` and `@@map`](../prisma-schema/data-model#mapping-column,-table-and-enum-names) attributes in your Prisma schema. ## Example @@ -91,7 +91,7 @@ The are a few "issues" with this Prisma schema when the Prisma Client API is gen **Adhering to Prisma's naming conventions** -Prisma has a [naming convention]() of **camelCasing** and using the **singular form** for Prisma models. If these naming conventions are not met, the Prisma schema can become harder to interpret and the generated Prisma Client API will feel less natural. Consider the following, generated model: +Prisma has a [naming convention](../prisma-schema/models#naming-models) of **camelCasing** and using the **singular form** for Prisma models. If these naming conventions are not met, the Prisma schema can become harder to interpret and the generated Prisma Client API will feel less natural. Consider the following, generated model: ```prisma model users { @@ -111,11 +111,11 @@ model User { } ``` -Because these fields are [virtual relation fields]() you can manually rename them in your Prisma schema. +Because these fields are "Prisma-level" [relation fields]() that do not manifest you can manually rename them in your Prisma schema. -**Naming of physical relation fields** +**Naming of annotated relation fields** -Foreign keys are represented as a combination of a [physical relation fields]() and a corresponding [link field]() in the Prisma schema. Here's how all the relations from the SQL schema are currently represented: +Foreign keys are represented as a combination of a [annotated relation fields](../prisma-schema/relations##annotated-relation-fields-and-relation-scalar-fields) and its corresponding relation scalar field in the Prisma schema. Here's how all the relations from the SQL schema are currently represented: ```prisma model categories { @@ -124,8 +124,8 @@ model categories { } model post_in_categories { - category_id Int // link field - post_id Int // link field + category_id Int // relation scalar field + post_id Int // relation scalar field categories categories @relation(fields: [category_id], references: [category_id]) // virtual relation field posts posts @relation(fields: [post_id], references: [post_id]) @@ -152,9 +152,9 @@ model users { } ``` -In the _database schema_, it makes sense to call the foreign key references after the referenced column, e.g. `post_id`, `user_id`. However, the mental model for relations in the Prisma schema is different. Here, the relation is referencing the _entire_ model, not only it's ID field. Therefore, the naming doesn't seem appropriate. + ## Using `@map` and `@@map` to rename fields and models in the Prisma Client API You can "rename" fields and models that are used in the Prisma Client by mapping them to the "original" names in the database using the `@map` and `@@map` attributes. For the [example](#example) above, you could e.g. annotate your models as follows to prevent the mentioned issues. -_After_ you introspected your database with `prisma introspect`, you can adjust the resulting Prisma schema as follows: +_After_ you introspected your database with `prisma introspect`, you can manually adjust the resulting Prisma schema as follows: ```prisma model Category { @@ -252,9 +252,9 @@ const userByProfile = await prisma.profile > **Warning**: `@map` and `@@map` attributes are removed when you run `prisma introspect` again. You therefore might want to back up your Prisma schema with these attributes in order to not having to annotate everything from scratch again after a re-introspection. -## Renaming virtual relation fields +## Renaming relation fields -[Virtual relation fields]() only exist in the Prisma schema, but are not actually manifested in the underlying database. You can therefore name these fields whatever you want. +Prisma-level [relation fields]() (sometimes referred to as "virtual relation fields") only exist in the Prisma schema, but do not actually manifest in the underlying database. You can therefore name these fields whatever you want. Consider the following example of an ambiguous relation in a SQL database: @@ -271,7 +271,7 @@ CREATE TABLE "Post" ( ); ``` -Prism's introspection will result in the following Prisma schema: +Prism's introspection will output the following Prisma schema: ```prisma model Post { @@ -303,4 +303,4 @@ model User { } ``` -> **Warning**: Virtual relation fields that were renamed in the Prisma schema will be reset when you run `prisma introspect` again. You therefore might want to back up your Prisma schema with these attributes in order to not having to annotate everything from scratch again after a re-introspection. +> **Warning**: Prisma-level relation fields that were renamed in the Prisma schema will be reset when you run `prisma introspect` again. You therefore might want to back up your Prisma schema with these attributes in order to not having to annotate everything from scratch again after a re-introspection. From 3419891a1421c6a76b90432217025f326466fcba Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 12:59:34 +0200 Subject: [PATCH 46/76] update links in prisma client reference --- .../02-prisma-client/04-crud.mdx | 2 +- .../02-prisma-client/05-relation-queries.mdx | 82 +++++++++---------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx index 1106372721..872aa2fff3 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx @@ -194,7 +194,7 @@ const result = await prisma.user.findOne({ ## findMany -The `findMany` query retrieves a list of records. The list can be altered using [pagination](), [filtering]() and [ordering]() arguments. You can use the `select` and `include` arguments to determine which fields should be included on each model object in the returned list. +The `findMany` query retrieves a list of records. The list can be altered using pagination, filtering and ordering arguments. You can use the `select` and `include` arguments to determine which fields should be included on each model object in the returned list. ### Options diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx index ab24bfb4ea..66861d4536 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx @@ -6,11 +6,11 @@ metaDescription: '' ## Overview -One of the main features of Prisma Client is its API for sending relation queries. Relation queries refer to queries that operate on a [relation]() between two or more models: +One of the main features of Prisma Client is its API for sending relation queries. Relation queries refer to queries that operate on a [relation](../prisma-schema/relations) between two or more models: - Fluent API for traversing relations - Nested writes with [transactional]() guarantees -- Nested reads (sometimes referred to as _eager loading_) via [`select`]() and [`include`]() +- Nested reads (sometimes referred to as _eager loading_) via [`select`](./field-selection#select) and [`include`](./field-selection#include) - Relation filters (filters on related objects) This page explains which relation queries exist and how to use them. @@ -52,18 +52,18 @@ model Category { } ``` -> **Note**. This schema is the same as the [example data model](./data-modeling.md/#example) but has all [scalar fields](./data-modeling.md/#scalar-types) removed so you can focus on the relation fields. +> **Note**. This schema is the same as the [example data model](../prisma-schema/data-model#example) but has all [scalar fields](../prisma-schema/data-model#scalar-types) removed so you can focus on the relation fields. ## Fluent API -The fluent API lets you _fluently_ traverse the [relations]() of your models via function calls. Note that the _last_ function call determines the return type of the entire query (the respective type annotations are added in the code snippets below to make that explicit). +The fluent API lets you _fluently_ traverse the [relations](../prisma-schema/relations) of your models via function calls. Note that the _last_ function call determines the return type of the entire query (the respective type annotations are added in the code snippets below to make that explicit). This query returns all `Post` records by a specific `User`: ```ts const postsByUser: Post[] = await prisma.user .findOne({ where: { email: 'alice@prisma.io' } }) - .posts(); + .posts() ``` Note that this call is equivalent to this Prisma Client query: @@ -71,7 +71,7 @@ Note that this call is equivalent to this Prisma Client query: ```ts const postsByUser = await prisma.post.findMany({ where: { author: { email: 'alice@prisma.io' } }, -}); +}) ``` The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query (see this [GitHub issue](https://github.com/prisma/prisma2/issues/1984)). @@ -79,7 +79,7 @@ The main difference between the two is that the fluent API call is translated in This request returns all categories by a specific post: ```ts -const categoriesOfPost: Category[] = await prisma.post.findOne({ where: { id: 1 } }).categories(); +const categoriesOfPost: Category[] = await prisma.post.findOne({ where: { id: 1 } }).categories() ``` Note that you can chain as many queries as you like. In this example, the chanining starts at `Profile` and goes over `User` to `Post`: @@ -106,7 +106,7 @@ const posts = await prisma.user ## Relation filters -A relation filter is a filter operation that's applied to a related object of a model. Relation filter options can be passed to the last chained query in a fluent API call if it returns a [list](). +A relation filter is a filter operation that's applied to a related object of a model. Relation filter options can be passed to the last chained query in a fluent API call if it returns a [list](..../prisma-schema/models#type-modifiers). **Retrieve all `Post` records of a particular `User` record that start with "Hello"** @@ -119,7 +119,7 @@ const posts: Post[] = await prisma.user where: { title: { startsWith: 'Hello' }, }, - }); + }) ``` Note that this query is _equivalent_ to the following one which is initiated via the `post` instead of the `user` field (i.e. it doesn't use the fluent API): @@ -130,19 +130,19 @@ const posts = await prisma.post.findMany({ author: { email: 'bob@prisma.io' }, title: { startsWith: 'Hello' }, }, -}); -console.log(posts); +}) +console.log(posts) ``` The main difference between the two is that the fluent API call is translated into two separate database queries while the other one only generates a single query (see this [GitHub issue](https://github.com/prisma/prisma2/issues/1984)). ## Nested writes -Nested writes provide a way for writing relational data in your database. They further provide [transactional]() guarantees for creating, updating or deleting data across multiple tables in a single Prisma Client query. +Nested writes provide a way for writing relational data in your database. They further provide [transactional](./transactions) guarantees for creating, updating or deleting data across multiple tables in a single Prisma Client query. Nested writes can be nested arbitrarily deep. -Nested writes are available for [relation fields]() when using the model's `create` or `update` query. The following section shows the nested write options that are available per query. +Nested writes are available for [relation fields](../prisma-schema/relations#relation-fields) when using the model's `create` or `update` query. The following section shows the nested write options that are available per query. ### One-to-one relations @@ -187,7 +187,7 @@ const user = await prisma.user.create({ create: { bio: 'Hello World' }, }, }, -}); +}) ``` This example uses the `user` model property, but you could also run the query from the `profile` side: @@ -200,7 +200,7 @@ const user = await prisma.profile.create({ create: { email: 'alice@prisma.io' }, }, }, -}); +}) ``` **Create a new `Profile` record and connect it to an existing `User` record** @@ -213,12 +213,12 @@ const user = await prisma.profile.create({ connect: { email: 'alice@prisma.io' }, }, }, -}); +}) ``` Note that this requires that a `User` record with an `email` of `"alice@prisma.io"` already exists in the database. If that's not the case, the query will fail with an exception. -You can provide any [unique]() or [ID]() property to the `connect` option, so in this case you could also provide the `id` fied to identify the target `User` record: +You can provide any [unique](../prisma-schema/data-model#unique) or [ID](../prisma-schema/data-model#ids) property to the `connect` option, so in this case you could also provide the `id` fied to identify the target `User` record: ```ts const user = await prisma.profile.create({ @@ -228,7 +228,7 @@ const user = await prisma.profile.create({ connect: { id: 42 }, }, }, -}); +}) ``` **Update an existing `User` record by creating a new `Profile` record** @@ -241,7 +241,7 @@ const user = await prisma.user.update({ create: { bio: 'Hello World' }, }, }, -}); +}) ``` **Update an existing `User` record by connecting it to an existing `Profile` record** @@ -254,7 +254,7 @@ const user = await prisma.user.update({ connect: { id: 24 }, }, }, -}); +}) ``` **Update an existing `User` record by updating the `Profile` record it's connected to** @@ -267,7 +267,7 @@ const user = await prisma.user.update({ update: { bio: 'Hello World' }, }, }, -}); +}) ``` **Update an existing `User` record by updating the `Profile` record it's connected to or creating a new one (_upsert_)** @@ -283,7 +283,7 @@ const user = await prisma.user.update({ }, }, }, -}); +}) ``` **Update an existing `User` record by deleting the `Profile` record it's connected to** @@ -296,7 +296,7 @@ const user = await prisma.user.update({ delete: true, }, }, -}); +}) ``` **Update an existing `User` record by disconnecting the `Profile` record it's connected to** @@ -309,7 +309,7 @@ const user = await prisma.user.update({ disconnect: true, }, }, -}); +}) ``` Note that this query is actually illegal with the data model from above because the `user` field on `Profile` is required. In order to make this query succeed, you'd need to make both relation fields optional: @@ -372,7 +372,7 @@ const user = await prisma.user.create({ create: { title: 'Hello World' }, }, }, -}); +}) ``` This example uses the `user` model property, but you could also run the query from the `post` side: @@ -385,7 +385,7 @@ const user = await prisma.post.create({ create: { email: 'alice@prisma.io' }, }, }, -}); +}) ``` **Create a new `User` record with two new `Post` records**: @@ -400,7 +400,7 @@ const user = await prisma.user.create({ create: [{ title: 'This is my first post' }, { title: 'Here comes a second post' }], }, }, -}); +}) ``` **Create a new `Post` record and connect it to an existing `User` record** @@ -413,7 +413,7 @@ const user = await prisma.post.create({ connect: { email: 'alice@prisma.io' }, }, }, -}); +}) ``` Note that this requires that a `User` record with an `email` of `"alice@prisma.io"` already exists in the database. If that's not the case, the query will fail with an exception. @@ -428,7 +428,7 @@ const user = await prisma.post.create({ connect: { id: 42 }, }, }, -}); +}) ``` **Update an existing `User` record by creating a new `Post` record** @@ -441,7 +441,7 @@ const user = await prisma.user.update({ create: { title: 'Hello World' }, }, }, -}); +}) ``` **Update an existing `User` record by connecting it to two existing `Post` records** @@ -454,7 +454,7 @@ const user = await prisma.user.update({ connect: [{ id: 24 }, { id: 42 }], }, }, -}); +}) ``` **Update an existing `User` record by updating two `Post` records it's connected to** @@ -476,7 +476,7 @@ const user = await prisma.user.update({ ], }, }, -}); +}) ``` **Update an existing `User` record by updating two `Post` record it's connected to or creating new ones (_upsert_)** @@ -500,7 +500,7 @@ const user = await prisma.user.update({ ], }, }, -}); +}) ``` **Update an existing `User` record by deleting two `Post` records it's connected to** @@ -513,7 +513,7 @@ const user = await prisma.user.update({ delete: [{ id: 34 }, { id: 36 }], }, }, -}); +}) ``` **Update an existing `User` record by disconnecting two `Post` records it's connected to** @@ -526,7 +526,7 @@ const user = await prisma.user.update({ disconnect: [{ id: 44 }, { id: 46 }], }, }, -}); +}) ``` **Update an existing `User` record by disconnecting any previous `Post` records and connect two other exiting ones** @@ -539,14 +539,14 @@ const user = await prisma.user.update({ set: [{ id: 32 }, { id: 42 }], }, }, -}); +}) ``` ## Nested reads -With nested reads, you can modify the structures of the model objects that are returned by your Prisma Client queries by _including_ their relations. In [ORM]() terminoloy, this is sometimes called _eager loading_. +With nested reads, you can modify the structures of the model objects that are returned by your Prisma Client queries by _including_ their relations. In ORM terminoloy, this is sometimes called _eager loading_. -You can load relations of your models with the [`include`]() and [`select`]() options which you can pass to _any_ Prisma Client query (except for the batch operations `updateMany` and `deleteMany`). `include` is more commonly used for relations, `select` is used for selecting specific fields. +You can load relations of your models with the [`include`](./field-selection#include) and [`select`](./field-selection#select) options which you can pass to _any_ Prisma Client query (except for the batch operations `updateMany` and `deleteMany`). `include` is more commonly used for relations, `select` is used for selecting specific fields. **Include the `posts` and `profile` relation when loading `User` records** @@ -556,7 +556,7 @@ const users = await prisma.user.findMany({ posts: true, profile: true, }, -}); +}) ``` **Include the `posts` relation on the returned objects when creating a new `User` record with two `Post` records** @@ -570,7 +570,7 @@ const user = await prisma.user.create({ }, }, include: { posts: true }, -}); +}) ``` **Retrieve deeply nested data by loading several levels of relations** @@ -588,5 +588,5 @@ const users = await prisma.user.findMany({ }, }, }, -}); +}) ``` From 410b2a3cb618a2382d415532a95eddc873e03d5b Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 13:11:31 +0200 Subject: [PATCH 47/76] reslove merge conflicts --- .../01-prisma-schema/06-relations.mdx | 208 ------------------ 1 file changed, 208 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 0b40112507..f48557df91 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -9,8 +9,6 @@ metaDescription: '' This is an extension of the [Data model](./data-model) page which describes how to handle relations between Prisma models in the Prisma schema. A relation is a _connection_ between two models in the Prisma schema. A relation must always be defined with two _relation fields_, one on each the model. In the case of one-to-one and one-to-many relations, an additional _relation scalar field_ must be added: -<<<<<<< HEAD -======= ```prisma. model User { @@ -29,34 +27,6 @@ model Post { > > This means that one side of the relation represents the _foreign key_ in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level). - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 ## Example @@ -88,11 +58,7 @@ model Category { } ``` -<<<<<<< HEAD > **Note**: This schema is the same as the [example data model](./data-model#example) but has all [scalar fields](./data-model#scalar-types) removed (except for the required [relation scalars](#annotated-relation-fields-and-relation-scalar-fields)) so you can focus on the [relation fields](#relation-fields). -======= -> **Note**: This schema is the same as the [example data model]() but has all [scalar fields]() removed (except for the required [relation scalars]()) so you can focus on the relation fields. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 ## Terminology @@ -112,11 +78,7 @@ In the example above, there are the following relations: ### Relation fields -<<<<<<< HEAD Relation [fields](./models#fields) are fields on a Prisma [model](./models) that do _not_ have a [scalar type](./data-model#scalar-types). Instead, their type is another model. -======= -Relation [fields]() are fields on a Prisma [model]() that do _not_ have a [scalar type](). Instead, their type is another model. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 Every relation must have exactly two relation fieds, one on each model. In case of 1-1 and 1-n relations, an additional _relation scalar field_ is required which gets linked by one of the two relation fields in the `@relation` attribute. This relation scalar is the direct representation of the _foreign key_ in the underlying database. @@ -201,7 +163,6 @@ model Category { ``` Note that both relation fields in a many-to-many relation must be annotated with the `@relation` attribute and _reference_ the fields of the other model they're mapping to. -<<<<<<< HEAD If a [multi-field ID](./data-model#multi-field-ids) was used on `User`, the models would look as follows: @@ -223,10 +184,6 @@ model Post { This m-n-relation still manifests in a relation table in the underlying database. However, this relation table is managed by Prisma. Using an implicit instead of an explicit m-n relations makes the [Prisma Client API](../prisma-client/api) for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes](../prisma-client/relation-queries#nested-writes)). -======= - -This m-n-relation is still manifested in a relation table in the underlying database. However, this relation table is managed by Prisma which makes the [Prisma Client API]() for many-to-many relations a bit simpler (since you e.g. have one fewer level of nesting inside of [nested writes]()). ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 If you're not using Prisma Migrate but obtain your data model from [introspection](../introspection), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations). @@ -234,11 +191,7 @@ If you're not using Prisma Migrate but obtain your data model from [introspectio A relation table (also sometimes called _JOIN_, _link_ or _pivot_ table) connects two or more other tables and therefore creates a _relation_ between them. Creating relation tables is a common data modeling practice in SQL to represent relationships between different entities. In essence it means that "one m-n relation is modeled as two 1-n relations in the database". -<<<<<<< HEAD When using Prisma, you can create relation tables by defining [models](./models) similar to how you would model them as tables. The main difference is that the fields of the relation table are both annotated relation fields with a corresponding relation scalar field. -======= -When using Prisma, you can create relation tables by defining [models]() similar to how you would model them as tables. The main difference is that the fields of the relation table are both annotated relation fields with a corresponding relation scalar field. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 Relation tables are also often used to add "meta-information" to a relation. For example, to store _when_ the relation was created. @@ -270,7 +223,6 @@ model CategoriesOnPosts { In this example, the `createdAt` field stores additional information about the relation between `Post` and `Category` (i.e. it stores the point in time when "the post was added to the catgegory"). -<<<<<<< HEAD Note that the same rules as for [1-n-relations](#one-to-many-relations) apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations), which means one side of the relation needs to be annotated with the `@relation` attribute. When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but obtain your data model from [introspection](../introspection), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations). @@ -287,24 +239,6 @@ Note that relation scalar fields are read-only in the generated [Prisma Client A In **1-1 relations**, you can decide yourself which side of the relation you want to annotate with the `@relation` attribute (and therefore holds the foreign key). -======= -Note that the same rules as for [1-n-relations]() apply (because `Post`โ†” `CategoriesOnPosts` and `Category` โ†” `CategoriesOnPosts` are both in fact 1-n-relations), which means one side of the relation needs to be annotated with the `@relation` attribute. - -When you don't need to attach additional information to the relation, you can model m-n-relations as [implicit many-to-many relations](#implicit-many-to-many-relations). If you're not using Prisma Migrate but obtain your data model from [introspection](), you can still make use of implicit many-to-many relations by following Prisma's [conventions for relation tables](). - -### Annotated relation fields and relation scalar fields - -1-1 and 1-n relations require one side of the relation to be _annotated_ with the `@relation` attribute, they're therefore commonly referred to as _annotated relation fields_. - -The side of the relation which is annotated with the `@relation` attribute represents the side that stores the foreign key in the underlying database. The "actual" field that represents the foreign key is required on that side of the relation as well, it's called _relation scalar field_ and must be used in the `@relation` attribute on the annotated relation field. A scalar field _becomes_ a relation scalar field when it's used in the `fields` of an `@relation` attribute. - -Because a relation scalar field always _belongs_ to a relation field, the two are often named the same but the relation scalar is suffixed with `Id`. For example, assume an annotated relation field is called `author`, the corresponding relation scalar would be called `authorId` according to this convention. - -Note that relation scalar fields are read-only in the generated [Prisma Client API](). If you want to update a relation in your code, you can do so using [nested writes](). - -In **1-1 relations**, you can decide yourself which side of the relation you want to annotate with the `@relation` attribute (and therefore holds the foreign key). - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 This example annotates the relation field on the `Profile` model: ```prisma @@ -323,7 +257,6 @@ model Profile { In the code above, the `userId` relation scalar is a direct representation of the foreign key in the underlying database. This example annotates the relation field on the `Profile` model: -<<<<<<< HEAD ```prisma model User { @@ -384,68 +317,6 @@ model User { @@id([firstName, lastName]) } -======= - -```prisma -model User { - id Int @id @default(autoincrement()) - profile Profile? @relation(fields: [profileId], references: [id]) - profileId Int? // relation scalar field (used in the `@relation` attribute above) -} - -model Profile { - id Int @id @default(autoincrement()) - user User -} -``` - -In the code above, `profileId` is a direct representation of the foreign key in the underlying database. - -In **1-n-relations**, you must annotate the non-list field with the `@relation` attribute: - -```prisma -model User { - id Int @id @default(autoincrement()) - email String @unique - role Role @default(USER) - posts Post[] -} - -model Post { - id Int @id @default(autoincrement()) - title String - author User @relation(fields: [authorId], references: [id]) - authorId Int // relation scalar field (used in the `@relation` attribute above) -} -``` - -Note that for **1-1 and 1-n relations**, the annotated relation field and its relation scalar field must either _both be optional_ or _both be required_. So, the following would be illegal because `user` is optional but `userId` is required: - -```prisma -model User { - id Int @id @default(autoincrement()) - profile Profile? -} - -model Profile { - id Int @id @default(autoincrement()) - user User? @relation(fields: [userId], references: [id]) // ILLEGAL - userId Int // relation scalar field (used in the `@relation` attribute above) -} -``` - -With [multi-field IDs](), there might also be multiple relation scalars on the same model which are both used in the `@relation`attribute: - -```prisma -model User { - firstName String - lastName String - profile Profile? - - @@id([firstName, lastName]) -} - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [authorFirstName, authorLastName], references: [firstName, lastName]) @@ -456,15 +327,9 @@ model Profile { ## The @relation attribute -<<<<<<< HEAD The `@relation` attribute can only be applied to the [relation fields](#relation-fields), not to [scalar fields](./data-model#scalar-types). It must be added to _every_ relation in your Prisma schema. In [implicit m-n relations](#implicit-many-to-many-relations), it is required on both sides of the relation. In 1-1 and 1-n relations, it is only required on one side. -======= -The `@relation` attribute can only be applied to the [relation fields](), not to [scalar fields](). - -It must be added to _every_ relation in your Prisma schema. In [implicit m-n relations](), it is required on both sides of the relation. In 1-1 and 1-n relations, it is only required on one side. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 Here are some example scenarios when the `@relation` attribute is needed, e.g. when: @@ -484,13 +349,8 @@ Here are some example scenarios when the `@relation` attribute is needed, e.g. w | Argument | Type | Required | Description | Example | | :----------- | :----------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | | `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | -<<<<<<< HEAD | `fields` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | | `references` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | -======= -| `fields` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | -| `references` | `FieldReference[]` | On [annotated]() relation fields | A list of [fields]() of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 ## One-to-one relations @@ -534,7 +394,6 @@ CREATE TABLE "Profile" ( ``` Notice the `UNIQUE` constraint on the foreign key `userId`. If this `UNIQUE` constraint was missing, the relation would be considered a 1-n relation. -<<<<<<< HEAD You can also define this relation using [multi-field IDs](./data-model#multi-field-ids): @@ -547,20 +406,6 @@ model User { @@id([firstName, lastName]) } -======= - -You can also define this relation using [multi-field IDs](): - -```prisma -model User { - firstName String - lastName String - profile Profile? - - @@id([firstName, lastName]) -} - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userFirstName, userLastName], references: [firstName, lastName]) @@ -657,7 +502,6 @@ model Profile { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) userId Int // relation scalar field (used in the `@relation` attribute above) -<<<<<<< HEAD } ``` @@ -676,26 +520,6 @@ model Profile { } ``` -======= -} -``` - -You can also annotate the other side of the relation with the `@relation` attribute. The following example annotates the relation field on the `User` model: - -```prisma -model User { - id Int @id @default(autoincrement()) - profile Profile? @relation(fields: [profileId], references: [id]) - profileId Int? // relation scalar field (used in the `@relation` attribute above) -} - -model Profile { - id Int @id @default(autoincrement()) - user User -} -``` - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 In the code above, `profileId` is a direct representation of the foreign key in the underlying database. This is what the relation looks like in the database: @@ -762,11 +586,7 @@ model Post { } ``` -<<<<<<< HEAD > **Note** The `posts` field does not "manifest" in the underlying database schema. On the other side of the relation, the [annotated relation field](#annotated-relation-fields-and-relation-scalar-fields) `author` and its relation scalar `authorId` represent the side of the relation that stores the foreign key in the underlying database. -======= -> **Note** The `posts` field does not "manifest" in the underlying database schema. On the other side of the relation, the [annotated relation field]() `author` and the [relation scalar]() `authorId` represent the side of the relation that stores the foreign key in the underlying database. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 This 1-n-relation expresses the following: @@ -788,11 +608,7 @@ CREATE TABLE "Post" ( Since there's no `UNIQUE` constraint on the `author` column (foreign key), you can create multiple `Post` records that point to the same `User` record therefore creating a one-to-many relationship between the two tables. -<<<<<<< HEAD You can also define this relation using [multi-field IDs](./data-model#multi-field-ids): -======= -You can also define this relation using [multi-field IDs](): ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 ```prisma model User { @@ -829,7 +645,6 @@ CREATE TABLE "Post" ( ### Required vs optional relation fields in one-to-many relations -<<<<<<< HEAD A 1-n-relation always has two relation fields: - a [list](./models#type-modifiers) relation field which is _not_ annotated with `@relation` @@ -837,18 +652,6 @@ A 1-n-relation always has two relation fields: The relation fields in a 1-n relation can take the following forms: -======= - - -A 1-n-relation always has two relation fields: - -- a [list]() relation field which is _not_ annotated with `@relation` -- the [annotated relation field]() (including its relation scalar) - -The relation fields in a 1-n relation can take the following forms: - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 - the annotated relation field can be either optional or required - if the annotated relation field is required, the relation scalar must be required - if the annotated relation field is optional, the relation scalar must be optional @@ -905,11 +708,7 @@ model Category { } ``` -<<<<<<< HEAD Implicit many-to-many relations are maintained by Prisma with a [relation table](#relation-tables) that's not reflected in the Prisma schema. -======= -Implicit many-to-many relations are maintained by Prisma with a [relation table]() that's not reflected in the Prisma schema. ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 Both fields require the `@relation` attribute to specify the fields they _reference_ on the other model. @@ -1097,17 +896,10 @@ Note that one-to-one self-relations can not be made required on both sides, one Self-relations always require the `@relation` attribute on both sides of the relation. On both ends, you need provide the same relation _name_. -<<<<<<< HEAD The `husband` field on the other hand is the [annotated relation field](#annotated-relation-fields-and-relation-scalar-fields) (although here the term is ambiguous because both relation fields are annotated with the `@relation` attribute, however here this refers too the field that also has the `fields` and `references` arguments). The annotated field is backed by a foreign key in the underlying database. Here, `id` is the [relation scalar](#annotated-relation-fields-and-relation-scalar-fields) that's referenced by `husband`. -======= -The `husband` field on the other hand is the [annotated relation field]() (although here the term is ambiguous because both relation fields are annotated with the `@relation` attribute, however here this refers too the field that also has the `fields` and `references` arguments). - -The annotated field is backed by a foreign key in the underlying database. Here, `id` is the [relation scalar]() that's referenced by `husband`. - ->>>>>>> 6568085f11c3a49eae4c8b786708b55c36952034 You can again determine which side of the relation should store the foreign key in the underlying database: ```prisma From c7a05f06eb94a6c19dc72c8fa57c35f24c8f8b11 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 13:51:41 +0200 Subject: [PATCH 48/76] update links on more reference pages --- .../01-prisma-schema/06-relations.mdx | 4 +- .../02-prisma-client/06-field-selection.mdx | 20 +++--- .../08-connection-management.mdx | 4 +- .../09-advanced-usage-of-generated-types.mdx | 10 +-- .../02-prisma-client/16-transactions.mdx | 4 +- .../02-prisma-client/18-query-engine.mdx | 10 +-- .../02-prisma-client/19-module-bundlers.mdx | 2 +- .../20-database-polyfills.mdx | 8 +-- .../03-prisma-migrate.mdx | 24 +++---- .../04-introspection.mdx | 65 ++++++++++--------- 10 files changed, 70 insertions(+), 81 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index f48557df91..39f929a786 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -561,7 +561,7 @@ In both cases, the foreign key is now defined on the `profile` column of the `Us ![](https://imgur.com/NAd72ql.png) -## One-to-many +## One-to-many relations One-to-many (1-n) relations refer to relations where one record on one side of the relation can be connected to zero or more records on the other side. @@ -688,7 +688,7 @@ model Post { } ``` -## Many-to-many +## Many-to-many relations Many-to-many (m-n) relations refer to relations where zero or more records on one side of the relation can be connected to zero or more records on the other side. m-n-relations are typically modelled via [relation tables](#relation-tables) in a relational database. m-n-relations can be either [explicit](#explicit-many-to-many-relations) or [implicit](#implicit-many-to-many-relations) in the Prisma schema. diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx index b0953e1b5c..8260f51b8f 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx @@ -66,7 +66,7 @@ All the fields that are contained in this object are scalar fields, enums or arr ## The default selection set -If the selection set is not manipulated (via `select` or `include`), a Prisma Client API call returns the **default selection set** for a model. It includes all [scalar]() fields (including [enums]() and arrays/scalar lists) fields of the model. +If the selection set is not manipulated (via `select` or `include`), a Prisma Client API call returns the **default selection set** for a model. It includes all [scalar](../prisma-schema/data-model#scalar-types) fields (including [enums](../prisma-schema/data-model#enums) and arrays/scalar lists) fields of the model. Considering the sample datamodel from above: @@ -133,12 +133,12 @@ Please either use `include` or `select`, but not both at the same time. Both, `select` and `include` are available as options on the following methods: -- [`findOne`](#findOne) -- [`findMany`](#findMany) -- [`create`](#create) -- [`update`](#update) -- [`upsert`](#upsert) -- [`delete`](#delete) +- [`findOne`](./crud#findOne) +- [`findMany`](./crud#findMany) +- [`create`](./crud#create) +- [`update`](./crud#update) +- [`upsert`](./crud#upsert) +- [`delete`](./crud#delete) ## `select` @@ -188,8 +188,6 @@ export type FindManyPostArgs = { }; ``` -You can read more about the additional types on `FindManyPostArgs` [here](). - ### Examples In this example, we're using `select` to exclusively select the `name` field of the returned `User` object: @@ -372,8 +370,6 @@ export type FindManyPostArgs = { }; ``` -You can read more about the additional types on `FindManyPostArgs` [here](). - ### Examples ```ts @@ -383,7 +379,7 @@ const result = await prisma.user.findOne({ }); ``` -The `result` object in this case contains the [default selection set]() of the `User` model _plus_ its `posts` relation: +The `result` object in this case contains the default selection set of the `User` model _plus_ its `posts` relation: ```js { diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx index ecc9812f8d..ba8902edac 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx @@ -36,7 +36,7 @@ main() ## `connect` -The `connect` method establishes a physical connection to the database via Prisma's [query engine](). +The `connect` method establishes a physical connection to the database via Prisma's [query engine](./query-engine). Note that `connect` returns a `Promise`, so you shsould call it inside an `async` function with the `await` keyword. @@ -50,7 +50,7 @@ Note that `connect` returns a `Promise`, so you should call it inside an `async` Once `connect` was called, the query engine immediately creates a connection pool with the amount of connections that were specified as the `connection_limit` parameter on your database connection URL. -For example, with the following `datasource` configuration in your [Prisma schema]() the connection pool will have exactly five connections: +For example, with the following `datasource` configuration in your [Prisma schema](../prisma-schema/prisma-schema-file) the connection pool will have exactly five connections: ```prisma datasource postgresql { diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx index 45944c668c..aa93e200b4 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx @@ -8,11 +8,11 @@ metaDescription: '' The generated code for Prisma Client contains a number of helpful types that you can use to make your application more type-safe. This page describes patterns for leveraging some of the generated types. -Note that you can find all type definitions inside the `index.d.ts` file inside the [generated `@prisma/client` node module](). +Note that you can find all type definitions inside the `index.d.ts` file inside the [generated `@prisma/client` node module](./generating-prisma-client#the-prisma-client-npm-module). ## Operating against partial structures of your model types -When using Prisma Client, every model from your [Prisma schema]() is translated into a dedicated TypeScript type. For example, assume you have the following `User` and `Post` models: +When using Prisma Client, every model from your [Prisma schema](../prisma-schema/prisma-schema-file) is translated into a dedicated TypeScript type. For example, assume you have the following `User` and `Post` models: ```prisma model User { @@ -50,9 +50,9 @@ In some scenarios, you may need a _variation_ of the generated `User` type. For As a solution, you can customize the generated model type using Prisma Client's helper types. -The `User` type only contains the model's [scalar]() fields, but doesn't account for any relations. That's because [relations are not included by default]() in Prisma Client' API calls. +The `User` type only contains the model's [scalar](../prisma-schema/data-model#scalar-types) fields, but doesn't account for any relations. That's because [relations are not included by default](./field-selection#the-default-selection-set) in Prisma Client queries. -However, sometimes it's useful to have a type available that **includes a relation** (i.e. a type that you'd get from an API call that uses [`include`]()). Similarly, another useful scenario could be to have a type available that **includes only a subset of the model's scalar fields** (i.e. a type that you'd get from an API call that uses [`select`](). +However, sometimes it's useful to have a type available that **includes a relation** (i.e. a type that you'd get from an API call that uses [`include`](./field-selectio#include)). Similarly, another useful scenario could be to have a type available that **includes only a subset of the model's scalar fields** (i.e. a type that you'd get from an API call that uses [`select`](./field-selection#select). One way of achieving this would be to define these types manually in your application code: @@ -97,7 +97,7 @@ The main benefits of the latter approach are: #### Description -When doing [`select`]() or [`include`]() operations on your models and returning these variants from a function, it can be difficult to gain access to the return type, e.g: +When doing [`select`](./field-selectio#select) or [`include`](./field-selectio#include) operations on your models and returning these variants from a function, it can be difficult to gain access to the return type, e.g: ```ts // Function definition that returns a partial structure diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx index df916a1a71..1d0930142c 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx @@ -25,9 +25,9 @@ While there's a lot of of ambiguity and nuance to each of these properties (e.g. Prisma Client provides a data access API to read and write data from a database. For relational databases, Prisma Client's API abstracts over SQL where transactions are a common feature. -While Prisma Client doesn't allow for the same flexibility a SQL-level transaction provides, it covers the vast majority of use cases developers have for transactions with [**nested writes**](). +While Prisma Client doesn't allow for the same flexibility a SQL-level transaction provides, it covers the vast majority of use cases developers have for transactions with [**nested writes**](./relation-queries#nested-writes). -A nested write lets you perform a single Prisma Client API call with multiple _operations_ that touch multiple [_related_](./relations.md#nested-writes) records, for example creating a _user_ together with a _post_ or updating an _order_ together with an _invoice_. When a nested write is performed, Prisma Client ensures that it will either succeed or fail as a whole. +A nested write lets you perform a single Prisma Client API call with multiple _operations_ that touch multiple [_related_](../prisma-schema/relations) records, for example creating a _user_ together with a _post_ or updating an _order_ together with an _invoice_. When a nested write is performed, Prisma Client ensures that it will either succeed or fail as a whole. Here are examples for nested writes in the Prisma Client API: diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx index cb2390564b..02ad6cd477 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx @@ -12,7 +12,7 @@ From a technical perspective, Prisma Client consists of three major components: - TypeScript type definitions - A query engine (in the form of binary file) -All of these components are located in the [generated `@prisma/client` node module]() after you ran `prisma generate`. +All of these components are located in the [generated `@prisma/client` node module](./generating-prisma-client#the-prisma-client-npm-module) after you ran `prisma generate`. This page covers relevant technical details about the query engine. @@ -30,9 +30,9 @@ The query engine is running as a separate process on the same machine where the ![](https://i.imgur.com/1YmOJpx.png) -The query engine process is started when the [`connect()`]() method is called on your `PrismaClient` instance. Once the process is started, the query engine creates a [connnection pool]() and manages the physical connections to the database. From that point onwards, Prisma Client is ready to send [queries]() to the database (e.g. `findOne`, `findMany`, `create`, ...). +The query engine process is started when the [`connect()`](./connection-management) method is called on your `PrismaClient` instance. Once the process is started, the query engine creates a [connnection pool](./connection-management#connection-pool) and manages the physical connections to the database. From that point onwards, Prisma Client is ready to send [queries](./crud) to the database (e.g. `findOne`, `findMany`, `create`, ...). -The query engine process is stopped and the database connections are closed when [`disconnect()`]() is invoked. +The query engine process is stopped and the database connections are closed when [`disconnect()`](./connection-management) is invoked. The following diagram depicts a "typical flow": @@ -62,7 +62,7 @@ The query engine has the following responsibilities in an application that uses ## Debugging the query engine -You can access the logs of the query engine by setting the [`DEBUG`]() environment variable to `engine`: +You can access the logs of the query engine by setting the [`DEBUG`](./debugging) environment variable to `engine`: ```bash export DEBUG="engine" @@ -76,4 +76,4 @@ const prisma = new PrismaClient({ }); ``` -Learn more in the [debugging]() and [logging]() sections of the docs. +Learn more in the [Debugging](./debugging) and [Logging](./logging) pages of the docs. diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx index 6df75cbdaf..910244e8d7 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx @@ -8,7 +8,7 @@ metaDescription: '' _Module bundlers_ bundle JavaScript modules into a single JavaScript file. Most bundlers work by copying over the JavaScript code from a variety of source files into the target file. -Since Prisma Client is not only based on JavaScript code, but also relies on the [**query engine binary file**]() to be available, you need to make sure that your bundled code has access to the binary file. +Since Prisma Client is not only based on JavaScript code, but also relies on the [**query engine binary file**](./query-engine#the-query-engine-binary-file) to be available, you need to make sure that your bundled code has access to the binary file. To do so, you can use plugins that let you copy over static assets: diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx index fd6a2a8ac5..c16d521db3 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx @@ -8,7 +8,7 @@ metaDescription: '' Prisma Client provides features that are typically not achievable with relational databases. These features are referred to as _polyfills_. -- Initializing [ID]() values with `cuid` and `uuid` values -- Using [`@updatedAt`]() to store the time when a record was last updated -- [Making 1-1-relations required on both sides]() -- [Implicit many-to-many relations]() +- Initializing [ID](../prisma-schema/data-model#ids) values with `cuid` and `uuid` values +- Using [`@updatedAt`](../data-model#attributes) to store the time when a record was last updated +- [Making 1-1-relations required on both sides](../prisma-schema/relations#one-to-one-relations) +- [Implicit many-to-many relations](./prisma-schema/relations#implicit-many-to-many-relations) diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx index 640935ce37..c68c58215b 100644 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx +++ b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx @@ -7,16 +7,16 @@ experimental: true ## Overview -Prisma Migrate is a tool that lets you _change your database schema_, e.g. by creating new tables or adding columns to existing tables. These changes are called _schema migrations_. Prisma Migrate is available as part of the [Prisma CLI]() via the `prisma migrate` command. +Prisma Migrate is a tool that lets you _change your database schema_, e.g. by creating new tables or adding columns to existing tables. These changes are called _schema migrations_. Prisma Migrate is available as part of the [Prisma CLI](../prisma-cli/installation) via the `prisma migrate` command. -**Prisma Migrate is currently in an experimental state.** This means that it is not recommended to use Prisma Migrate in production. Instead, you can perform schema migrations using plain SQL or another migration tool of your choice and then bring the changes into your Prisma schema using [introspection](). +**Prisma Migrate is currently in an experimental state.** This means that it is not recommended to use Prisma Migrate in production. Instead, you can perform schema migrations using plain SQL or another migration tool of your choice and then bring the changes into your Prisma schema using [introspection](./introspection). ## Prisma Migrate vs SQL migrations Prisma Migrate is a _declarative_ migration system, as opposed to SQL which can be considered _imperative_: - **SQL (imperative)**: Provide the individual _steps_ to get from the current schema to the desired schema. -- **Prisma Migrate (delarative)**: Define the desired schema as a [Prisma data model]() (Prisma Migrate takes care of generating the necessary _steps_). +- **Prisma Migrate (delarative)**: Define the desired schema as a [Prisma data model](../prisma-schema/data-model) (Prisma Migrate takes care of generating the necessary _steps_). Here's a quick comparison. Assume you have the following scenario: @@ -64,14 +64,14 @@ ADD COLUMN published BOOLEAN DEFAULT false; ### Prisma Migrate -With Prisma Migrate, you write the desired database schema in the form of a [Prisma data model]() inside your [Prisma schema file](). To map the data model to your database schema, you then have to run these two commands: +With Prisma Migrate, you write the desired database schema in the form of a [Prisma data model](../prisma-schema/data-model) inside your [Prisma schema file](../prisma-schema/prisma-schema-file). To map the data model to your database schema, you then have to run these two commands: ``` prisma migrate save --experimental prisma migrate up --experimental ``` -The first command _saves_ a new migration to the file system and updates the [`_Migration`]() table. It stores information about the migration in a dedicated directory inside the [`migrations`]() directory. Each migration that is stored has its own `README.md` file which contains detailled information about the migration (e.g. the generated SQL statements which will be executed when you run `prisma migrate up`). +The first command _saves_ a new migration to the file system and updates the `_Migration` table. It stores information about the migration in a dedicated directory inside the `migrations` directory. Each migration that is stored has its own `README.md` file which contains detailled information about the migration (e.g. the generated SQL statements which will be executed when you run `prisma migrate up`). The second command _executes_ the migration against your database. @@ -120,7 +120,7 @@ model Post { } ``` -Notice that in addition to the [relation fields which represent the foreign keys](), you also must specify the [virtual relation fields]() on the other side of the relation. +Notice that in addition to the [annotated relation fields](../prisma-schema/relations#annotated-relation-fields-and-relation-scalar-fields) and its relation scalar field (which represent the foreign keys), you also must specify the Prisma-level [relation fields](../prisma-schema/relations#relation-fields) on the other side of the relation. Now run the two commands mentioned above: @@ -131,7 +131,7 @@ prisma migrate up --experimental **3. Add a new column with default value to the `Post` table** -Add a [field]() to the `Post` model: +Add a [field](../prisma-schema/models#fields) to the `Post` model: ```prisma model User { @@ -165,7 +165,7 @@ prisma migrate up --experimental ## Supported operations -The following table shows which SQL operations are currently supported by Prisma Migrate. If an operation is not yet supported, it links to a workaround that uses plain SQL and [introspection]() to enable this feature in Prisma Client. +The following table shows which SQL operations are currently supported by Prisma Migrate. If an operation is not yet supported, it links to a workaround that uses plain SQL and [introspection](./introspection) to enable this feature in Prisma Client. | Operation | SQL | Supported | | :---------------------------------- | :------------------------------ | :----------------------: | @@ -188,14 +188,6 @@ The following table shows which SQL operations are currently supported by Prisma Note that this table assumes that the operation is also supported by the underlying database. For example, `ENUM` is not supported in SQLite, this means that you also can't use `enum` using Prisma Migrate. -## Polyfills - -Prisma Migrate provides features that are typically not achievable with relational databases. These features are referred to as _polyfills_. - -- Initializing [ID]() values with `cuid` and `uuid` values (requires [Prisma Migrate]()) -- [Making 1-1-relations required on both sides]() -- [Implicit many-to-many relations]() - ## Migration history Prisma Migrate stores the migration history of your project in two places: diff --git a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx index 6bfa9ba799..c27a5a9f12 100644 --- a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx +++ b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx @@ -6,40 +6,40 @@ metaDescription: '' ## Overview -You can introspect your database using the Prisma CLI in order to generate the [data model]() in your [Prisma schema](). The data model is needed to [generate Prisma Client](). +You can introspect your database using the Prisma CLI in order to generate the [data model](./prisma-schema/data-model) in your [Prisma schema](./prisma-schema/prisma-schema-file). The data model is needed to [generate Prisma Client](../prisma-client/configuring-the-prisma-client-api). -Introspection is often used to generate an _initial_ version of the data model when [adding Prisma to an existing project](). +Introspection is often used to generate an _initial_ version of the data model when [adding Prisma to an existing project](../../getting-started/setup-prisma/add-to-an-existing-project). -However, it can also be used _repeatedly_ in an application. This is most commonly the case when you're _not_ using [Prisma Migrate]() but perform schema migrations using plain SQL or another migration tool. In that case, you also need to re-introspect your database and subsequently re-generate Prisma Client to reflect the schema changes in your [Prisma Client API](). +However, it can also be used _repeatedly_ in an application. This is most commonly the case when you're _not_ using [Prisma Migrate](./prisma-migrate) but perform schema migrations using plain SQL or another migration tool. In that case, you also need to re-introspect your database and subsequently re-generate Prisma Client to reflect the schema changes in your [Prisma Client API](../prisma-client/api). ## What does introspection do? -Introspection has one main goal: Populate your Prisma schema with a data model that reflects the current database schema. +Introspection has one main function: Populate your Prisma schema with a data model that reflects the current database schema. ![](https://imgur.com/EYC3RIK.png) Here's an overview of its main functions: -- Map _tables_ in the database to [Prisma models]() -- Map _columns_ in the database to the [fields]() of Prisma models -- Map _indexes_ in the database to [indexes]() in the Prisma schema -- Map _database_ constraints to [attributes]() or [type modifiers]() in the Prisma schema +- Map _tables_ in the database to [Prisma models](./prisma-schema/models) +- Map _columns_ in the database to the [fields](./prisma-schema/models#fields) of Prisma models +- Map _indexes_ in the database to [indexes](./prisma-schema/data-model#indexes) in the Prisma schema +- Map _database_ constraints to [attributes](./prisma-schema/data-model#attributes) or [type modifiers](./prisma-schema/models#type-modifiers) in the Prisma schema You can learn more about how Prisma maps types from the database to the types available in the Prisma schema on the respective docs page for the data source connector: -- [PostgreSQL]() -- [MySQL]() -- [SQLite]() +- [PostgreSQL](./database-connectors/postgresql) +- [MySQL](./database-connectors/mysql) +- [SQLite](./database-connectors/sqlite) ## The `prisma introspect` command -You can introspect your database using the `prisma introspect` command of the [Prisma CLI](). Note that using this command requires your [connection URL]() to be set in your Prisma schema! +You can introspect your database using the `prisma introspect` command of the [Prisma CLI](./prisma-cli/installation). Note that using this command requires your [connection URL](./database-connectors/connection-urls) to be set in your Prisma schema! -> **Warning**: The `prisma introspect` command overwrites the current version of your Prisma schema! If you made any manual adjustments to the Prisma schema (e.g. by adding [comments](), [making a 1-1-relation required on both sides]() or [configuring your Prisma Client API]()), be sure to back up your schema before running the command! +> **Warning**: The `prisma introspect` command overwrites the current version of your Prisma schema! If you made any manual adjustments to the Prisma schema (e.g. by adding [comments](/prisma-schema/prisma-schema-file), [making a 1-1-relation required on both sides](./prisma-schema/relations#making-both-sides-required-in-one-to-one-relations) or [configuring your Prisma Client API](./prisma-client/configuring-the-prisma-client-api)), be sure to back up your schema before running the command! Here's a high-level overview of the steps that `prisma introspect` performs internally: -1. Read the [connection URL]() from the `datasource` configuration in the Prisma schema +1. Read the [connection URL](./database-connectors/connection-urls) from the `datasource` configuration in the Prisma schema 1. Open database connection 1. Introspect database schema (i.e. read tables, columns and other structures ...) 1. Transform database schema into Prisma data model @@ -66,9 +66,9 @@ Prisma employs a number of conventions for translating a database schema into a Field, model and enum names (identifiers) must start with a letter and generally must only contain underscores, letters and digits. You can find the naming rules and conventions for each of these identifiers on the respective docs page: -- [Naming models]() -- [Naming fields]() -- [Naming enums]() +- [Naming models](./prisma-schema/models#naming-models) +- [Naming fields](./prisma-schema/models#naming-fields) +- [Naming enums](./prisma-schema/models#naming-enums) The general rule for identifiers is that they need to adhere to this regular expression: @@ -137,11 +137,11 @@ In this case, you must manually change the name of one of the two generated `Use ### Relations -Prisma translates foreign keys that are defined on your database tables into [relations](). +Prisma translates foreign keys that are defined on your database tables into [relations](./prisma-schema/relations). #### One-to-one relations -Prisma adds a [one-to-one]() relation to your data model when the foreign key on a table has a `UNIQUE` constraint, e.g.: +Prisma adds a [one-to-one](./prisma-schema/relations#one-to-one-relations) relation to your data model when the foreign key on a table has a `UNIQUE` constraint, e.g.: ```sql CREATE TABLE "User" ( @@ -168,7 +168,7 @@ model Profile { } ``` -Note that you can still [make both sides of the relation required]() by manually removing the `?` on `User.profile`: +Note that you can still [make both sides of the relation required](./prisma-schema/relations#making-both-sides-required-in-one-to-one-relations) by manually removing the `?` on `User.profile`: ```prisma model User { @@ -186,7 +186,7 @@ The required constraint will be enforced by Prisma Client. #### One-to-many relations -By default, Prisma adds a [one-to-many]() relation to your data model for a foreign key it finds in your database schema: +By default, Prisma adds a [one-to-many](./prisma-schema/relations#one-to-many-relations) relation to your data model for a foreign key it finds in your database schema: ```sql CREATE TABLE "User" ( @@ -203,8 +203,9 @@ These tables are transformed into the following models: ```prisma model Post { - id Int @default(autoincrement()) @id - author User @relation(references: [id]) + id Int @default(autoincrement()) @id + author User @relation(references: [id]) + authorId Int } model User { @@ -215,20 +216,20 @@ model User { #### Many-to-many relations -Many-to-many relations are commonly represented as [relation tables]() in relational databases. +[Many-to-many](./prisma-schema/relations#many-to-many-relations) relations are commonly represented as [relation tables](./prisma-schema/relations#relation-tables) in relational databases. Prisma supports two ways for defining many-to-many relations in the Prisma schema: -- [Implicit many-to-many relations]() (Prisma manages the relation table under the hood) -- [Explicit many-to-many relations]() (the relation table is present as a [model]()) +- [Implicit many-to-many relations](./prisma-schema/relations#implicit-many-to-many-relations) (Prisma manages the relation table under the hood) +- [Explicit many-to-many relations](./prisma-schema/relations#explicit-many-to-many-relations) (the relation table is present as a [model](./prisma-schema/models)) -_Implicit_ many-to-many relations are recognized if they adhere to Prisma's [conventions for relation tables](). Otherwise the relation table is rendered in the Prisma schema as a model (therefore making it an _explicit_ many-to-many relation). +_Implicit_ many-to-many relations are recognized if they adhere to Prisma's [conventions for relation tables](./prisma-schema/relations#conventions-for-relation-tables-in-implicit-m-n-relations). Otherwise the relation table is rendered in the Prisma schema as a model (therefore making it an _explicit_ many-to-many relation). -This topic is covered extensively on the docs page about [relations](). +This topic is covered extensively on the docs page about [Relations](./prisma-schema/relations). #### Disambiguating relations -Prisma generally omits the `name` argument on the [`@relation`]() attribute if it's not needed. Consider the `User` โ†” `Post` example from the previous section. The `@relation` attribute only has the `references` argument, `name` is omitted because it's not needed in this case: +Prisma generally omits the `name` argument on the [`@relation`](./prisma-schema/relations#the-relation-attribute) attribute if it's not needed. Consider the `User` โ†” `Post` example from the previous section. The `@relation` attribute only has the `references` argument, `name` is omitted because it's not needed in this case: ```prisma model Post { @@ -252,7 +253,7 @@ CREATE TABLE "Post" ( ); ``` -In this case, Prisma needs to [disambiguate the relation]() using a dedicated relation name: +In this case, Prisma needs to [disambiguate the relation](./prisma-schema/relations#disambiguating-relations) using a dedicated relation name: ```prisma model Post { @@ -268,7 +269,7 @@ model User { } ``` -Note that you can [rename the virtual relation field]() to anything you like so that it looks friendlier in the generated Prisma Client API. +Note that you can rename the [Prisma-level](./prisma-schema/relations#relation-fields) relation field to anything you like so that it looks friendlier in the generated Prisma Client API. ## Introspecting only a subset of your database schema @@ -276,4 +277,4 @@ Introspecting only a subset of your database schema is [not yet officially suppo However, you can achieve this by creating a new database user that only has access to the tables which you'd like to see represented in your Prisma schema, and then perform the introspection using that user. The introspection will then only include the tables the new user has access to. -If your goal is to exclude certain models from the [Prisma Client generation](), you can also manually delete the models that should be excluded from your Prisma schema. Note however that they will be added again when you run `prisma introspect`. +If your goal is to exclude certain models from the [Prisma Client generation](./prisma-client/generating-prisma-client), you can also manually delete the models that should be excluded from your Prisma schema. Note however that they will be added again when you run `prisma introspect`. From d4b23df52b5c39cdc2091c729480b5455875c880 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 14:41:17 +0200 Subject: [PATCH 49/76] update links on more reference pages --- .../05-prisma-cli/01-installation.mdx | 58 ++++++++++++------- .../02-database-connectors/01-features.mdx | 50 ++++++++-------- .../02-connection-urls.mdx | 10 ++-- .../02-database-connectors/03-postgresql.mdx | 16 ++--- .../02-database-connectors/04-mysql.mdx | 17 +++--- .../02-database-connectors/05-sqlite.mdx | 4 +- 6 files changed, 84 insertions(+), 71 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx index 81c9641a0e..c3b09f8f63 100644 --- a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx +++ b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx @@ -8,28 +8,29 @@ metaDescription: '' The Prisma CLI is available as an [npm package](). It is **recommended to install the Prisma CLI locally** in your project's `package.json` to avoid version conflicts. -## Local installation (recommended) -The Prisma CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. +### Local installation (recommended) + +The Prisma 2 CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. #### npm Install with npm: ``` -npm install prisma2 --save-dev +npm install @prisma/cli --save-dev ``` -This should add `prisma2` to the `devDependencies` in your `package.json`. You can then invoke the locally installed `prisma2` CLI by prefixing it with [`npx`](https://github.com/npm/npx#readme): +This should add `@prisma/cli` to the `devDependencies` in your `package.json`. You can then invoke the locally installed CLI with the **`prisma`** command prefixed with [`npx`](https://github.com/npm/npx#readme): ``` -npx prisma2 +npx prisma ``` Here's an example for invoking the `generate` command: ``` -npx prisma2 generate +npx prisma generate ``` #### Yarn @@ -37,24 +38,24 @@ npx prisma2 generate Install with Yarn: ``` -yarn add prisma2 dev +yarn add @prisma/cli --dev ``` -This should add `prisma2` to the `devDependencies` in your `package.json`. You can then invoke the locally installed `prisma2` CLI by prefixing it with `yarn`: +This should add `@prisma/cli` to the `devDependencies` in your `package.json`. You can then invoke the locally installed CLI with the **`prisma`** command prefixed with `yarn`: ``` -yarn prisma2 +yarn prisma ``` Here's an example for invoking the `generate` command: ``` -yarn prisma2 generate +yarn prisma generate ``` -## Global installation +### Global installation (not recommended) -While it is recommended to [locally install](#local-installation-recommended) the `prisma2` CLI, you can also install it globally on your machine. +While it is recommended to [locally install](#local-installation-recommended) the Prisma 2 CLI, you can also install it globally on your machine. > **Warning**: If you have several Prisma projects on your machine, a global installation can lead to version conflicts between these projects. @@ -63,19 +64,19 @@ While it is recommended to [locally install](#local-installation-recommended) th Install with npm: ``` -npm install -g prisma2 +npm install -g @prisma/cli ``` -You can then invoke the globally installed `prisma2` CLI like so: +You can then invoke the globally installed CLI with the **`prisma`** command like so: ``` -prisma2 +prisma ``` Here's an example for invoking the `generate` command: ``` -prisma2 generate +prisma generate ``` #### Yarn @@ -83,17 +84,34 @@ prisma2 generate Install with Yarn: ``` -yarn global add prisma2 +yarn global add @prisma/cli ``` -You can then invoke the globally installed `prisma2` CLI like so: +You can then invoke the globally installed CLI with the **`prisma`** command like so: ``` -prisma2 +prisma ``` Here's an example for invoking the `generate` command: ``` -prisma2 generate +prisma generate ``` + +### The `postinstall` hook + +When installing Prisma 2 CLI, a [`postinstall`](https://github.com/prisma/prisma/blob/master/cli/sdk/package.json#L13) hook is being executed. It downloads Prisma 2's query and migration [engine binaries](https://github.com/prisma/prisma-engine). The query engine contains the [Prisma schema](../prisma-schema/prisma-schema-file) parser which is used by the `prisma init` and the `prisma generate` commands. The migration engine is used by all `prisma migrate` commands. + +## Using a HTTP proxy for the CLI + +Prisma 2 CLI supports [custom HTTP proxies](https://github.com/prisma/prisma/issues/506). This is particularly relevant when being behind a corporate firewall. + +To activate the proxy, provide the environment variables `HTTP_PROXY` and/or `HTTPS_PROXY`. The behavior is very similar to how the [`npm` CLI handles this](https://docs.npmjs.com/misc/config#https-proxy). + +The following environment variables can be provided: + +- `HTTP_PROXY` or `http_proxy`: Proxy URL for http traffic, for example `http://localhost:8080` +- `HTTPS_PROXY` or `https_proxy`: Proxy URL for https traffic, for example `https://localhost:8080` + +> To get a local proxy, you can also use the [`proxy`](https://www.npmjs.com/package/proxy) module: diff --git a/content/03-reference/02-database-connectors/01-features.mdx b/content/03-reference/02-database-connectors/01-features.mdx index a802cb9333..4bdd966686 100644 --- a/content/03-reference/02-database-connectors/01-features.mdx +++ b/content/03-reference/02-database-connectors/01-features.mdx @@ -10,7 +10,7 @@ This page gives an overview of the features which are provided by the databases ## Relational database features -This section describes which database features exist on the databases that are currently supported by Prisma. The **Prisma schema** column indicates how a certain feature can be represented in the [Prisma schema]() and links to its documentation. Note that database features can be used in **Prisma Client** even though they might not yet be representable in the Prisma schema. +This section describes which database features exist on the databases that are currently supported by Prisma. The **Prisma schema** column indicates how a certain feature can be represented in the [Prisma schema](../prisma-schema/prisma-schema-file) and links to its documentation. Note that database features can be used in **Prisma Client** even though they might not yet be representable in the Prisma schema. If a feature is not supported natively by the database, it's also not available in Prisma. @@ -18,12 +18,12 @@ If a feature is not supported natively by the database, it's also not available | Constraint | PostgreSQL | MySQL | SQLite | Prisma schema | Prisma Client | Prisma Migrate | | ------------- | :--------: | :---: | :----: | :--------------------------: | :-----------: | :------------: | -| `PRIMARY KEY` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@id` and `@@id`]() | โœ”๏ธ | โœ”๏ธ | -| `FOREIGN KEY` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [Relation fields]() | โœ”๏ธ | โœ”๏ธ | -| `UNIQUE` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@unique` and `@@unique`]() | โœ”๏ธ | โœ”๏ธ | +| `PRIMARY KEY` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@id` and `@@id`](../prisma-schema/data-model#ids) | โœ”๏ธ | โœ”๏ธ | +| `FOREIGN KEY` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [Relation fields](prisma-schema/relations#relation-fields) | โœ”๏ธ | โœ”๏ธ | +| `UNIQUE` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@unique` and `@@unique`](../prisma-schema/data-model#unique) | โœ”๏ธ | โœ”๏ธ | | `CHECK` | โœ”๏ธ | โœ”\* | โœ”๏ธ | Not yet | โœ”๏ธ | Not yet | -| `NOT NULL` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`?`]() | โœ”๏ธ | โœ”๏ธ | -| `DEFAULT` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@default`]() | โœ”๏ธ | โœ”๏ธ | +| `NOT NULL` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`?`](../prisma-schema/models#type-modifiers) | โœ”๏ธ | โœ”๏ธ | +| `DEFAULT` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@default`](../prisma-schema/data-model#default-values) | โœ”๏ธ | โœ”๏ธ | \*In [MySQL 8 and higher](https://mysqlserverteam.com/mysql-8-0-16-introducing-check-constraint/) @@ -51,7 +51,7 @@ If a feature is not supported natively by the database, it's also not available | Index | PostgreSQL | MySQL | SQLite | Prisma schema | Prisma Client | Prisma Migrate | | -------- | ---------- | ----- | ------ | ---------------------------- | ------------- | -------------- | -| `UNIQUE` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@unique` and `@@unique`]() | โœ”๏ธ | Not yet | +| `UNIQUE` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`@unique` and `@@unique`](../prisma-schema/data-model#unique) | โœ”๏ธ | Not yet | | `WHERE` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | Not yet | โœ”๏ธ | Not yet | | `USING` | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | Not yet | โœ”๏ธ | Not yet | @@ -88,9 +88,9 @@ Lock option (MySQL): | Feature | PostgreSQL | MySQL | SQLite | Prisma schema | Prisma Client | Prisma Migrate | | --------------------------------- | ---------- | ----- | ------ | --------------------- | ------------- | -------------- | -| Autoincrementing IDs | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`autoincrement()`]() | โœ”๏ธ | โœ”๏ธ | -| Arrays | โœ”๏ธ | No | No | [`[]`]() | โœ”๏ธ | โœ”๏ธ | -| Enums | โœ”๏ธ | โœ”๏ธ | No | [`enum`]() | โœ”๏ธ | โœ”๏ธ | +| Autoincrementing IDs | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | [`autoincrement()`](../prisma-schema/data-model#single-field-ids-with-default-values) | โœ”๏ธ | โœ”๏ธ | +| Arrays | โœ”๏ธ | No | No | [`[]`](../prisma-schema/models#type-modifiers) | โœ”๏ธ | โœ”๏ธ | +| Enums | โœ”๏ธ | โœ”๏ธ | No | [`enum`](../prisma-schema/data-model#enums) | โœ”๏ธ | โœ”๏ธ | | Native database types | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | Not yet | โœ”๏ธ | Not yet | | SQL Views | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | Not yet | Not yet | Not yet | | Authorization and user management | โœ”๏ธ | โœ”๏ธ | No | Not yet | Not yet | Not yet | @@ -100,11 +100,11 @@ Lock option (MySQL): ## Prisma features -This section provides a high-level overview of the features that are provided by Prisma. Some features directly map to a feature in the underlying database, others are implemented by Prisma's [query engine]() and therefore provide features that would not be available when using plain SQL. +This section provides a high-level overview of the features that are provided by Prisma. Some features directly map to a feature in the underlying database, others are implemented by Prisma's [query engine](../prisma-client/query-engine) and therefore provide features that would not be available when using plain SQL. ### Data modeling -You can find a full reference of all data modeling feature on the [Data model]() page. +You can find a full reference of all data modeling feature on the [Data model](../prisma-schema/data-model) page. #### Functions @@ -113,9 +113,9 @@ The following functions are implemented by Prisma's query engine: | Name | Description | | -------- | -------------------------- | | `uuid()` | Generates a UUID value | -| `cuid()` | Generated a [cuid]() value | +| `cuid()` | Generates a [cuid](https://github.com/ericelliott/cuid) value | -`uuid()` and `cuid()` are commonly used to set default values for [ID]() fields. +`uuid()` and `cuid()` are commonly used to set default values for [ID](../prisma-schema/data-model#ids) fields. #### Attributes -The following [attributes]() are available in Prisma. They either map to a database feature or are implemented by Prisma's query engine: +The following [attributes](../prisma-schema/data-model#attributes) are available in Prisma. They either map to a database feature or are implemented by Prisma's [query engine](../prisma-client/query-engine): | Name | Database representation | Description | | :----------- | :---------------------- | :------------------------------------------------------------------------------------- | @@ -152,22 +148,22 @@ The following [attributes]() are available in Prisma. They either map to a datab | `@unique` | `UNIQUE` | Defines a unique constraint for this field. | | `@@unique` | `UNIQUE` | Defines a compound unique constraint for the specified fields. | | `@@index` | `INDEX` | Defines an index. | -| `@relation` | n/a\* | Defines meta information about the relation. [Learn more](). | +| `@relation` | n/a\* | Defines meta information about the relation. [Learn more](../prisma-schema/relations). | | `@map` | n/a\* | Maps a field name from the Prisma schema to a different column name. | | `@@map` | n/a\* | Maps a model name from the Prisma schema to a differenttable name. | | `@updatedAt` | n/a\*\* | Automatically stores the time when a record was last updated. | \*A Prisma feature that doesn't map directly to the database -\*\*Implemented by Prisma's [query engine]() +\*\*Implemented by Prisma's [query engine](../prisma-client/query-engine) ### Queries (Prisma Client API) -- [CRUD]() -- [Fully type-safe]() +- CRUD +- Fully type-safe - Autocompleting database queries -- [Field selection]() -- [Raw database access]() +- Field selection +- Raw database access - Filtering - Ordering - Pagination diff --git a/content/03-reference/02-database-connectors/02-connection-urls.mdx b/content/03-reference/02-database-connectors/02-connection-urls.mdx index 7f14fd1172..05837a3e4b 100644 --- a/content/03-reference/02-database-connectors/02-connection-urls.mdx +++ b/content/03-reference/02-database-connectors/02-connection-urls.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -Prisma needs a connection URL to be able to connect to your database, e.g. when sending queries with [Prisma Client]() or when changing the database schema with [Prisma Migrate](). +Prisma needs a connection URL to be able to connect to your database, e.g. when sending queries with [Prisma Client](../prisma-client/api) or when changing the database schema with [Prisma Migrate](../prisma-migrate). The connection URL is provided via the `url` field of a `datasource` block in your Prisma schema. It generally consists of the following components (except for SQLite): @@ -16,7 +16,7 @@ The connection URL is provided via the `url` field of a `datasource` block in yo - **Port**: The port on which your database server is running - **Database name**: The name of the database you want to use -Make sure you have this information at hand when getting started with Prisma. If you don't have a database server running yet, you can either use a local SQLite database file (see the [Quickstart]()) or [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1). +Make sure you have this information at hand when getting started with Prisma. If you don't have a database server running yet, you can either use a local SQLite database file (see the [Quickstart](../../../getting-started/quickstart)) or [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1). ## Examples @@ -70,6 +70,6 @@ DATABASE_URL=postgresql://janedoe:mypassword@localhost:5432/mydb The format of the connection URL depends on the _database connector_ you're using. Prisma generally supports the standard formats for each database. You can find out more about the connection URL of your database on the dedicated docs page: -- [PostgreSQL]() -- [MySQL]() -- [SQLite]() +- [PostgreSQL](./postgresql) +- [MySQL](./mysql) +- [SQLite](./sqlite) diff --git a/content/03-reference/02-database-connectors/03-postgresql.mdx b/content/03-reference/02-database-connectors/03-postgresql.mdx index d301a4f3ca..a957559548 100644 --- a/content/03-reference/02-database-connectors/03-postgresql.mdx +++ b/content/03-reference/02-database-connectors/03-postgresql.mdx @@ -6,11 +6,11 @@ metaDescription: '' ## Overview -The PostgreSQL data source connector connects Prisma to a [PostgreSQL]() database server. +The PostgreSQL data source connector connects Prisma to a [PostgreSQL](https://www.postgresql.org/) database server. ## Example -To connect to a PostgreSQL database server, you need to configure a [`datasource`]() block in your [Prisma schema file](): +To connect to a PostgreSQL database server, you need to configure a [`datasource`](../prisma-schema/data-sources) block in your [Prisma schema file](../prisma-schema/prisma-schema-file): ```prisma datasource postgresql { @@ -22,7 +22,7 @@ datasource postgresql { The fields passed to the `datasource` block are: - `provider`: Specifies the `postgresql` data source connector. -- `url`: Specifies the [connection URL](#connection-url) for the PostgreSQL database server. In this case, an [environment variable is used]() to provide the connection URL. +- `url`: Specifies the [connection URL](#connection-url) for the PostgreSQL database server. In this case, an [environment variable is used](../prisma-schema/prisma-schema-file#using-environment-variables) to provide the connection URL. ## Connection details @@ -48,7 +48,7 @@ The following components make up the _base URL_ of your database, they are alway | Port | `PORT` | Port on which your database server is running, e.g. `5432` | | User | `USER` | Name of your database user, e.g. `janedoe` | | Password | `PASSWORD` | Password for your database user | -| Database | `DATABASE` | Name of the [database]() you want to use, e.g. `mydb` | +| Database | `DATABASE` | Name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) you want to use, e.g. `mydb` | **Arguments** @@ -62,8 +62,8 @@ The following arguments can be used | Argument name | Required | Default | Description | | :----------------- | :------- | ---------------------- | ------------------------------------------------------------------------------ | -| `schema` | **Yes** | `public` | Mame of the schema you want to use, e.g. `myschema` | -| `connection_limit` | No | `num_cpus * 2 + 1` | Maximum size of the [connection pool]() | +| `schema` | **Yes** | `public` | Name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) you want to use, e.g. `myschema` | +| `connection_limit` | No | `num_cpus * 2 + 1` | Maximum size of the [connection pool](../prisma-client/connection-management#connection-pool)) | | `connect_timeout` | No | `5` | Maximum number of seconds to wait for a new connection | | `socket_timeout` | No | `5` | Maximum number of seconds to wait until a single query terminates | | `sslmode` | No | `prefer` | Configures whether to use TLS, possible values: `prefer`, `disable`, `require` | @@ -120,7 +120,7 @@ Note that `localhost` is required, the value itself is ignored and can be anythi ## Type mapping between PostgreSQL to Prisma schema -The PostgreSQL connector maps the [scalar types]() from the Prisma [data model]() as follows to native column types: +The PostgreSQL connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the Prisma [data model](../prisma-schema/data-model) as follows to native column types: ### Prisma Migrate @@ -188,7 +188,7 @@ When introspecting a PostgreSQL database, the database types are mapped to Prism | Composite types | n/a | Not yet | | Domain types | n/a | Not yet | -During [introspection](), fields with types that **already have match in the Prisma schema but are not yet supported** will be added to the Prisma schema as comments, e.g. `macaddr` would be added to a model as follows: +During [introspection](../introspection), fields with types that **already have match in the Prisma schema but are not yet supported** will be added to the Prisma schema as comments, e.g. `macaddr` would be added to a model as follows: ```prisma model Device { diff --git a/content/03-reference/02-database-connectors/04-mysql.mdx b/content/03-reference/02-database-connectors/04-mysql.mdx index 32386ed0eb..ca94884028 100644 --- a/content/03-reference/02-database-connectors/04-mysql.mdx +++ b/content/03-reference/02-database-connectors/04-mysql.mdx @@ -6,11 +6,11 @@ metaDescription: '' ## Overview -The MySQL data source connector connects Prisma to a [MySQL]() database server. +The MySQL data source connector connects Prisma to a [MySQL](https://www.mysql.com/) database server. ## Example -To connect to a MySQL database server, you need to configure a [`datasource`]() block in your [Prisma schema file](): +To connect to a MySQL database server, you need to configure a [`datasource`](../prisma-schema/data-sources) block in your [Prisma schema file](../prisma-schema/prisma-schema-file): ```prisma datasource mysql { @@ -22,7 +22,7 @@ datasource mysql { The fields passed to the `datasource` block are: - `provider`: Specifies the `mysql` data source connector. -- `url`: Specifies the [connection URL](#connection-url) for the MySQL database server. In this case, an [environment variable is used]() to provide the connection URL. +- `url`: Specifies the [connection URL](#connection-url) for the MySQL database server. In this case, an [environment variable is used](../prisma-schema/prisma-schema-file#using-environment-variables) to provide the connection URL. ## Connection details @@ -30,7 +30,7 @@ The fields passed to the `datasource` block are: Here's an overview of the components needed for a MySQL connection URL: -![](![](https://imgur.com/NswjbsP.png) +![](https://imgur.com/NswjbsP.png) **Base URL and path** @@ -48,7 +48,7 @@ The following components make up the _base URL_ of your database, they are alway | Port | `PORT` | Port on which your database server is running, e.g. `5432` | | User | `USER` | Name of your database user, e.g. `janedoe` | | Password | `PASSWORD` | Password for your database user | -| Database | `DATABASE` | Name of the [database]() you want to use, e.g. `mydb` | +| Database | `DATABASE` | Name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) you want to use, e.g. `mydb` | **Arguments** @@ -62,8 +62,7 @@ The following arguments can be used | Argument name | Required | Default | Description | | :----------------- | :------- | ---------------------- | ------------------------------------------------------------------------------ | -| `schema` | **Yes** | `public` | Mame of the schema you want to use, e.g. `myschema` | -| `connection_limit` | No | `num_cpus * 2 + 1` | Maximum size of the [connection pool]() | +| `connection_limit` | No | `num_cpus * 2 + 1` | Maximum size of the [connection pool](../prisma-client/connection-management#connection-pool) | | `connect_timeout` | No | `5` | Maximum number of seconds to wait for a new connection | | `socket_timeout` | No | `5` | Maximum number of seconds to wait until a single query terminates | | `sslmode` | No | `prefer` | Configures whether to use TLS, possible values: `prefer`, `disable`, `require` | @@ -120,7 +119,7 @@ Note that `localhost` is required, the value itself is ignored and can be anythi ## Type mapping between MySQL to Prisma schema -The MySQL connector maps the [scalar types]() from the Prisma [data model]() as follows to native column types: +The MySQL connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the Prisma [data model](..//prisma-schema/data-model) as follows to native column types: ### Prisma Migrate @@ -174,7 +173,7 @@ When introspecting a MySQL database, the database types are mapped to Prisma acc | `multipolygon` | | Not yet | | `geometrycollection` | | Not yet | -During [introspection](), fields with types that **already have match in the Prisma schema but are not yet supported** will be added to the Prisma schema as comments, e.g. `macaddr` would be added to a model as follows: +During [introspection](../introspection), fields with types that **already have match in the Prisma schema but are not yet supported** will be added to the Prisma schema as comments, e.g. `macaddr` would be added to a model as follows: ```prisma model Device { diff --git a/content/03-reference/02-database-connectors/05-sqlite.mdx b/content/03-reference/02-database-connectors/05-sqlite.mdx index d91113b9b5..dad055c3ed 100644 --- a/content/03-reference/02-database-connectors/05-sqlite.mdx +++ b/content/03-reference/02-database-connectors/05-sqlite.mdx @@ -22,11 +22,11 @@ datasource sqlite { The fields passed to the `datasource` block are: - `provider`: Specifies the `sqlite` data source connector. -- `url`: Specifies the [connection string](#connection-string) for the SQLite database. The connection string always starts with the prefix `file:` and then contains a file path pointing to the SQLite database file. In this case, the file is located in the same directory and called `dev.db`. +- `url`: Specifies the [connection URL](./connection-urls) for the SQLite database. The connection URL always starts with the prefix `file:` and then contains a file path pointing to the SQLite database file. In this case, the file is located in the same directory and called `dev.db`. ## Data model mapping -The SQLite connector maps the [scalar types]() from the [data model]() to native column types as follows: +The SQLite connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the [data model](..//prisma-schema/data-model) to native column types as follows: | Data model | SQLite | | ---------- | --------- | From 4a31f350138eb519bb531c3754b43d606f0d350e Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 14:56:31 +0200 Subject: [PATCH 50/76] continue docs content --- .../01-prisma-schema/06-relations.mdx | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 39f929a786..1b8eb7ae8a 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -27,7 +27,6 @@ model Post { > > This means that one side of the relation represents the _foreign key_ in the underlying database, the other relation field is provided on a Prisma-level (in the case of implicit many-to-many relations, both relation fields are provided on a Prisma-level). - ## Example The examples on this page are based on the following schema file: @@ -107,7 +106,7 @@ These models have the following fields: | `User` | `id` | `Int` | No | | | `email` | `String` | No | | | `role` | `Role` | No | -| | `posts` | `Post[]` | **Yes** | +| | `posts` | `Post[]` | **Yes** (Prisma-level) | | `Post` | `id` | `Int` | No | | | `title` | `String` | No | | | `authorId` | `Int` | No (_relation scalar field_) | @@ -115,7 +114,9 @@ These models have the following fields: Both `posts` and `author` are relation fields because their types are not scalar types but other models. -Also note that the annotated relation field `author` needs to link the relation scalar field `authorId` on the `Post` model inside the `@relation` attribute. +Also note that the annotated relation field `author` needs to link the relation scalar field `authorId` on the `Post` model inside the `@relation` attribute. The relation scalar represents the foreign key in the underlying database. + +The other relation field called `posts` is defined purely on a Prisma-leve, it doesn't manifest in the database. ### Implicit vs explicit many-to-many relations @@ -346,11 +347,11 @@ Here are some example scenarios when the `@relation` attribute is needed, e.g. w > **Note**: The leading underscore in the signature means that the argument name can be omitted. -| Argument | Type | Required | Description | Example | -| :----------- | :----------------- | :------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | -| `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | -| `fields` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | -| `references` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | +| Argument | Type | Required | Description | Example | +| :----------- | :----------------- | :------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- | +| `name` | `String` | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | `"CategoryOnPost"`, `"MyRelation"` | +| `fields` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the _current_ model | `["authorId"]`, `["authorFirstName, authorLastName"]` | +| `references` | `FieldReference[]` | On [annotated](#annotated-relation-fields-and-relation-scalar-fields) relation fields | A list of [fields](./models#fields) of the model on _the other side of the relation_ | `["id"]`, `["firstName, lastName"]` | ## One-to-one relations @@ -1066,7 +1067,7 @@ There are two different kinds of virtual relation fields. For **1-1 and 1-n relations**, one side of the relation represents a foreign key, the other side is a virtual relation field: - \ No newline at end of file +--> From 6b0e448ccc615a9a04eb7d12deb641d4b7220642 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 15:05:10 +0200 Subject: [PATCH 51/76] wrap up fixing links --- .../01-postgresql.mdx | 2 +- .../02-mysql.mdx | 2 +- .../03-sqlite.mdx | 2 +- .../05-foreign-keys/01-postgresql.mdx | 2 +- .../05-foreign-keys/02-mysql.mdx | 2 +- .../05-foreign-keys/03-sqlite.mdx | 2 +- .../06-cascading-deletes/01-postgresql.mdx | 2 +- .../07-data-validation/01-postgresql.mdx | 2 +- content/05-more/04-creating-bug-reports.mdx | 2 +- content/05-more/05-faq.mdx | 24 ++++++++++--------- content/05-more/06-limitations.mdx | 4 ++-- content/05-more/07-roadmap.mdx | 4 ++-- 12 files changed, 26 insertions(+), 24 deletions(-) diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx index 4865d6adb4..3fd80616e8 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx @@ -203,7 +203,7 @@ datasource postgresql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx index 09aa6a4781..1a9015774e 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx @@ -218,7 +218,7 @@ datasource mysql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx index ba527d638b..fd27abd947 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx @@ -139,7 +139,7 @@ datasource sqlite { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx index 0f1621a4e8..e0d1554840 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx @@ -148,7 +148,7 @@ datasource postgresql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx index ba5e8d5f03..3cd4d8148a 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx @@ -129,7 +129,7 @@ datasource mysql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx index f03dd3f1b5..d910d059db 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx @@ -146,7 +146,7 @@ datasource sqlite { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx b/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx index 5a8049cf3b..cb5012446c 100644 --- a/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx @@ -277,7 +277,7 @@ datasource postgresql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx b/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx index dd78ac0de1..7cf16c0b4c 100644 --- a/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx @@ -263,7 +263,7 @@ datasource postgresql { } ``` -The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`]() format which automatically picks up environment variables defined in a file called `.env`. +The database connection URL is set via an environment variable. The Prisma CLI automatically supports the [`dotenv`](https://github.com/motdotla/dotenv) format which automatically picks up environment variables defined in a file called `.env`. Create a new file called `.env` and set your database connection URL as the `DATABASE_URL` environment variable: diff --git a/content/05-more/04-creating-bug-reports.mdx b/content/05-more/04-creating-bug-reports.mdx index 10e618e204..db5bbd07b6 100644 --- a/content/05-more/04-creating-bug-reports.mdx +++ b/content/05-more/04-creating-bug-reports.mdx @@ -20,7 +20,7 @@ If you don't have the time to create a full reproduction of the issue, please in ### Include logging and debugging output -Please make sure to include _any_ [logging](./prisma-client-js/api.md#logging) and [debugging](./prisma-client-js/api.md#debugging) output in the issue that may help to identify the problem. +Please make sure to include _any_ [logging](../reference/tools-and-interfaces/prisma-client/logging) and [debugging](../reference/tools-and-interfaces/prisma-client/debugging) output in the issue that may help to identify the problem. **Setting the `DEBUG` env var** diff --git a/content/05-more/05-faq.mdx b/content/05-more/05-faq.mdx index 8328a59dd1..063ff700a7 100644 --- a/content/05-more/05-faq.mdx +++ b/content/05-more/05-faq.mdx @@ -6,9 +6,9 @@ metaDescription: '' ## Can I still access my database directly (e.g. using raw SQL)? -Yes, Prisma Client provides has a method called [`.raw`]() which you can use to send raw SQL strings to the database. +Yes, Prisma Client provides has a method called [`.raw`](../reference/tools-and-interfaces/prisma-client/raw-database-access) which you can use to send raw SQL strings to the database. -Note that Prisma currently doesn't support full [transactions](). If your application needs transactions, you can use Prisma Client alongside other lightweight query builder such as [knex](https://www.github.com/tgriesser/knex) to perform one-off queries as transaction. +Note that Prisma currently doesn't support full [transactions](./reference/tools-and-interfaces/prisma-client/transactions). If your application needs transactions, you can use Prisma Client alongside other lightweight query builder such as [knex.js](https://www.github.com/tgriesser/knex) to perform one-off queries as transaction. ## Is Prisma Client an ORM? @@ -16,7 +16,7 @@ ORMs are typically object-oriented mapping layers that map classes to tables. A ## Will Prisma Client support more databases (and other data sources) in the future? -Yes. Prisma Client is based on Prisma's [query engine]() that can connect to any data source that provides a proper _connector implementation_. There will be built-in connectors such as the current ones for [PostgreSQL](), [MySQL]() and [SQLite](). +Yes. Prisma Client is based on Prisma's [query engine](./reference/tools-and-interfaces/prisma-client/query-engine) that can connect to any data source that provides a proper _connector implementation_. There will be built-in connectors such as the current ones for [PostgreSQL](../reference/tools-and-interfaces/database-connectors/postgresql), [MySQL](../reference/tools-and-interfaces/database-connectors/mysql) and [SQLite](../reference/tools-and-interfaces/database-connectors/sqlite). However, it's also possible to build your own connectors, more documentation on that topic will follow soon. @@ -30,11 +30,11 @@ const prisma = new PrismaClient({ }); ``` -Learn more on the [Debugging]() page in the docs. +Learn more on the [Debugging](../reference/tools-and-interfaces/prisma-client/debugging) page in the docs. ## How do schema migrations work with Prisma Client? -Prisma Client is not opinionated on how exactly you migrate your database schema (e.g. create new tables, alter columns, ...). You can keep your existing migration system and re-[introspect]() your database schema after each schema migration. You can also use Prisma Migrate to run your migrations based on Prisma's declarative [data model definition](). +Prisma Client is not opinionated on how exactly you migrate your database schema (e.g. create new tables, alter columns, ...). You can keep your existing migration system and re-[introspect](../reference/tools-and-interfaces/introspection) your database schema after each schema migration. You can also use Prisma Migrate to run your migrations based on Prisma's declarative [data model definition](../reference/tools-and-interfaces/prisma-schema/data-model). ## Is Prisma Client production-ready? Should I start using it? @@ -46,15 +46,15 @@ GraphQL [schema delegation](https://www.prisma.io/blog/graphql-schema-stitching- Prisma 1 officially supports both schema delegation and GraphQL binding as it exposes a GraphQL CRUD API through the [Prisma server](https://www.prisma.io/docs/prisma-server/). This API can be used to as foundation for an application-layer GraphQL API created with GraphQL binding. -With Prisma 2.0, Prisma's [query engine]() doesn't expose a [spec](https://graphql.github.io/graphql-spec/June2018/)-compliant GraphQL endpoint any more, so usage of schema delegation and GraphQL binding with Prisma 2.0 is not supported. To build GraphQL servers with Prisma 2.0, be sure to check out [GraphQL Nexus](https://nexusjs.org/). GraphQL Nexus provides a code-first and type-safe way to build GraphQL servers in a scalable way. +With Prisma 2.0, Prisma's [query engine](../reference/tools-and-interfaces/prisma-client/query-engine) doesn't expose a [spec](https://graphql.github.io/graphql-spec/June2018/)-compliant GraphQL endpoint any more, so usage of schema delegation and GraphQL binding with Prisma 2.0 is not supported. To build GraphQL servers with Prisma 2.0, be sure to check out [GraphQL Nexus](https://nexusjs.org/). GraphQL Nexus provides a code-first and type-safe way to build GraphQL servers in a scalable way. -Learn more about how Prisma can be used to build GraphQL servers on the [GraphQL]() page in the docs. +Learn more about how Prisma can be used to build GraphQL servers on the [GraphQL](../understand-prisma/prisma-in-your-stack/graphql) page in the docs. ## Am I locked-in when using Prisma Migrate? Is it easy to migrate off it? There's no lock-in when using Prisma Migrate. To stop using Prisma for your migrations, you need to: -- delete your [Prisma schema file]() +- delete your [Prisma schema file](../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) - the `migrations` directory on your file system - drop the `_Migrations` table in your database/schema @@ -62,13 +62,13 @@ There's no lock-in when using Prisma Migrate. To stop using Prisma for your migr Each migration is represented via its own directory on your file system inside a directory called `migrations`. The name of each directory contains a timestamp so that the order of all migrations in the project history can be maintained. -Each of these migration directories contains detailed information about the respective migration, for example which steps are executed (and in what order) as well as a human-friendly Markdown file that summarizes the most important information about the migration, such as the source and the target [data model definition]() of the migration. This information can also be found in the `_Migrations` table in your database/schema. +Each of these migration directories contains detailed information about the respective migration, for example which steps are executed (and in what order) as well as a human-friendly Markdown file that summarizes the most important information about the migration, such as the source and the target [data model definition](../reference/tools-and-interfaces/prisma-schema/data-model) of the migration. This information can also be found in the `_Migrations` table in your database/schema. ## Is Prisma Migrate production-ready? Should I start using it? Prisma Migrate is currently in an experimental state. It has a number of issues that don't make it suitable for production uses. You can track the progress of the release process on [isprisma2ready.com](https://www.isprisma2ready.com). -While it shouldn't be used for mission critical applications yet, Prisma Migrate is definitely in a usable state. You can help us accelerate the release process by using it and [sharing your feedback]() with us. +While it shouldn't be used for mission critical applications yet, Prisma Migrate is definitely in a usable state. You can help us accelerate the release process by using it and [sharing your feedback](https://github.com/prisma/prisma2) with us. ## Since Prisma 2.0 is released, will Prisma 1 still be maintained? @@ -76,9 +76,11 @@ Yes, Prisma 1 will continue to be maintained. However, most Prisma engineering a There will be no new features developed for Prisma 1. +Note that there will be dedicated tooling and detailled migration guides to help you with the setup. + ## Where can I get more information about the plans for Prisma 2.0? -Check out the [`specs`](https://github.com/prisma/specs) repo which contains the technical specifications for future Prisma 2.0 features. Get involved by [creating issues](https://github.com/prisma/prisma2/issues) and [sharing feedback]()! +Check out the [`specs`](https://github.com/prisma/specs) repo which contains the technical specifications for future Prisma 2.0 features. Get involved by [creating issues](https://github.com/prisma/prisma2/issues) and [sharing feedback](https://github.com/prisma/prisma2)! ## How much does Prisma 2.0 cost? diff --git a/content/05-more/06-limitations.mdx b/content/05-more/06-limitations.mdx index eba1cf6220..51fca8b753 100644 --- a/content/05-more/06-limitations.mdx +++ b/content/05-more/06-limitations.mdx @@ -12,7 +12,7 @@ This page describes features that are currently not supported by Prisma and are Databases often offer "long-running transactions" as a feature. A transaction generall refers to a sequence of read/write operations that are guaranteed to either succeed or fail as a whole. -Prisma offers a limited set of transactions in the form of [nested writes](). There currently is no plan to provide an API to allow a transaction API for long-running transactions. +Prisma offers a limited set of transactions in the form of [nested writes](../reference/tools-and-interfaces/prisma-client/relation-queries#nested-writes). There currently is no plan to provide an API to allow a transaction API for long-running transactions. ## Records must be uniquely identifiable @@ -23,4 +23,4 @@ Prisma currently only supports models that have at least one unique field or com ## Manual database connection handling -When using Prisma, the database connections are handled on an [engine]()-level. This means they're not exposed to the developer and it's not possible to manually access them. +When using Prisma, the database connections are handled on an [engine](https://github.com/prisma/prisma-engines)-level. This means they're not exposed to the developer and it's not possible to manually access them. diff --git a/content/05-more/07-roadmap.mdx b/content/05-more/07-roadmap.mdx index add23926a3..e332243e8d 100644 --- a/content/05-more/07-roadmap.mdx +++ b/content/05-more/07-roadmap.mdx @@ -16,7 +16,7 @@ Note that the roadmap only lists "larger" features which require a significant e ### Schema migrations with Prisma Migrate -[Prisma Migrate]() is a declarative database migration system. It lets you model your database via the Prisma schema and provides a CLI to map the Prisma schema to your database by generating the required SQL migration statements. +[Prisma Migrate](../reference/tools-and-interfaces/prisma-migrate) is a declarative database migration system. It lets you model your database via the Prisma schema and provides a CLI to map the Prisma schema to your database by generating the required SQL migration statements. Prisma Migrate is already available as an experimental feature. @@ -72,7 +72,7 @@ SQL views are "virtual" tables. As opposed to a "real" table (that was creatd by ### Native database types -Prisma currently only support a limited set of scalar types in the Prisma schema (learn more [here]()). +Prisma currently only support a limited set of scalar types in the Prisma schema). However, you can still make full use of the types that are available in your database by configuring them manually and then [introspecting]() your database schema. Prisma will map the type to the a type that is currently supported in the Prisma schema, but when querying the database the actual database type will be used. From 59297dade8ececf7598d6d0e44a09f9103fbd291 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Sun, 29 Mar 2020 15:13:39 +0200 Subject: [PATCH 52/76] wrap up fixing links --- content/05-more/07-roadmap.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/05-more/07-roadmap.mdx b/content/05-more/07-roadmap.mdx index e332243e8d..5cfd08ac21 100644 --- a/content/05-more/07-roadmap.mdx +++ b/content/05-more/07-roadmap.mdx @@ -74,7 +74,7 @@ SQL views are "virtual" tables. As opposed to a "real" table (that was creatd by Prisma currently only support a limited set of scalar types in the Prisma schema). -However, you can still make full use of the types that are available in your database by configuring them manually and then [introspecting]() your database schema. Prisma will map the type to the a type that is currently supported in the Prisma schema, but when querying the database the actual database type will be used. +However, you can still make full use of the types that are available in your database by configuring them manually and then [introspecting](../reference/tools-and-interfaces/introspection) your database schema. Prisma will map the type to the a type that is currently supported in the Prisma schema, but when querying the database the actual database type will be used. ### Embedded types From 2f340bc358bca96a4d6510e1562e6e57aeae2bc8 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 07:54:25 +0200 Subject: [PATCH 53/76] fix build --- content/index.mdx | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/content/index.mdx b/content/index.mdx index 722a6d1541..4f9d4cb624 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -62,11 +62,6 @@ The **Reference** section contains _technical_ information about Prisma. - [Raw database access](./reference/tools-and-interfaces/prisma-client/raw-database-access) - [Connection management](./reference/tools-and-interfaces/prisma-client/connection-management) - [Advanced usage of generated types](./reference/tools-and-interfaces/prisma-client/advanced-usage-of-generated-types) - - [Logging](./reference/tools-and-interfaces/prisma-client/logging) - [Debugging](./reference/tools-and-interfaces/prisma-client/debugging) - [Error formatting](./reference/tools-and-interfaces/prisma-client/error-formatting) @@ -92,8 +87,6 @@ The **Reference** section contains _technical_ information about Prisma. --- - +- [Roadmap](./more/roadmap) From 74600331bf1e1bca7a11dec67740a066fd9adfba Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:03:06 +0200 Subject: [PATCH 54/76] fix build --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index e38dd633c4..c0c57034c9 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -104,7 +104,6 @@ This command created a new directory called `prisma` with the following contents To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls): - From e1a3eecde041b6674145f3ee351cd90a3840d339 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:11:05 +0200 Subject: [PATCH 55/76] attempt to fix build --- .../02-setup-prisma/01-add-to-an-existing-project.mdx | 2 -- 1 file changed, 2 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index c0b6be5a69..07cd3d6a50 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -584,8 +584,6 @@ ts-node index.ts - - Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: From 109f12a5f13a645a99d7bdc6e4a00176501ac0b4 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:12:20 +0200 Subject: [PATCH 56/76] attempt to fix build --- .../02-setup-prisma/01-add-to-an-existing-project.mdx | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index 07cd3d6a50..28753da711 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -584,16 +584,6 @@ ts-node index.ts - - -Run the code with your current TypeScript setup. If you're using `ts-node`, you can run it like this: - -``` -ts-node index.ts -``` - - - Run the code with this command: From 768d02639b8509f481d1b67c1589549d12e05256 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:22:52 +0200 Subject: [PATCH 57/76] attempt to fix build --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 5 ++++- .../04-unique-constraints-and-indexes/01-postgresql.mdx | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index c0c57034c9..11bdb66adf 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -104,7 +104,6 @@ This command created a new directory called `prisma` with the following contents To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls): - ```prisma @@ -327,10 +326,14 @@ CREATE TABLE Profile ( You can create the tables using any MySQL client of your choice. If you're using `mysql`, you can now create the tables using the following command: + + ``` mysql < schema.sql ``` + + Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: Great, you now created three tables in your database diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx index 3fd80616e8..1c42b13545 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx @@ -357,7 +357,7 @@ node index.js This time, you'll see a similar error message indicating the unique constraint on `firstName` and `lastName` was violated: -```s +``` Invalid `newUser2 = await prisma.anotherUser.create()` invocation in /Users/janedoe/unique-demo/index.js:13:45 From 7adc7011ee8fb377f51fa9d439c1cc8245f96d2f Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:23:34 +0200 Subject: [PATCH 58/76] attempt to fix build --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 11bdb66adf..4a5e5e3ca9 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -326,14 +326,10 @@ CREATE TABLE Profile ( You can create the tables using any MySQL client of your choice. If you're using `mysql`, you can now create the tables using the following command: - - ``` -mysql < schema.sql +mysql > schema.sql ``` - - Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: Great, you now created three tables in your database From 7e4a63c34be1906c5717f669c9011f413553f64b Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:24:16 +0200 Subject: [PATCH 59/76] attempt to fix build --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 4a5e5e3ca9..2d73dba76e 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -327,7 +327,7 @@ CREATE TABLE Profile ( You can create the tables using any MySQL client of your choice. If you're using `mysql`, you can now create the tables using the following command: ``` -mysql > schema.sql +mysql < schema.sql ``` Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: From 0f05de45c48903d7888e404b8f1bc74cb39972ba Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:31:34 +0200 Subject: [PATCH 60/76] attempt to fix build --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 2d73dba76e..77601b7de9 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -330,8 +330,6 @@ You can create the tables using any MySQL client of your choice. If you're using mysql < schema.sql ``` -Similar to before, you need to replace the all-uppercase placeholders with your database credentials, e.g.: - Great, you now created three tables in your database
    Expand for a graphical overview of the tables @@ -588,8 +586,6 @@ npx ts-node index.ts - - Run the code with this command: From 080b3027d29432cbd6a9f85805c4e97559168ca4 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 08:41:57 +0200 Subject: [PATCH 61/76] fix content on landing page --- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 2 +- content/index.mdx | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 77601b7de9..dab37f8db1 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -327,7 +327,7 @@ CREATE TABLE Profile ( You can create the tables using any MySQL client of your choice. If you're using `mysql`, you can now create the tables using the following command: ``` -mysql < schema.sql +mysql <\ schema.sql ``` Great, you now created three tables in your database diff --git a/content/index.mdx b/content/index.mdx index 4f9d4cb624..4ebded80ee 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -18,10 +18,10 @@ Welcome to the Prisma documentation! You can find an overview of the available c The **Getting started** section contains _practical guides_ to help you get started with Prisma. -- [Quickstart](./getting-started/quickstart) +- [Quickstart](./getting-started/quickstart) (5 min) - Setup Prisma - - [Add Prisma to an existing project](./getting-started/setup-prisma/add-to-an-existing-project) - - [Start from scratch (SQL migrations)](./getting-started/setup-prisma/start-from-scratch-sql-migrations) + - [Add Prisma to an existing project](./getting-started/setup-prisma/add-to-an-existing-project) (15 min) + - [Start from scratch (SQL migrations)](./getting-started/setup-prisma/start-from-scratch-sql-migrations) (15 min) --- @@ -53,8 +53,8 @@ The **Reference** section contains _technical_ information about Prisma. - [Models](./reference/tools-and-interfaces/prisma-schema/models) - [Relations](./reference/tools-and-interfaces/prisma-schema/relations) - Prisma Client - - [Generating Prisma Client](./reference/tools-and-interfaces/prisma-client/generating-prisma-client) - [API reference](./reference/tools-and-interfaces/prisma-client/api) + - [Generating Prisma Client](./reference/tools-and-interfaces/prisma-client/generating-prisma-client) - [Configuring the Prisma Client API](./reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api) - [CRUD](./reference/tools-and-interfaces/prisma-client/crud) - [Relation queries](./reference/tools-and-interfaces/prisma-client/relation-queries) @@ -70,7 +70,7 @@ The **Reference** section contains _technical_ information about Prisma. - [Query engine](./reference/tools-and-interfaces/prisma-client/query-engine) - [Module bundlers](./reference/tools-and-interfaces/prisma-client/module-bundlers) - [Database polyfills](./reference/tools-and-interfaces/prisma-client/database-polyfills) - - [Prisma Migrate]./reference/tools-and-interfaces/prisma-migrate() + - [Prisma Migrate](./reference/tools-and-interfaces/prisma-migrate) - [Introspection](./reference/tools-and-interfaces/introspection) - Prisma CLI - [Installation](./reference/tools-and-interfaces/prisma-cli/installation) @@ -119,7 +119,7 @@ The **Guides** section contains _step-by-step tutorials_ on various topics. - Deployment - [Deploying to AWS Lambda](./guides/deployment/deploying-to-aws-lambda) - [Deploying to ZEIT Now](./guides/deployment/deploying-to-zeit-now) - - [Deploying to Netlify](./guides/deployment/deploying-to-netlify) --> + - [Deploying to Netlify](./guides/deployment/deploying-to-netlify) --- From 79707628d6f3ba2d43172d2152bdd92e76e01ae0 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 09:29:38 +0200 Subject: [PATCH 62/76] add meta data --- content/01-getting-started/01-quickstart.mdx | 4 ++-- .../02-setup-prisma/01-add-to-an-existing-project.mdx | 4 ++-- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 4 ++-- content/02-understand-prisma/01-introduction.mdx | 4 ++-- content/02-understand-prisma/02-why-prisma.mdx | 4 ++-- .../02-understand-prisma/03-prisma-in-your-stack/01-rest.md | 4 ++-- .../03-prisma-in-your-stack/02-graphql.md | 4 ++-- content/index.mdx | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/content/01-getting-started/01-quickstart.mdx b/content/01-getting-started/01-quickstart.mdx index 5b68455b92..ef28cca0ea 100644 --- a/content/01-getting-started/01-quickstart.mdx +++ b/content/01-getting-started/01-quickstart.mdx @@ -1,7 +1,7 @@ --- title: 'Quickstart' -metaTitle: '' -metaDescription: '' +metaTitle: 'Quickstart (5 min)' +metaDescription: 'Get started with Prisma in 5 minutes. You will learn how to send queries to a SQL database in a plain Node.js or TypeScript script using Prisma Client.' duration: '5 min' langSwitcher: true --- diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index 28753da711..e14d6ce019 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -1,7 +1,7 @@ --- title: 'Add to an existing project' -metaTitle: '' -metaDescription: '' +metaTitle: 'Add Prisma to an existing project (15 min)' +metaDescription: 'Learn how to add Prisma to an existing Node.js or TypeScript project by connecting it to your database and generating Prisma Client for database access.' dbSwitcher: true langSwitcher: true --- diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index dab37f8db1..1b10878d30 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -1,7 +1,7 @@ --- title: 'Start from scratch' -metaTitle: '' -metaDescription: '' +metaTitle: 'Setup a new projecct with Prisma from scratch (15 min)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your database and generating Prisma Client for database access.' dbSwitcher: true langSwitcher: true --- diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 5f10b1a390..7153a113b0 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -1,7 +1,7 @@ --- title: 'Introduction' -metaTitle: '' -metaDescription: '' +metaTitle: 'Introduction to Prisma' +metaDescription: 'This page gives a high-level overview of what Prisma is and how it works. It's a great starting point for Prisma newcomers!' --- ## Overview diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx index 1db068be9f..8d559666cc 100644 --- a/content/02-understand-prisma/02-why-prisma.mdx +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -1,7 +1,7 @@ --- title: 'Why Prisma?' -metaTitle: '' -metaDescription: '' +metaTitle: 'Why Prisma? (Comparison with SQL query builders & ORMs)' +metaDescription: 'Learn about the motivation for Prisma and how it compares to other Node.js and TypeScript database tools like ORMs and SQL query builders.' --- ## Overview diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md index 42700ceb43..f3367a4a71 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md @@ -1,7 +1,7 @@ --- title: 'REST' -metaTitle: '' -metaDescription: '' +metaTitle: 'Build REST APIs with Prisma' +metaDescription: 'This page gives an overview of the most important things when building REST APIs with Prisma. It shows practical examples and the supported libraries.' --- ## Overview diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md index 5d7f1f9ccc..38370c9342 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/02-graphql.md @@ -1,7 +1,7 @@ --- title: 'GraphQL' -metaTitle: '' -metaDescription: '' +metaTitle: 'Building GraphQL servers with Prisma' +metaDescription: 'This page gives explains how to build GraphQL servers with Prisma. It shows how Prisma fits into the GraphQL ecosystem and provides practical examples.' --- ## Overview diff --git a/content/index.mdx b/content/index.mdx index 4ebded80ee..3574cdc86f 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -1,7 +1,7 @@ --- title: 'Prisma Documentation' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma Documentation (Concepts, Reference & Guides)' +metaDescription: 'Welcome to the Prisma documentation! Get started with Prisma and connect it to your database, read about the main Prisma concepts and explore the API reference.' --- ## Overview From 5c8ea9f1e0444103917c50450b93727e6c843992 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 10:42:42 +0200 Subject: [PATCH 63/76] add meta data --- .../03-prisma-in-your-stack/01-rest.md | 2 +- .../03-prisma-in-your-stack/03-is-prisma-an-orm.mdx | 4 ++-- content/02-understand-prisma/04-data-modeling.mdx | 4 ++-- content/02-understand-prisma/05-under-the-hood.mdx | 4 ++-- .../01-prisma-schema/01-prisma-schema-file.mdx | 4 ++-- .../01-prisma-schema/02-data-sources.mdx | 10 +++++----- .../01-prisma-schema/03-generators.mdx | 6 +++--- .../01-prisma-schema/04-data-model.mdx | 4 ++-- .../01-prisma-schema/05-models.mdx | 4 ++-- .../01-prisma-schema/06-relations.mdx | 4 ++-- .../02-prisma-client/01-api.mdx | 4 ++-- .../02-prisma-client/02-generating-prisma-client.mdx | 4 ++-- .../03-configuring-the-prisma-client-api.mdx | 4 ++-- .../02-prisma-client/04-crud.mdx | 4 ++-- .../02-prisma-client/05-relation-queries.mdx | 4 ++-- .../02-prisma-client/06-field-selection.mdx | 4 ++-- .../02-prisma-client/07-raw-database-access.mdx | 4 ++-- .../02-prisma-client/08-connection-management.mdx | 4 ++-- .../09-advanced-usage-of-generated-types.mdx | 4 ++-- .../02-prisma-client/13-logging.mdx | 4 ++-- .../02-prisma-client/14-debugging.mdx | 4 ++-- .../02-prisma-client/15-error-formatting.mdx | 4 ++-- .../02-prisma-client/16-transactions.mdx | 4 ++-- .../02-prisma-client/17-deployment.mdx | 4 ++-- .../02-prisma-client/18-query-engine.mdx | 4 ++-- .../02-prisma-client/19-module-bundlers.mdx | 4 ++-- .../02-prisma-client/20-database-polyfills.mdx | 4 ++-- .../01-tools-and-interfaces/03-prisma-migrate.mdx | 4 ++-- .../01-tools-and-interfaces/04-introspection.mdx | 4 ++-- .../05-prisma-cli/01-installation.mdx | 2 +- .../05-prisma-cli/02-command-reference.mdx | 4 ++-- 31 files changed, 64 insertions(+), 64 deletions(-) diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md index f3367a4a71..e0daa8b6f9 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md @@ -1,6 +1,6 @@ --- title: 'REST' -metaTitle: 'Build REST APIs with Prisma' +metaTitle: 'Building REST APIs with Prisma' metaDescription: 'This page gives an overview of the most important things when building REST APIs with Prisma. It shows practical examples and the supported libraries.' --- diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx b/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx index 016c6ec8ef..150db7e3ee 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx +++ b/content/02-understand-prisma/03-prisma-in-your-stack/03-is-prisma-an-orm.mdx @@ -1,7 +1,7 @@ --- title: 'Is Prisma an ORM?' -metaTitle: '' -metaDescription: '' +metaTitle: 'Is Prisma an ORM?' +metaDescription: "Learn why Prisma is not an ORM. It shares similar goals with ORMs and wants to make working with databases easy, but it does not map classes to tables as ORMs do." --- ## Overview diff --git a/content/02-understand-prisma/04-data-modeling.mdx b/content/02-understand-prisma/04-data-modeling.mdx index f2aa4036a6..999e76778a 100644 --- a/content/02-understand-prisma/04-data-modeling.mdx +++ b/content/02-understand-prisma/04-data-modeling.mdx @@ -1,7 +1,7 @@ --- title: 'Data modeling' -metaTitle: '' -metaDescription: '' +metaTitle: 'Data modeling with Prisma' +metaDescription: 'Learn how data modeling with Prisma differs from data modeling with SQL or ORMs. Prisma uses a declarative data modeling language to describe a database schema.' --- ## What is data modeling? diff --git a/content/02-understand-prisma/05-under-the-hood.mdx b/content/02-understand-prisma/05-under-the-hood.mdx index a8d5c66122..6199cbea29 100644 --- a/content/02-understand-prisma/05-under-the-hood.mdx +++ b/content/02-understand-prisma/05-under-the-hood.mdx @@ -1,7 +1,7 @@ --- title: 'Under the hood' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma under the hood' +metaDescription: 'Learn about Prisma internals and how it works "under the hood". Prisma tools are based on an engine-layer which manages the communication with the database.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx index 1b1a97793a..92129ace02 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/01-prisma-schema-file.mdx @@ -1,7 +1,7 @@ --- title: 'Prisma schema file' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma schema file (Reference)' +metaDescription: 'The Prisma schema is the main configuration file when using Prisma. It is typically called schema.prisma and contains your database connection and data model.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/02-data-sources.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/02-data-sources.mdx index c854b185e6..e07cfab304 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/02-data-sources.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/02-data-sources.mdx @@ -1,7 +1,7 @@ --- title: 'Data sources' -metaTitle: '' -metaDescription: '' +metaTitle: 'Data sources (Reference)' +metaDescription: 'Data sources enable Prisma to connect to your database. This page explains how to configure data sources in your Prisma schema.' --- ## Overview @@ -37,7 +37,7 @@ datasource postgresql { } ``` -Learn more about PostgreSQL connection strings [here](). +Learn more about PostgreSQL connection strings [here](../../database-connectors/postgresql). **Specify a MySQL data source** @@ -56,7 +56,7 @@ datasource mysql { } ``` -Learn more about PostgreSQL connection strings [here](). +Learn more about PostgreSQL connection strings [here](../../database-connectors/mysql). **Specify a SQLite data source** @@ -69,7 +69,7 @@ datasource sqlite { } ``` -Learn more about SQLite connection strings [here](). +Learn more about SQLite connection strings [here](../../database-connectors/sqlite). **Specify a PostgreSQL data source via an environment variable** diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx index a71820fe23..db0b5958cf 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/03-generators.mdx @@ -1,12 +1,12 @@ --- title: 'Generators' -metaTitle: '' -metaDescription: '' +metaTitle: 'Generators (Reference)' +metaDescription: 'Generators in your Prisma schema specify what assets are generated when the `prisma generate` command is invoked. This page explains how to configure generators.' --- ## Overview -A generator can be specified via the `generator` block in the Prisma schema. +A generator can be specified via the `generator` block in the Prisma schema. Generators in your Prisma schema specify what assets are generated when the `prisma generate` command is invoked. ## Fields diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx index ede702a3a0..3cb068b33b 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/04-data-model.mdx @@ -1,7 +1,7 @@ --- title: 'Data model' -metaTitle: '' -metaDescription: '' +metaTitle: 'Data model (Reference)' +metaDescription: 'Learn about the concepts for building your data model with Prisma: Models, scalar types, enums, attributes, functions, IDs, default values and more.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx index a2fd440092..4ebf84434b 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx @@ -1,7 +1,7 @@ --- title: 'Models' -metaTitle: '' -metaDescription: '' +metaTitle: 'Models (Reference)' +metaDescription: 'Learn about defining your application models with Prisma. Models represent tables in the database and serve as foundation for generated Prisma Client queries.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx index 1b8eb7ae8a..31a924abc3 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/06-relations.mdx @@ -1,7 +1,7 @@ --- title: 'Relations' -metaTitle: '' -metaDescription: '' +metaTitle: 'Relations (Reference)' +metaDescription: 'A relation is a connection between two models in the Prisma schema. This page explains how you can define 1-1, 1-n and m-n relations in Prisma.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx index f7d95dd884..95d514be68 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx @@ -1,7 +1,7 @@ --- title: 'API reference' -metaTitle: '' -metaDescription: '' +metaTitle: 'API Reference' +metaDescription: "This page gives an overview of the Prisma Client API and links to more detailled explanations. It's a great starting point for exploring Prisma Client." --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx index a8f2700263..01013ce562 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/02-generating-prisma-client.mdx @@ -1,7 +1,7 @@ --- title: 'Generating Prisma Client' -metaTitle: '' -metaDescription: '' +metaTitle: 'Generating Prisma Client (Reference)' +metaDescription: 'This page explains how to generate Prisma Client. It also provides additional context on the generated npm module, typical workflows and Node.js configuration.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx index 0b50031ce8..8e5b27b2c7 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/03-configuring-the-prisma-client-api.mdx @@ -1,7 +1,7 @@ --- title: 'Configuring the Prisma Client API' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configuring the Prisma Client API (Reference)' +metaDescription: 'Learn how you can decouple the naming of Prisma models from database tables to improve the ergonomics of the generated Prisma Client API.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx index 872aa2fff3..680fc16aff 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/04-crud.mdx @@ -1,7 +1,7 @@ --- title: 'CRUD' -metaTitle: '' -metaDescription: '' +metaTitle: 'CRUD (Reference)' +metaDescription: 'This page provides a detailled reference of the auto-generated CRUD queries that are exposed in the Prisma Client API, such as findOne, findMany, create, ...' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx index 66861d4536..49d00d08c0 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/05-relation-queries.mdx @@ -1,7 +1,7 @@ --- title: 'Relation queries' -metaTitle: '' -metaDescription: '' +metaTitle: 'Relation queries (Reference)' +metaDescription: 'Prisma Client provides convenient queries for working with relations, such as a fluent API, nested writes (transactions), nested reads and relation filters.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx index 8260f51b8f..642c16d65e 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx @@ -1,7 +1,7 @@ --- title: 'Field selection' -metaTitle: '' -metaDescription: '' +metaTitle: 'Field selection (Reference)' +metaDescription: "This page explains how to select only a subset of a model's fields and/or include relations ("eager loading") in a Prisma Client query." --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx index 8027e4310a..ac2cd41a33 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/07-raw-database-access.mdx @@ -1,7 +1,7 @@ --- title: 'Raw database access' -metaTitle: '' -metaDescription: '' +metaTitle: 'Raw database access (Reference' +metaDescription: 'Learn how you can send raw SQL queries to your database using the raw() method from the Prisma Client API.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx index ba8902edac..7224c68c0f 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/08-connection-management.mdx @@ -1,7 +1,7 @@ --- title: 'Connection management' -metaTitle: '' -metaDescription: '' +metaTitle: 'Connection management (Reference)' +metaDescription: 'This page explains how database connections are handled with Prisma Client and how to manually connect and disconnect your database.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx index aa93e200b4..2e8fbddde0 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/09-advanced-usage-of-generated-types.mdx @@ -1,7 +1,7 @@ --- title: 'Advanced usage of generated types' -metaTitle: '' -metaDescription: '' +metaTitle: 'Advanced usage of generated types (Reference)' +metaDescription: 'Prisma Client provides full type safety for queries, even for partial queries or included relations. This page explains how to leverage the generated types.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx index 5a6fcf033b..db26722b4b 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/13-logging.mdx @@ -1,7 +1,7 @@ --- title: 'Logging' -metaTitle: '' -metaDescription: '' +metaTitle: 'Logging (Reference)' +metaDescription: 'Learn how to configure Prismaa Client to log the raw SQL queries it sends to the database and other information.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx index 1d1770ae5d..320a3cac49 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/14-debugging.mdx @@ -1,7 +1,7 @@ --- title: 'Debugging' -metaTitle: '' -metaDescription: '' +metaTitle: 'Debugging (Reference)' +metaDescription: 'This page explains how to enable debugging output for Prisma Client by setting the `DEBUG` environment variable.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx index 187d182ead..b4d9863eb3 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/15-error-formatting.mdx @@ -1,7 +1,7 @@ --- title: 'Error formatting' -metaTitle: '' -metaDescription: '' +metaTitle: 'Error formatting (Reference)' +metaDescription: 'This page expains how to configure the formatting of errors when using Prisma Client.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx index 1d0930142c..2c74acd0ff 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/16-transactions.mdx @@ -1,7 +1,7 @@ --- title: 'Transactions' -metaTitle: '' -metaDescription: '' +metaTitle: 'Transactions (Reference)' +metaDescription: 'This page explains the current transactions API of Prisma Client.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx index a51939d812..c81ca5dd30 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/17-deployment.mdx @@ -1,7 +1,7 @@ --- title: 'Deployment' -metaTitle: '' -metaDescription: '' +metaTitle: 'Deployment (Reference)' +metaDescription: 'Learn the basics about deploying Node.js and TypeScript applications that are using Prisma Client.' --- Coming ๐Ÿ”œ diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx index 02ad6cd477..dde0d7e64d 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx @@ -1,7 +1,7 @@ --- title: 'Query engine' -metaTitle: '' -metaDescription: '' +metaTitle: 'Query engine (Reference)' +metaDescription: "Prisma's query engine manages the comunication with the database when using Prisma Client. Learn how it works on this page." --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx index 910244e8d7..e6aa78b0b4 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/19-module-bundlers.mdx @@ -1,7 +1,7 @@ --- title: 'Module bundlers' -metaTitle: '' -metaDescription: '' +metaTitle: 'Module bundlers (Reference)' +metaDescription: 'This page gives an overview of the most important things to be aware of when using a module bundler to bundle an application that uses Prisma Client.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx index c16d521db3..bc05afc293 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/20-database-polyfills.mdx @@ -1,7 +1,7 @@ --- title: 'Database polyfills' -metaTitle: '' -metaDescription: '' +metaTitle: 'Database polyfills (Reference)' +metaDescription: 'Prisma Client provides features that are not achievable with relational databases. These features are referred to as "polyfills" and explained on this page.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx index c68c58215b..4f744620c9 100644 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx +++ b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx @@ -1,7 +1,7 @@ --- title: 'Prisma Migrate' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma Migrate (Reference)' +metaDescription: 'Prisma Migrate is a declarative data modeling and schema migration tool that is available via the Prisma CLI.' experimental: true --- diff --git a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx index c27a5a9f12..2e16f56416 100644 --- a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx +++ b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx @@ -1,7 +1,7 @@ --- title: 'Introspection' -metaTitle: '' -metaDescription: '' +metaTitle: 'Introspection (Reference)' +metaDescription: 'Learn how you can introspect your database to generate a data model into your Prisma schema.' --- ## Overview diff --git a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx index c3b09f8f63..3b14de7281 100644 --- a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx +++ b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx @@ -1,6 +1,6 @@ --- title: 'Installation' -metaTitle: '' +metaTitle: 'Prisma CLI Installation (Reference)' metaDescription: '' --- diff --git a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/02-command-reference.mdx b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/02-command-reference.mdx index c1bb991e4e..aaa2c7d49f 100644 --- a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/02-command-reference.mdx +++ b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/02-command-reference.mdx @@ -1,7 +1,7 @@ --- title: 'CLI command reference' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma CLI Command Reference' +metaDescription: 'This page gives an overview of all available Prisma CLI commands, explains their options and shows numerous usage examples.' --- ## Overview From e35217f10b91312e95de7b664a047e0817e35336 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 10:56:02 +0200 Subject: [PATCH 64/76] add meta data --- .../01-prisma-schema/05-models.mdx | 2 +- .../01-tools-and-interfaces/02-prisma-client/01-api.mdx | 2 +- .../{01-features.mdx => 01-database-features.mdx} | 6 +++--- .../02-database-connectors/02-connection-urls.mdx | 4 ++-- .../03-reference/02-database-connectors/03-postgresql.mdx | 6 +++--- content/03-reference/02-database-connectors/04-mysql.mdx | 6 +++--- content/03-reference/02-database-connectors/05-sqlite.mdx | 8 ++++---- content/03-reference/03-more/01-editor-setup.mdx | 6 +++--- 8 files changed, 20 insertions(+), 20 deletions(-) rename content/03-reference/02-database-connectors/{01-features.mdx => 01-database-features.mdx} (98%) diff --git a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx index 4ebf84434b..b9e8e6ffcd 100644 --- a/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx +++ b/content/03-reference/01-tools-and-interfaces/01-prisma-schema/05-models.mdx @@ -192,7 +192,7 @@ const allUsers = await prisma.user.findMany(); Prisma Client not only provides a query API for models, it also generates type definitions that reflect your model structures. These are part of the generated [`@prisma/client`](../prisma-client/generating-prisma-client#the-prisma-client-npm-module) node module in a file called `index.d.ts`. -When using TypeScript, these type definitions ensure that all your database queries are entirely type safe and validated at compile-time (even partial queries using [`select`](..//prisma-client/field-selection#select) or [`include`](..//prisma-client/field-selection#include)). +When using TypeScript, these type definitions ensure that all your database queries are entirely type safe and validated at compile-time (even partial queries using [`select`](../prisma-client/field-selection#select) or [`include`](../prisma-client/field-selection#include)). Even when using plain JavaScript, the type definitions are still included in the generated `@prisma/client` node module, enabling features like [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)/autocompletion in your editor. diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx index 95d514be68..7b2cb51fc9 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx @@ -17,7 +17,7 @@ The setup instruction below provide a high-level overview of the steps needed to ### 1. Prerequisites -In order to set up Prisma Client, you need a [Prisma schema file](..//prisma-schema/prisma-schema-file) with your database connection, the Prisma Client generator and at least one model: +In order to set up Prisma Client, you need a [Prisma schema file](../prisma-schema/prisma-schema-file) with your database connection, the Prisma Client generator and at least one model: ```prisma datasource postgresql { diff --git a/content/03-reference/02-database-connectors/01-features.mdx b/content/03-reference/02-database-connectors/01-database-features.mdx similarity index 98% rename from content/03-reference/02-database-connectors/01-features.mdx rename to content/03-reference/02-database-connectors/01-database-features.mdx index 4bdd966686..31ea28f582 100644 --- a/content/03-reference/02-database-connectors/01-features.mdx +++ b/content/03-reference/02-database-connectors/01-database-features.mdx @@ -1,7 +1,7 @@ --- -title: 'Features' -metaTitle: '' -metaDescription: '' +title: 'Database features' +metaTitle: 'Database features (Reference)' +metaDescription: 'Learn which database features are supported in Prisma and how they map to the different Prisma tools.' --- ## Overview diff --git a/content/03-reference/02-database-connectors/02-connection-urls.mdx b/content/03-reference/02-database-connectors/02-connection-urls.mdx index 05837a3e4b..1edf13cded 100644 --- a/content/03-reference/02-database-connectors/02-connection-urls.mdx +++ b/content/03-reference/02-database-connectors/02-connection-urls.mdx @@ -1,7 +1,7 @@ --- title: 'Connection URLs' -metaTitle: '' -metaDescription: '' +metaTitle: 'Connection URLs (Reference)' +metaDescription: 'Learn about the format and syntax Prisma uses for defining database connection URLs for PostgreSQL, MySQL and SQLite.' --- ## Overview diff --git a/content/03-reference/02-database-connectors/03-postgresql.mdx b/content/03-reference/02-database-connectors/03-postgresql.mdx index a957559548..0524426bb3 100644 --- a/content/03-reference/02-database-connectors/03-postgresql.mdx +++ b/content/03-reference/02-database-connectors/03-postgresql.mdx @@ -1,7 +1,7 @@ --- title: 'PostgreSQL' -metaTitle: '' -metaDescription: '' +metaTitle: 'PostgreSQL database connector (Reference)' +metaDescription: 'This page explains how Prisma can connect to a PostgreSQL database using the PostgreSQL database connector.' --- ## Overview @@ -120,7 +120,7 @@ Note that `localhost` is required, the value itself is ignored and can be anythi ## Type mapping between PostgreSQL to Prisma schema -The PostgreSQL connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the Prisma [data model](../prisma-schema/data-model) as follows to native column types: +The PostgreSQL connector maps the [scalar types](../prisma-schema/data-model#scalar-types) from the Prisma [data model](../prisma-schema/data-model) as follows to native column types: ### Prisma Migrate diff --git a/content/03-reference/02-database-connectors/04-mysql.mdx b/content/03-reference/02-database-connectors/04-mysql.mdx index ca94884028..29dfc7deb6 100644 --- a/content/03-reference/02-database-connectors/04-mysql.mdx +++ b/content/03-reference/02-database-connectors/04-mysql.mdx @@ -1,7 +1,7 @@ --- title: 'MySQL' -metaTitle: '' -metaDescription: '' +metaTitle: 'MySQL database connector (Reference)' +metaDescription: 'This page explains how Prisma can connect to a MySQL database using the MySQL database connector.' --- ## Overview @@ -119,7 +119,7 @@ Note that `localhost` is required, the value itself is ignored and can be anythi ## Type mapping between MySQL to Prisma schema -The MySQL connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the Prisma [data model](..//prisma-schema/data-model) as follows to native column types: +The MySQL connector maps the [scalar types](../prisma-schema/data-model#scalar-types) from the Prisma [data model](../prisma-schema/data-model) as follows to native column types: ### Prisma Migrate diff --git a/content/03-reference/02-database-connectors/05-sqlite.mdx b/content/03-reference/02-database-connectors/05-sqlite.mdx index dad055c3ed..2ffb48dec0 100644 --- a/content/03-reference/02-database-connectors/05-sqlite.mdx +++ b/content/03-reference/02-database-connectors/05-sqlite.mdx @@ -1,7 +1,7 @@ --- title: 'SQLite' -metaTitle: '' -metaDescription: '' +metaTitle: 'SQLite database connector (Reference)' +metaDescription: 'This page explains how Prisma can connect to a SQLite database using the SQLite database connector.' --- ## Overview @@ -10,7 +10,7 @@ The SQLite data source connector connects Prisma to a [SQLite](https://www.sqlit ## Example -To connect to a SQLite database file, you need to configure a [`datasource`]() block in your [schema file](): +To connect to a SQLite database file, you need to configure a [`datasource`](../prisma-schema/data-sources) block in your [schema file](../prisma-schema/prisma-schema-file): ```prisma datasource sqlite { @@ -26,7 +26,7 @@ The fields passed to the `datasource` block are: ## Data model mapping -The SQLite connector maps the [scalar types](..//prisma-schema/data-model#scalar-types) from the [data model](..//prisma-schema/data-model) to native column types as follows: +The SQLite connector maps the [scalar types](../prisma-schema/data-model#scalar-types) from the [data model](../prisma-schema/data-model) to native column types as follows: | Data model | SQLite | | ---------- | --------- | diff --git a/content/03-reference/03-more/01-editor-setup.mdx b/content/03-reference/03-more/01-editor-setup.mdx index 60bbab76b5..4372f2d909 100644 --- a/content/03-reference/03-more/01-editor-setup.mdx +++ b/content/03-reference/03-more/01-editor-setup.mdx @@ -1,6 +1,6 @@ --- title: 'Editor setup' -metaTitle: '' +metaTitle: 'Editor setup' metaDescription: '' --- @@ -8,8 +8,8 @@ metaDescription: '' This page describes how you can configure your editor for an optimal developer experience when using Prisma. -If you don't see you editor here, please [open a feature request]() and ask for dedicated support for your editor (e.g. for syntax highlighting and auto-formatting). +If you don't see you editor here, please [open a feature request](https://github.com/prisma/prisma2/issues/new?assignees=&labels=&template=feature_request.md&title=) and ask for dedicated support for your editor (e.g. for syntax highlighting and auto-formatting). ## VS Code -You can install the [Prisma VS Code extension](). +You can install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma). From 1d6c173b4c248e26863ea485cfb9cb32e4f5c07b Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 10:58:58 +0200 Subject: [PATCH 65/76] add meta data --- .../05-prisma-cli/01-installation.mdx | 8 ++++---- content/03-reference/03-more/01-editor-setup.mdx | 4 ++-- content/03-reference/03-more/02-telemetry.mdx | 4 ++-- .../04-guides/02-deployment/04-deploying-to-netlify.mdx | 2 +- content/05-more/03-supported-databases.mdx | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx index 3b14de7281..50a81691b5 100644 --- a/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx +++ b/content/03-reference/01-tools-and-interfaces/05-prisma-cli/01-installation.mdx @@ -11,7 +11,7 @@ The Prisma CLI is available as an [npm package](). It is **recommended to instal ### Local installation (recommended) -The Prisma 2 CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. +The Prisma CLI is typically installed as a **development dependency**, that's why the `--save-dev` (npm) and `--dev` (Yarn) options are used in the commands below. #### npm @@ -55,7 +55,7 @@ yarn prisma generate ### Global installation (not recommended) -While it is recommended to [locally install](#local-installation-recommended) the Prisma 2 CLI, you can also install it globally on your machine. +While it is recommended to [locally install](#local-installation-recommended) the Prisma CLI, you can also install it globally on your machine. > **Warning**: If you have several Prisma projects on your machine, a global installation can lead to version conflicts between these projects. @@ -101,11 +101,11 @@ prisma generate ### The `postinstall` hook -When installing Prisma 2 CLI, a [`postinstall`](https://github.com/prisma/prisma/blob/master/cli/sdk/package.json#L13) hook is being executed. It downloads Prisma 2's query and migration [engine binaries](https://github.com/prisma/prisma-engine). The query engine contains the [Prisma schema](../prisma-schema/prisma-schema-file) parser which is used by the `prisma init` and the `prisma generate` commands. The migration engine is used by all `prisma migrate` commands. +When installing Prisma CLI, a [`postinstall`](https://github.com/prisma/prisma/blob/master/cli/sdk/package.json#L13) hook is being executed. It downloads Prisma's query and migration [engine binaries](https://github.com/prisma/prisma-engine). The query engine contains the [Prisma schema](../prisma-schema/prisma-schema-file) parser which is used by the `prisma init` and the `prisma generate` commands. The migration engine is used by all `prisma migrate` commands. ## Using a HTTP proxy for the CLI -Prisma 2 CLI supports [custom HTTP proxies](https://github.com/prisma/prisma/issues/506). This is particularly relevant when being behind a corporate firewall. +Prisma CLI supports [custom HTTP proxies](https://github.com/prisma/prisma/issues/506). This is particularly relevant when being behind a corporate firewall. To activate the proxy, provide the environment variables `HTTP_PROXY` and/or `HTTPS_PROXY`. The behavior is very similar to how the [`npm` CLI handles this](https://docs.npmjs.com/misc/config#https-proxy). diff --git a/content/03-reference/03-more/01-editor-setup.mdx b/content/03-reference/03-more/01-editor-setup.mdx index 4372f2d909..9c12e2a307 100644 --- a/content/03-reference/03-more/01-editor-setup.mdx +++ b/content/03-reference/03-more/01-editor-setup.mdx @@ -1,7 +1,7 @@ --- title: 'Editor setup' -metaTitle: 'Editor setup' -metaDescription: '' +metaTitle: 'Editor and IDE setup (Reference)' +metaDescription: 'Learn how to configure your editor and IDEs for an optimal developer experience with Prisma.' --- ## Overview diff --git a/content/03-reference/03-more/02-telemetry.mdx b/content/03-reference/03-more/02-telemetry.mdx index f2822f2a18..9b9ee92458 100644 --- a/content/03-reference/03-more/02-telemetry.mdx +++ b/content/03-reference/03-more/02-telemetry.mdx @@ -1,7 +1,7 @@ --- title: 'Telemetry' -metaTitle: '' -metaDescription: '' +metaTitle: 'Telemetry (Reference)' +metaDescription: 'Thiis page explains how Prisma uses telemetry features to improve the Prisma developer experience.' --- ## Overview diff --git a/content/04-guides/02-deployment/04-deploying-to-netlify.mdx b/content/04-guides/02-deployment/04-deploying-to-netlify.mdx index 2c36afa277..c240920567 100644 --- a/content/04-guides/02-deployment/04-deploying-to-netlify.mdx +++ b/content/04-guides/02-deployment/04-deploying-to-netlify.mdx @@ -1,7 +1,7 @@ --- title: 'Deploying to Netlify' metaTitle: '' -metaDescription: 'A guide to deploying Prisma 2 to Netlify' +metaDescription: 'A guide to deploying Prisma to Netlify' --- In this guide, you will set up and deploy a serverless Node.js application to [Netlify](https://www.netlify.com/). The application will expose a REST API and use Prisma Client to handle fetching, creating, and deleting records from a database. diff --git a/content/05-more/03-supported-databases.mdx b/content/05-more/03-supported-databases.mdx index ee17f391c2..f65366c4e6 100644 --- a/content/05-more/03-supported-databases.mdx +++ b/content/05-more/03-supported-databases.mdx @@ -6,7 +6,7 @@ metaDescription: '' ## Overview -Prisma 2 currently supports the following databases: +Prisma currently supports the following databases: | Database | Version | | ---------- | ------- | @@ -19,4 +19,4 @@ Prisma 2 currently supports the following databases: | MariaDB | 10 | | SQLite | 3.28.0 | -Note that a fixed version of SQLite is shipped with every Prisma 2 release. +Note that a fixed version of SQLite is shipped with every Prisma release. From 230e672684f18e852853ea2d727c1a656b7e419f Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 11:12:49 +0200 Subject: [PATCH 66/76] add meta data --- .../01-setting-up-a-database/01-postgresql.mdx | 6 ++++-- .../01-setting-up-a-database/02-mysql.mdx | 6 ++++-- .../01-setting-up-a-database/03-sqlite.mdx | 6 ++++-- .../02-import-and-export-data/01-postgresql.mdx | 6 +++--- .../02-import-and-export-data/02-mysql.mdx | 4 ++-- .../02-import-and-export-data/03-sqlite.mdx | 4 ++-- .../04-unique-constraints-and-indexes/01-postgresql.mdx | 4 ++-- .../04-unique-constraints-and-indexes/02-mysql.mdx | 4 ++-- .../04-unique-constraints-and-indexes/03-sqlite.mdx | 5 +++-- .../01-database-workflows/05-foreign-keys/01-postgresql.mdx | 4 ++-- .../01-database-workflows/05-foreign-keys/02-mysql.mdx | 4 ++-- .../01-database-workflows/05-foreign-keys/03-sqlite.mdx | 4 ++-- .../06-cascading-deletes/01-postgresql.mdx | 4 ++-- .../01-database-workflows/06-cascading-deletes/02-mysql.mdx | 4 ++-- .../06-cascading-deletes/03-sqlite.mdx | 4 ++-- .../07-data-validation/01-postgresql.mdx | 4 ++-- .../04-guides/02-deployment/01-deploying-to-zeit-now.mdx | 4 ++-- .../04-guides/02-deployment/02-deploying-to-aws-lambda.mdx | 4 ++-- content/04-guides/02-deployment/04-deploying-to-netlify.mdx | 6 ++++-- 19 files changed, 48 insertions(+), 39 deletions(-) diff --git a/content/04-guides/01-database-workflows/01-setting-up-a-database/01-postgresql.mdx b/content/04-guides/01-database-workflows/01-setting-up-a-database/01-postgresql.mdx index 92e65326e8..35344e5d64 100644 --- a/content/04-guides/01-database-workflows/01-setting-up-a-database/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/01-setting-up-a-database/01-postgresql.mdx @@ -1,9 +1,11 @@ --- title: 'Setting up a database (PostgreSQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Set up a PostgreSQL database on Windows, Mac OS or Linux' +metaDescription: 'Learn how to set up a PostgreSQL database on Windows, Mac OS or Linux by following the step-by-step instructions in this practical guide.' --- +## Overview + This page explains how to install and configure a [PostgreSQL database server](https://www.postgresql.org/docs/current/intro-whatis.html) and the [`psql` command line client](https://www.postgresql.org/docs/current/app-psql.html). This guide will cover how to install and set up these components on your computer for local access. This guide will cover the following platforms: diff --git a/content/04-guides/01-database-workflows/01-setting-up-a-database/02-mysql.mdx b/content/04-guides/01-database-workflows/01-setting-up-a-database/02-mysql.mdx index 38b9a90c03..556c86007d 100644 --- a/content/04-guides/01-database-workflows/01-setting-up-a-database/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/01-setting-up-a-database/02-mysql.mdx @@ -1,9 +1,11 @@ --- title: 'Setting up a database (MySQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Set up a MySQL database on Windows, Mac OS or Linux' +metaDescription: 'Learn how to set up a MySQL database on Windows, Mac OS or Linux by following the step-by-step instructions in this practical guide.' --- +## Overview + This page explains how to install and configure the [MySQL database server](https://dev.mysql.com/doc/refman/8.0/en/mysqld.html), and the [`mysql` command line client](https://dev.mysql.com/doc/refman/8.0/en/mysql.html). This guide will cover how to install and set up these components on your computer for local access. This guide will cover the following platforms: diff --git a/content/04-guides/01-database-workflows/01-setting-up-a-database/03-sqlite.mdx b/content/04-guides/01-database-workflows/01-setting-up-a-database/03-sqlite.mdx index d64d98fce5..9da9a5ed3a 100644 --- a/content/04-guides/01-database-workflows/01-setting-up-a-database/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/01-setting-up-a-database/03-sqlite.mdx @@ -1,9 +1,11 @@ --- title: 'Setting up a database (SQLite)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Set up a SQLite database on Windows, Mac OS or Linux' +metaDescription: 'Learn how to set up a SQLite database on Windows, Mac OS or Linux by following the step-by-step instructions in this practical guide.' --- +## Overview + This page explains how to set up [SQLite](https://www.sqlite.org/index.html) on your computer. This guide will cover the following platforms: diff --git a/content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx index 8bbd84cd25..eded12708b 100644 --- a/content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/02-import-and-export-data/01-postgresql.mdx @@ -1,7 +1,7 @@ --- -title: 'Importing and exporting data (PostgreSQL)' -metaTitle: '' -metaDescription: '' +title: 'Import and export data (PostgreSQL)' +metaTitle: 'Import and export data with a PostgreSQL database' +metaDescription: 'Learn how to import and export data with a PostgreSQL database.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx index 2b13d14c4a..8f46f3679a 100644 --- a/content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/02-import-and-export-data/02-mysql.mdx @@ -1,7 +1,7 @@ --- title: 'Importing and exporting data (MySQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Import and export data with a MySQL database' +metaDescription: 'Learn how to import and export data with a MySQL database.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx b/content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx index 838f74308d..1e4568ba15 100644 --- a/content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/02-import-and-export-data/03-sqlite.mdx @@ -1,7 +1,7 @@ --- title: 'Importing and exporting data (SQLite)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Import and export data with a SQLite database' +metaDescription: 'Learn how to import and export data with a SQLite database.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx index ac3bd552c8..51c769fa58 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/01-postgresql.mdx @@ -1,7 +1,7 @@ --- title: 'Unique constraints and indexes (PostgreSQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Unique constraints and indexes with Prisma and PostgreSQL' +metaDescription: 'Learn how to configure unique constraints and indexes with Prisma and PostgreSQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx index a8a1e1df33..7df29539b9 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/02-mysql.mdx @@ -1,7 +1,7 @@ --- title: 'Unique constraints and indexes (MySQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Unique constraints and indexes with Prisma and MySQL' +metaDescription: 'Learn how to configure unique constraints and indexes with Prisma and MySQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx index 31a2226124..43c946c145 100644 --- a/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/04-unique-constraints-and-indexes/03-sqlite.mdx @@ -1,7 +1,8 @@ --- title: 'Unique constraints and indexes (SQLite)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Unique constraints and indexes with Prisma and SQLite' +metaDescription: 'Learn how to configure unique constraints and indexes with Prisma and SQLite by following the step-by-step instructions in this practical guide.' + --- ## Overview diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx index 741ca99ecd..e74ab9eb94 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/01-postgresql.mdx @@ -1,7 +1,7 @@ --- title: 'Foreign keys / Relations (PostgreSQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure foreign keys with Prisma and PostgreSQL' +metaDescription: 'Learn how to configure foreign keys with Prisma and PostgreSQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx index af06fb92d4..e5a9275095 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/02-mysql.mdx @@ -1,7 +1,7 @@ --- title: 'Foreign keys / Relations (MySQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure foreign keys with Prisma and MySQL' +metaDescription: 'Learn how to configure foreign keys with Prisma and MySQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx b/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx index 3a1e2a86d8..6ecea401f1 100644 --- a/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/05-foreign-keys/03-sqlite.mdx @@ -1,7 +1,7 @@ --- title: 'Foreign keys / Relations (SQLite)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure foreign keys with Prisma and SQLite' +metaDescription: 'Learn how to configure foreign keys with Prisma and SQLite by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx b/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx index c8df264ac7..ad759cff95 100644 --- a/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/06-cascading-deletes/01-postgresql.mdx @@ -1,7 +1,7 @@ --- title: 'Cascading deletes (PostgreSQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure cascading deletes with Prisma and PostgreSQL' +metaDescription: 'Learn how to configure cascading deletes with Prisma and PostgreSQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/06-cascading-deletes/02-mysql.mdx b/content/04-guides/01-database-workflows/06-cascading-deletes/02-mysql.mdx index f94d17ed0d..cde0265bde 100644 --- a/content/04-guides/01-database-workflows/06-cascading-deletes/02-mysql.mdx +++ b/content/04-guides/01-database-workflows/06-cascading-deletes/02-mysql.mdx @@ -1,7 +1,7 @@ --- title: 'Cascading deletes (MySQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure cascading deletes with Prisma and MySQL' +metaDescription: 'Learn how to configure cascading deletes with Prisma and MySQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/06-cascading-deletes/03-sqlite.mdx b/content/04-guides/01-database-workflows/06-cascading-deletes/03-sqlite.mdx index c634df736d..7b2f47f05c 100644 --- a/content/04-guides/01-database-workflows/06-cascading-deletes/03-sqlite.mdx +++ b/content/04-guides/01-database-workflows/06-cascading-deletes/03-sqlite.mdx @@ -1,7 +1,7 @@ --- title: 'Cascading deletes (SQLite)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Configure cascading deletes with Prisma and SQLite' +metaDescription: 'Learn how to configure cascading deletes with Prisma and SQLite by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx b/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx index 27c24b35cc..541bbfbb58 100644 --- a/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx +++ b/content/04-guides/01-database-workflows/07-data-validation/01-postgresql.mdx @@ -1,7 +1,7 @@ --- title: 'Data validation with CHECK constraints (PostgreSQL)' -metaTitle: '' -metaDescription: '' +metaTitle: 'Data validation with CHECK constraints (PostgreSQL)' +metaDescription: 'Learn how to configure CHECK constraints for data validation with Prisma and PostgreSQL by following the step-by-step instructions in this practical guide.' --- ## Overview diff --git a/content/04-guides/02-deployment/01-deploying-to-zeit-now.mdx b/content/04-guides/02-deployment/01-deploying-to-zeit-now.mdx index a8fd18a91c..4e4e7bc455 100644 --- a/content/04-guides/02-deployment/01-deploying-to-zeit-now.mdx +++ b/content/04-guides/02-deployment/01-deploying-to-zeit-now.mdx @@ -1,7 +1,7 @@ --- title: 'Deploying to ZEIT Now' -metaTitle: '' -metaDescription: '' +metaTitle: 'Deploying to ZEIT Now' +metaDescription: 'Learn how to deploy Node.js and TypeScript that are using Prisma Client to ZEIT Now.' --- ## Overview diff --git a/content/04-guides/02-deployment/02-deploying-to-aws-lambda.mdx b/content/04-guides/02-deployment/02-deploying-to-aws-lambda.mdx index 81b1274717..f3d173fd2c 100644 --- a/content/04-guides/02-deployment/02-deploying-to-aws-lambda.mdx +++ b/content/04-guides/02-deployment/02-deploying-to-aws-lambda.mdx @@ -1,7 +1,7 @@ --- title: 'Deploying to AWS Lambda' -metaTitle: '' -metaDescription: '' +metaTitle: 'Deploying to AWS Lambda' +metaDescription: 'Learn how to deploy Node.js and TypeScript that are using Prisma Client to AWS Lambda.' --- Coming ๐Ÿ”œ diff --git a/content/04-guides/02-deployment/04-deploying-to-netlify.mdx b/content/04-guides/02-deployment/04-deploying-to-netlify.mdx index c240920567..e27ae02d7e 100644 --- a/content/04-guides/02-deployment/04-deploying-to-netlify.mdx +++ b/content/04-guides/02-deployment/04-deploying-to-netlify.mdx @@ -1,9 +1,11 @@ --- title: 'Deploying to Netlify' -metaTitle: '' -metaDescription: 'A guide to deploying Prisma to Netlify' +metaTitle: 'Deploying to Netlify' +metaDescription: 'Learn how to deploy Node.js and TypeScript that are using Prisma Client to Netlify.' --- +## Overview + In this guide, you will set up and deploy a serverless Node.js application to [Netlify](https://www.netlify.com/). The application will expose a REST API and use Prisma Client to handle fetching, creating, and deleting records from a database. Netlify is a cloud platform for continuous deployment, static sites, and serverless functions. Netlify integrates seamlessly with GitHub for automatic deployments upon commits. In this guide, you will use this approach to create a CI/CD pipeline that deploys your application from a GitHub repository. From 44bc5804f37220cf70a645d8d5fb452abb339461 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 11:22:51 +0200 Subject: [PATCH 67/76] add meta data --- content/05-more/01-about-the-docs.mdx | 4 ++-- content/05-more/02-style-guide.mdx | 4 ++-- content/05-more/03-supported-databases.mdx | 4 ++-- content/05-more/04-creating-bug-reports.mdx | 6 +++--- content/05-more/05-faq.mdx | 4 ++-- content/05-more/06-limitations.mdx | 4 ++-- content/05-more/07-roadmap.mdx | 2 +- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/content/05-more/01-about-the-docs.mdx b/content/05-more/01-about-the-docs.mdx index 974c033157..8fdba53ffa 100644 --- a/content/05-more/01-about-the-docs.mdx +++ b/content/05-more/01-about-the-docs.mdx @@ -1,7 +1,7 @@ --- title: 'About the docs' -metaTitle: '' -metaDescription: '' +metaTitle: 'About the Prisma documentation' +metaDescription: 'This page gives a meta-overview about different topics that are relevant to better understand and navigate the Prisma documentation.' --- ## Overview diff --git a/content/05-more/02-style-guide.mdx b/content/05-more/02-style-guide.mdx index 2c466832a7..f49f556cec 100644 --- a/content/05-more/02-style-guide.mdx +++ b/content/05-more/02-style-guide.mdx @@ -1,7 +1,7 @@ --- title: 'Prisma style guide' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma documentation style guide' +metaDescription: 'The Prisma style guide contains a number of rules and conventions for the content in the Prisma documentation.' --- ## Welcome! diff --git a/content/05-more/03-supported-databases.mdx b/content/05-more/03-supported-databases.mdx index f65366c4e6..0f1fb4273b 100644 --- a/content/05-more/03-supported-databases.mdx +++ b/content/05-more/03-supported-databases.mdx @@ -1,7 +1,7 @@ --- title: 'Supported databases' -metaTitle: '' -metaDescription: '' +metaTitle: 'Databases supported by Prisma' +metaDescription: 'This page lists all the databases and their versions that are supported by Prisma.' --- ## Overview diff --git a/content/05-more/04-creating-bug-reports.mdx b/content/05-more/04-creating-bug-reports.mdx index db5bbd07b6..a326fffda0 100644 --- a/content/05-more/04-creating-bug-reports.mdx +++ b/content/05-more/04-creating-bug-reports.mdx @@ -1,7 +1,7 @@ --- -title: "Creating bug reports" -metaTitle: "" -metaDescription: "" +title: 'Creating bug reports' +metaTitle: 'Creating bug reports for Prisma' +metaDescription: 'This page explains best practices for creating bug reports for Prisma, inlcuding sharing additional debugging output and other recommendations.' --- ## Overview diff --git a/content/05-more/05-faq.mdx b/content/05-more/05-faq.mdx index 063ff700a7..b17b73d9b9 100644 --- a/content/05-more/05-faq.mdx +++ b/content/05-more/05-faq.mdx @@ -1,7 +1,7 @@ --- title: 'FAQ' -metaTitle: '' -metaDescription: '' +metaTitle: 'Prisma FAQs' +metaDescription: 'Frequently asked questions (FAQ) about the Prisma tools and their ecosystem.' --- ## Can I still access my database directly (e.g. using raw SQL)? diff --git a/content/05-more/06-limitations.mdx b/content/05-more/06-limitations.mdx index 51fca8b753..2c94b44e67 100644 --- a/content/05-more/06-limitations.mdx +++ b/content/05-more/06-limitations.mdx @@ -1,7 +1,7 @@ --- title: 'Limitations' -metaTitle: '' -metaDescription: '' +metaTitle: 'Limitations' +metaDescription: 'This page lists a number of current limitations of Prisma.' --- ## Overview diff --git a/content/05-more/07-roadmap.mdx b/content/05-more/07-roadmap.mdx index 5cfd08ac21..05a91945f3 100644 --- a/content/05-more/07-roadmap.mdx +++ b/content/05-more/07-roadmap.mdx @@ -1,6 +1,6 @@ --- title: 'Roadmap' -metaTitle: '' +metaTitle: 'Roadmap โ€“ Future Prisma Features' metaDescription: '' --- From f2c411baf3abcda49a226fe1f161e6e5a54938f3 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 11:26:38 +0200 Subject: [PATCH 68/76] add meta data --- content/05-more/07-roadmap.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/05-more/07-roadmap.mdx b/content/05-more/07-roadmap.mdx index 05a91945f3..d3f89f8892 100644 --- a/content/05-more/07-roadmap.mdx +++ b/content/05-more/07-roadmap.mdx @@ -1,7 +1,7 @@ --- title: 'Roadmap' metaTitle: 'Roadmap โ€“ Future Prisma Features' -metaDescription: '' +metaDescription: 'This page gives an overview of the features that are on the Prisma roadmap.' --- ## Overview From d274c6480096672e909424140abf91bca2d81cad Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 11:46:06 +0200 Subject: [PATCH 69/76] adjust diagrams --- .../02-setup-prisma/01-add-to-an-existing-project.mdx | 6 +++--- .../02-setup-prisma/02-start-from-scratch-sql.mdx | 6 +++--- content/02-understand-prisma/01-introduction.mdx | 6 +++--- content/02-understand-prisma/02-why-prisma.mdx | 4 ++-- .../01-tools-and-interfaces/03-prisma-migrate.mdx | 11 +++++++++++ .../01-tools-and-interfaces/04-introspection.mdx | 4 ++-- 6 files changed, 24 insertions(+), 13 deletions(-) diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index e14d6ce019..be4c26ae62 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -315,7 +315,7 @@ This commands reads the `DATABASE_URL` environment variable that's defined in `. After the introspection has completed, your Prisma schema file was updated: -![](https://imgur.com/EYC3RIK.png) +![](https://imgur.com/f7itiYw.png) The data model now looks similar to this (note that the fields on the models have been reordered for better readability): @@ -435,7 +435,7 @@ npx prisma generate This commands reads your Prisma schema and generates your Prisma Client library into `node_modules/@prisma/client`. -![](https://imgur.com/0kmSv6l.png) +![](https://imgur.com/FensWfo.png) Because the `@prisma/client` node module actually is customized to your project, it is sometimes referred to as a "smart node module": @@ -708,7 +708,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Optionally re-configure your Prisma Client API 1. Re-generate Prisma Client -![](https://imgur.com/7BUqpyv.png) +![](https://imgur.com/ToNkpb2.png) --- diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index 1b10878d30..fc4216b4a8 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -379,7 +379,7 @@ This commands reads the `DATABASE_URL` environment variable that's defined in `. After the introspection has completed, your Prisma schema file was updated: -![](https://imgur.com/EYC3RIK.png) +![](https://imgur.com/f7itiYw.png) The data model now looks as follows (note that the fields on the models have been reordered for better readability): @@ -453,7 +453,7 @@ npx prisma generate This commands reads your Prisma schema and generates your Prisma Client library into `node_modules/@prisma/client`. -![](https://imgur.com/0kmSv6l.png) +![](https://imgur.com/FensWfo.png) Because the `@prisma/client` node module actually is customized to your project, it is sometimes referred to as a "smart node module": @@ -810,7 +810,7 @@ To evolve the app, you need to follow the same flow of the tutorial: 1. Optionally re-configure your Prisma Client API 1. Re-generate Prisma Client -![](https://imgur.com/7BUqpyv.png) +![](https://imgur.com/ToNkpb2.png) --- diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index 7153a113b0..a1cd8d841e 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -1,7 +1,7 @@ --- title: 'Introduction' metaTitle: 'Introduction to Prisma' -metaDescription: 'This page gives a high-level overview of what Prisma is and how it works. It's a great starting point for Prisma newcomers!' +metaDescription: "This page gives a high-level overview of what Prisma is and how it works. It's a great starting point for Prisma newcomers!" --- ## Overview @@ -202,7 +202,7 @@ The typical workflow when using **SQL migrations and introspection** looks as fo 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/7BUqpyv.png) +![](https://imgur.com/5mGLkYg.png) ### Prisma Migrate @@ -213,6 +213,6 @@ With **Prisma Migrate**, the workflow looks slightly different: 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/nX0jIo5.png) +![](https://imgur.com/5mGLkYg.png) To dive deeper, please refer to the respective docs page. diff --git a/content/02-understand-prisma/02-why-prisma.mdx b/content/02-understand-prisma/02-why-prisma.mdx index 8d559666cc..2ccc9b22bb 100644 --- a/content/02-understand-prisma/02-why-prisma.mdx +++ b/content/02-understand-prisma/02-why-prisma.mdx @@ -16,7 +16,7 @@ Prisma makes it easy for developers to reason about their database queries by pr The main problem with the database tools that currently exist in the Node.js and TypeScript ecosystem is that they require a major tradeoff between _productvity_ and _control_. -![](https://imgur.com/juPfyZS.png) +![](https://imgur.com/m8VTkDL.png) ### Raw SQL: Full control, low productivity @@ -86,4 +86,4 @@ Prisma's main goal is to make application developers more productive when workin Considering the tradeoff between productivity and control again, this is how Prisma fits in: -![](https://imgur.com/JkQHIKl.png) +![](https://imgur.com/2JtwqGm.png) diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx index 4f744620c9..19425b4122 100644 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx +++ b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx @@ -204,3 +204,14 @@ The `migrations` directory should be checked into version control (e.g. Git). ### The `_Migrations` table The `_Migrations` table additionally stores information about each migration that was ever executed against the database by Prisma Migrate. + +## Typical workflow + +With **Prisma Migrate**, the workflow looks slightly different: + +1. Manually adjust your [Prisma data model](./prisma-schema/data-model) +1. Migrate your database using the `prisma migrate` CLI commands +1. (Re-)generate Prisma Client +1. Use Prisma Client in your application code to access your database + +![](https://imgur.com/5mGLkYg.png) \ No newline at end of file diff --git a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx index 2e16f56416..6019881439 100644 --- a/content/03-reference/01-tools-and-interfaces/04-introspection.mdx +++ b/content/03-reference/01-tools-and-interfaces/04-introspection.mdx @@ -16,7 +16,7 @@ However, it can also be used _repeatedly_ in an application. This is most common Introspection has one main function: Populate your Prisma schema with a data model that reflects the current database schema. -![](https://imgur.com/EYC3RIK.png) +![](https://imgur.com/f7itiYw.png) Here's an overview of its main functions: @@ -56,7 +56,7 @@ The typical workflow for projects that are not using Prisma Migrate, but instead Note that as you evolve the application, this process can be repeated for an indefinite number of times. -![](https://imgur.com/7BUqpyv.png) +![](https://imgur.com/ToNkpb2.png) ## Rules and conventions From ba5a85f61e5cb0e207f3d79e2b6176c5f61482e7 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 11:54:42 +0200 Subject: [PATCH 70/76] adjust diagrams --- content/02-understand-prisma/01-introduction.mdx | 4 ++-- .../01-tools-and-interfaces/03-prisma-migrate.mdx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/content/02-understand-prisma/01-introduction.mdx b/content/02-understand-prisma/01-introduction.mdx index a1cd8d841e..b4e38d75da 100644 --- a/content/02-understand-prisma/01-introduction.mdx +++ b/content/02-understand-prisma/01-introduction.mdx @@ -202,7 +202,7 @@ The typical workflow when using **SQL migrations and introspection** looks as fo 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/5mGLkYg.png) +![](https://imgur.com/ToNkpb2.png) ### Prisma Migrate @@ -213,6 +213,6 @@ With **Prisma Migrate**, the workflow looks slightly different: 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/5mGLkYg.png) +![](https://imgur.com/OImder6.png) To dive deeper, please refer to the respective docs page. diff --git a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx index 19425b4122..14bdb18acd 100644 --- a/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx +++ b/content/03-reference/01-tools-and-interfaces/03-prisma-migrate.mdx @@ -214,4 +214,4 @@ With **Prisma Migrate**, the workflow looks slightly different: 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![](https://imgur.com/5mGLkYg.png) \ No newline at end of file +![](https://imgur.com/OImder6.png) \ No newline at end of file From bc895e34bb45d5c824efdd910e34e4ac3cfffafc Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 12:16:26 +0200 Subject: [PATCH 71/76] fix link for supported platforms --- .../02-prisma-client/18-query-engine.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx index dde0d7e64d..7e270e63f7 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/18-query-engine.mdx @@ -18,7 +18,7 @@ This page covers relevant technical details about the query engine. ### The query engine binary file -The **query engine binary file** is called `query-engine-PLATFORM` where `PLATFORM` corresponds to the name of a compile target. For example, if the query engine must run on a [Darwin]() operating system (e.g. Mac OS), it's called `query-engine-darwin`. You can find an overview of all supported platforms [here](). +The **query engine binary file** is called `query-engine-PLATFORM` where `PLATFORM` corresponds to the name of a compile target. For example, if the query engine must run on a [Darwin]() operating system (e.g. Mac OS), it's called `query-engine-darwin`. You can find an overview of all supported platforms [here](../prisma-schema/generators##supported-operating-systems). The query engine binary file is downloaded into the `runtime` directory of `node_modules/@prisma/client` when `prisma generate` is called. From 519ce517754b07a43c43962d0b1d0cf3bca3d436 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 12:39:15 +0200 Subject: [PATCH 72/76] fix build --- .../02-prisma-client/06-field-selection.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx index 642c16d65e..2475634d8f 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx @@ -1,7 +1,7 @@ --- title: 'Field selection' metaTitle: 'Field selection (Reference)' -metaDescription: "This page explains how to select only a subset of a model's fields and/or include relations ("eager loading") in a Prisma Client query." +metaDescription: "This page explains how to select only a subset of a model's fields and/or include relations (\"eager loading\") in a Prisma Client query." --- ## Overview From 9604357a939ae3f0b987bb2458e6c7a9ebb69d29 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 13:13:46 +0200 Subject: [PATCH 73/76] adjust diagrams --- content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md | 2 +- content/03-reference/02-database-connectors/03-postgresql.mdx | 2 +- content/03-reference/02-database-connectors/04-mysql.mdx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md index e0daa8b6f9..f6e4e6d970 100644 --- a/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md +++ b/content/02-understand-prisma/03-prisma-in-your-stack/01-rest.md @@ -8,7 +8,7 @@ metaDescription: 'This page gives an overview of the most important things when When building REST APIs, Prisma Client can be used inside your _route controllers_ to send databases queries. -![](https://imgur.com/dbRvgHc.png) +![](https://imgur.com/5NwAOMt.png) ## Supported libraries diff --git a/content/03-reference/02-database-connectors/03-postgresql.mdx b/content/03-reference/02-database-connectors/03-postgresql.mdx index 0524426bb3..68ef99dcc0 100644 --- a/content/03-reference/02-database-connectors/03-postgresql.mdx +++ b/content/03-reference/02-database-connectors/03-postgresql.mdx @@ -30,7 +30,7 @@ The fields passed to the `datasource` block are: Prisma follows the [official PostgreSQLl format](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for connection URLs. Here's an overview of the components needed for a PostgreSQL connection URL: -![](https://imgur.com/ZMzozDQ.png) +![](https://imgur.com/m7l8KVo.png) **Base URL and path** diff --git a/content/03-reference/02-database-connectors/04-mysql.mdx b/content/03-reference/02-database-connectors/04-mysql.mdx index 29dfc7deb6..a2fb80f9ae 100644 --- a/content/03-reference/02-database-connectors/04-mysql.mdx +++ b/content/03-reference/02-database-connectors/04-mysql.mdx @@ -30,7 +30,7 @@ The fields passed to the `datasource` block are: Here's an overview of the components needed for a MySQL connection URL: -![](https://imgur.com/NswjbsP.png) +![](https://imgur.com/KkZe3hO.png) **Base URL and path** From 973f9c148a0a4cc2a758487b7c90421bc39ab608 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 22:39:19 +0200 Subject: [PATCH 74/76] fix TS link --- .../02-prisma-client/06-field-selection.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx index 39fe7012cc..10761d10a1 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/06-field-selection.mdx @@ -1,11 +1,7 @@ --- title: 'Field selection' metaTitle: 'Field selection (Reference)' -<<<<<<< HEAD metaDescription: "This page explains how to select only a subset of a model's fields and/or include relations (\"eager loading\") in a Prisma Client query." -======= -metaDescription: 'This page explains how to select only a subset of a model''s fields and/or include relations ("eager loading") in a Prisma Client query.' ->>>>>>> 6b4b871db2e3eb6017f691dffbf90389c7b17f85 --- ## Overview From 90fca26eeb5e24ad6d1eb79cc617ecdbb970ddf2 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Mon, 30 Mar 2020 23:34:04 +0200 Subject: [PATCH 75/76] continue docs content --- content/01-getting-started/01-quickstart.mdx | 47 +++++++++++++++++-- .../01-add-to-an-existing-project.mdx | 2 + .../05-under-the-hood.mdx | 2 +- .../02-prisma-client/01-api.mdx | 17 ++++++- content/index.mdx | 14 ++++++ 5 files changed, 75 insertions(+), 7 deletions(-) diff --git a/content/01-getting-started/01-quickstart.mdx b/content/01-getting-started/01-quickstart.mdx index 40cce60cae..0a46bc07b4 100644 --- a/content/01-getting-started/01-quickstart.mdx +++ b/content/01-getting-started/01-quickstart.mdx @@ -94,7 +94,7 @@ Note that the dependencies defined in your project are: The starter project consists of five files: - `package.json`: Defines your npm dependencies -- `prisma/schema.prisma`: [Prisma schema file](../reference/tools-and-interfaces/prisma-schema/ +- `prisma/schema.prisma`: [Prisma schema file](../reference/tools-and-interfaces/prisma-schema/) defining your models - `prisma/.env`: Defines your database connection URL as an environment variable - `prisma/dev.db`: A SQLite database file - `scr/index.js`: A plain, executable Node.js script @@ -134,6 +134,35 @@ npm install ## Write your first query with Prisma Client +In this section, you will write your first query with Prisma Client. For reference, this is what the [Prisma schema](../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) for which your Prisma Client was generated looks like: + +```prisma +datasource db { + provider = "sqlite" + url = "file:./dev.db" +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` + The code inside `src/index.ts` currently looks as follows: @@ -475,8 +504,19 @@ const deletedUser = await prisma.user.delete({ To learn how to connect Prisma to your own database, you can follow the respective setup guide: -- [Setup a new project with Prisma from scratch](./setup-prisma/start-from-scratch-sql) -- [Add Prisma to an existing project](./setup-prisma/add-to-an-existing-project) + + Setup a new project from scratch + + +
    +
    + + + Add Prisma to an existing project + + + --- @@ -558,7 +598,6 @@ Now you can run the migration against the database `npx prisma migrate up --expe
    - Finally, re-generate Prisma Client with this command: ``` copy diff --git a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx index be4c26ae62..a98e4f2dda 100644 --- a/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx +++ b/content/01-getting-started/02-setup-prisma/01-add-to-an-existing-project.mdx @@ -20,6 +20,8 @@ This page walks you through the process of adding Prisma to a **Node.js** projec
    +You can also watch this short [video series](https://www.youtube.com/playlist?list=PLn2e1F9Rfr6k9PnR_figWOcSHgc_erDr5) that shows the Prisma setup process with an existing database. + ## Prerequisites In order to successfully complete this guide, you need: diff --git a/content/02-understand-prisma/05-under-the-hood.mdx b/content/02-understand-prisma/05-under-the-hood.mdx index 6199cbea29..4eb83f0009 100644 --- a/content/02-understand-prisma/05-under-the-hood.mdx +++ b/content/02-understand-prisma/05-under-the-hood.mdx @@ -21,7 +21,7 @@ The tools in the Prisma toolkit are built with respect to two dimensions: The following illustration gives an overview of the tools that exist (or are planned) in the Prisma toolkit: -![](https://imgur.com/NoTXRqT.png) +![](https://i.imgur.com/mxJTGOu.png) ### Modules diff --git a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx index 9a590271bf..a1fd19fe4f 100644 --- a/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx +++ b/content/03-reference/01-tools-and-interfaces/02-prisma-client/01-api.mdx @@ -8,10 +8,23 @@ metaDescription: "This page gives an overview of the Prisma Client API and links Prisma Client is an auto-generated and type-safe query builder that's _tailored_ to your data. The easiest way to get started with Prisma Client is by following the **[Quickstart](../../../getting-started/quickstart)**. + + + Quickstart (5 min) + + The setup instruction below provide a high-level overview of the steps needed to set up Prisma Client. If you want to get started using Prisma Client with your own database, follow one of these guides: -- [Setup a new project with Prisma from scratch](../../../setup-prisma/start-from-scratch-sql) -- [Add Prisma to an existing project](../../../setup-prisma/add-to-an-existing-project) + + Setup a new project from scratch + + +
    +
    + + + Add Prisma to an existing project + ## Setup diff --git a/content/index.mdx b/content/index.mdx index 7cd13b0337..f3eb440cde 100644 --- a/content/index.mdx +++ b/content/index.mdx @@ -10,6 +10,20 @@ Welcome to the Prisma documentation! You can find an overview of the available c > **If you're using Prisma 1, please refer to the [Prisma 1 documentation](https://www.prisma.io/docs/1.34).** +## Explore + + + Quickstart (5 min) + + +
    +
    + + + Read Prisma introduction + + + ## Table of contents --- From 602d7f2555fdb050b7279f0040f63a82b572f3f3 Mon Sep 17 00:00:00 2001 From: Nikolas Burk Date: Tue, 31 Mar 2020 00:00:49 +0200 Subject: [PATCH 76/76] add guide for prisma migrate --- content/01-getting-started/01-quickstart.mdx | 18 +- .../02-start-from-scratch-sql.mdx | 2 +- .../03-start-from-scratch-prisma-migrate.mdx | 764 ++++++++++++++++++ 3 files changed, 774 insertions(+), 10 deletions(-) create mode 100644 content/01-getting-started/02-setup-prisma/03-start-from-scratch-prisma-migrate.mdx diff --git a/content/01-getting-started/01-quickstart.mdx b/content/01-getting-started/01-quickstart.mdx index 0a46bc07b4..1a50ffd4f5 100644 --- a/content/01-getting-started/01-quickstart.mdx +++ b/content/01-getting-started/01-quickstart.mdx @@ -618,17 +618,17 @@ The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository c | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/typescript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/typescript/grpc) | Backend only | Simple gRPC API | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | **JavaScript (Node.js)** | Demo | Stack | Description | | :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | -| [`rest-nextjs`](https://github.com/prisma/prisma-examples/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | -| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | -| [`rest-express`](https://github.com/prisma/prisma-examples/javascript/rest-express) | Backend only | Simple REST API with Express.JS | -| [`grpc`](https://github.com/prisma/prisma-examples/javascript/grpc) | Backend only | Simple gRPC API | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | diff --git a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx index fc4216b4a8..3e95edc0c5 100644 --- a/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx +++ b/content/01-getting-started/02-setup-prisma/02-start-from-scratch-sql.mdx @@ -1,6 +1,6 @@ --- title: 'Start from scratch' -metaTitle: 'Setup a new projecct with Prisma from scratch (15 min)' +metaTitle: 'Setup a new project with Prisma from scratch (SQL)' metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your database and generating Prisma Client for database access.' dbSwitcher: true langSwitcher: true diff --git a/content/01-getting-started/02-setup-prisma/03-start-from-scratch-prisma-migrate.mdx b/content/01-getting-started/02-setup-prisma/03-start-from-scratch-prisma-migrate.mdx new file mode 100644 index 0000000000..64ffc558cc --- /dev/null +++ b/content/01-getting-started/02-setup-prisma/03-start-from-scratch-prisma-migrate.mdx @@ -0,0 +1,764 @@ +--- +title: 'Start from scratch (Prisma Migrate)' +metaTitle: 'Setup a new project with Prisma from scratch (Prisma Migrate)' +metaDescription: 'Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your database and generating Prisma Client for database access.' +dbSwitcher: true +langSwitcher: true +--- + +## Overview + +This page walks you through the process of setting up Prisma from scratch with your own database. It uses [Prisma Migrate](../../../reference/tools-and-interfaces/prisma-migrate) to create tables in your database. + +> **Note**: Prisma Migrate is currently considered experimental. + +## Prerequisites + +In order to successfully complete this guide, you need: + + + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [PostgreSQL](https://www.postgresql.org/) database server running + + + + + +- [Node.js](https://nodejs.org/en/) installed on your machine +- a [MySQL](https://www.mysql.com/) database server running + + + +Make sure your have your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) (includes your authentication credentials) at hand! + +If you don't have a database server running and only want to explore Prisma, check out the [Quickstart](../quickstart). Alternatively you can [setup a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1) and use it in this guide. + +## Create project setup + +As a first step, create a project directory and navigate into it: + +``` +mkdir hello-prisma +cd hello-prisma +``` + + + +Next, initialize a TypeScript project and add the Prisma CLI as a development dependency to it: + +``` +npm init -y +npm install @prisma/cli typescript ts-node @types/node --save-dev +``` + +This creates a `package.json` with an initial setup for your TypeScript app. + +Next, create a `tsconfig.json` file and add the following configuration to it: + +```json +{ + "compilerOptions": { + "sourceMap": true, + "outDir": "dist", + "strict": true, + "lib": ["esnext"], + "esModuleInterop": true + } +} +``` + + + + + +Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it: + +``` +npm init -y +npm install @prisma/cli --save-dev +``` + +This creates a `package.json` with an initial setup for a Node.js app. + + + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +``` +npx prisma +``` + +Next, set up your Prisma project by creating your [Prisma schema](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file) file with the following command: + +``` +npx prisma init +``` + +This command created a new directory called `prisma` with the following contents: + +- `schema.prisma`: The Prisma schema with your database connection and the Prisma Client generator +- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file for defining environment variables (used for your database connection) + +## Connect your database + +To connect your database, you need to set the `url` field of the `datasource` block in your Prisma schema to your database [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls): + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: + +``` +DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +``` +postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `5432` for PostgreSQL) +- `DATABASE`: The name of the [database](https://www.postgresql.org/docs/12/manage-ag-overview.html) +- `SCHEMA`: The name of the [schema](https://www.postgresql.org/docs/12/ddl-schemas.html) inside the database + +If you're unsure what to provide for the `schema` parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name `public` will be used. + +As an example, for a PostgreSQL database hosted on Heroku, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: + +``` +DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma" +``` + +When running PostgreSQL locally, your user and password as well as the database name _typically_ correspond to the current _user_ of your OS, e.g. assuming the user is called `janedoe`: + +``` +DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma" +``` + + + + + +```prisma +datasource postgresql { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Note that the default schema created by `prisma init` uses PostgreSQL, so you first need to switch the `provider` to `mysql`: + +```prisma +datasource mysql { + provider = "mysql" + url = env("DATABASE_URL") +} +``` + +In this case, the `url` is [set via an environment variable](../../reference/tools-and-interfaces/prisma-schema/prisma-schema-file#using-environment-variables) which is defined in `prisma/.env`: + +``` +DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" +``` + +You now need to adjust the connection URL to point to your own database. + +The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (the parts spelled all-uppercased are _placeholders_ for your specific connection details): + +``` +mysql://USER:PASSWORD@HOST:PORT/DATABASE +``` + +Here's a short explanation of each component: + +- `USER`: The name of your database user +- `PASSWORD`: The password your database user +- `PORT`: The port where your database server is running (typically `3306` for MySQL) +- `DATABASE`: The name of the [database](https://dev.mysql.com/doc/refman/8.0/en/creating-database.html) + +As an example, for a MySQL database hosted on AWS RDS, the [connection URL](../../reference/tools-and-interfaces/database-connectors/connection-urls) might look similar to this: + +``` +DATABASE_URL="mysql://johndoe:XXX@mysqlโ€“instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb +``` + +When running MySQL locally, your connection URL typically looks similar to this: + +``` +DATABASE_URL="mysql://root:randompassword@localhost:3306/mydb" +``` + + + +## Create database tables with Prisma Migrate + + + +In this guide, you'll use [Prisma Migrate](../../../reference/tools-and-interfaces/prisma-migrate) to create the tables in your database. Add the following Prisma data model to your Prisma schema in `prisma/schema.prisma`: + + + +```prisma +model Post { + id Int @default(autoincrement()) @id + createdAt DateTime @default(now()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId], name: "authorId") +} + +model Profile { + id Int @default(autoincrement()) @id + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @default(autoincrement()) @id + email String @unique + name String? + Post Post[] + Profile Profile? +} +``` + +```sql +CREATE TABLE "public"."User" ( + id SERIAL PRIMARY KEY NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE "public"."Post" ( + id SERIAL PRIMARY KEY NOT NULL, + title VARCHAR(255) NOT NULL, + "createdAt" TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + author INTEGER NOT NULL, + FOREIGN KEY (author) REFERENCES "public"."User"(id) +); + +CREATE TABLE "public"."Profile" ( + id SERIAL PRIMARY KEY NOT NULL, + bio TEXT, + "user" INTEGER UNIQUE NOT NULL, + FOREIGN KEY ("user") REFERENCES "public"."User"(id) +); +``` + + + + + + + +```prisma +model Post { + id Int @default(autoincrement()) @id + createdAt DateTime @default(now()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int + + @@index([authorId], name: "authorId") +} + +model Profile { + id Int @default(autoincrement()) @id + bio String? + user User @relation(fields: [userId], references: [id]) + userId Int @unique +} + +model User { + id Int @default(autoincrement()) @id + email String @unique + name String? + Post Post[] + Profile Profile? +} +``` + +```sql +CREATE TABLE User ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + name VARCHAR(255), + email VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE Post ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + title VARCHAR(255) NOT NULL, + createdAt TIMESTAMP NOT NULL DEFAULT now(), + content TEXT, + published BOOLEAN NOT NULL DEFAULT false, + authorId INTEGER NOT NULL, + FOREIGN KEY (authorId) REFERENCES User(id) +); + +CREATE TABLE Profile ( + id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, + bio TEXT, + userId INTEGER UNIQUE NOT NULL, + FOREIGN KEY (userId) REFERENCES User(id) +); +``` + + + +To map your data model to the databse schema, you need to use the `prisma migrate` CLI commands: + +``` +npx prisma migrate save --name init --experimental +npx prisma migrate up --experimental +``` + +The `save` command creates a new directory called `migrations` where it will store your migration history, it does not yet create any tables in the database. The tables are created when `up` is invoked! + +Great, you now created three tables in your database with Prisma Migrate ๐Ÿš€ + +
    Expand for a graphical overview of the tables + +**User** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `name` | `VARCHAR(255)` | No | No | No | - | +| `email` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | + +**Post** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :------------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `createdAt` | `TIMESTAMP` | No | No | **โœ”๏ธ** | `now()` | +| `title` | `VARCHAR(255)` | No | No | **โœ”๏ธ** | - | +| `content` | `TEXT` | No | No | No | - | +| `published` | `BOOLEAN` | No | No | **โœ”๏ธ** | `false` | +| `authorId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | `false` | + +**Profile** + +| Column name | Type | Primary key | Foreign key | Required | Default | +| :---------- | :-------- | :---------- | :---------- | :------- | :----------------- | +| `id` | `INTEGER` | **โœ”๏ธ** | No | No | _autoincrementing_ | +| `bio` | `TEXT` | No | No | **โœ”๏ธ** | - | +| `userId` | `INTEGER` | No | **โœ”๏ธ** | **โœ”๏ธ** | - | + +
    + +## Install and generate Prisma Client + +To get started with Prisma Client, you need to install it as a node module: + +``` +npm install @prisma/client +``` + +Notice that the [`@prisma/client` node module](../../reference/tools-and-interfaces/prisma-client/configuring-the-prisma-client-api#the-prisma-client-npm-module) is a bit different from "conventional" node modules (e.g. a library like [`lodash`](https://lodash.com/)). When installing the module with `npm install @prisma/client`, npm only downloads an empty package into the `node_modules/@prisma/client` directory. The package is then "filled" with the actual library with the following command of the Prisma CLI: + +``` +npx prisma generate +``` + +This commands reads your Prisma schema and generates your Prisma Client library into `node_modules/@prisma/client`. + +![](https://imgur.com/FensWfo.png) + +Because the `@prisma/client` node module actually is customized to your project, it is sometimes referred to as a "smart node module": + +![](https://i.imgur.com/83djlkl.png) + +## Write your first query with Prisma Client + +Now that you generated your Prisma Client library, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client. + + + +Create a new file called `index.ts` and add the following code to it: + +```js +import { PrismaClient } from "@prisma/client" + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .catch(e => { + throw e + }) + .finally(async () => { + await prisma.disconnect() + }) +``` + + + + + +Create a new file called `index.js` and add the following code to it: + +```js +const { PrismaClient } = require("@prisma/client") + +const prisma = new PrismaClient() + +async function main() { + // ... you will write your Prisma Client queries here +} + +main() + .catch(e => { + throw e + }) + .finally(async () => { + await prisma.disconnect() + }) +``` + + + +Here's a quick overview of the different parts of the code snippet: + +1. Import the `PrismaClient` constructor from the `@prisma/client` node module +1. Instantiate `PrismaClient` +1. Define an `async` function called `main` to send queries to the database +1. Call the `main` function +1. Close the database connections when the script terminates + +Inside the `main` function, add the folowing query to read all `User` records from the database and print the result: + +```js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Now run the code with this command: + +``` +node index.js +``` + +This should print an empty arrays because there are no `User` records in the database yet: + +```js +[] +``` + +## Write data into the database + +The `findMany` query you used in the previous section only _reads_ data from the database (although it was still empty). In this section, you'll learn how to write a query to _write_ new records into the `Post` and `User` tables. + +Adjust the `main` function to send a `create` query to the database: + +```js +async function main() { + + await prisma.user.create({ + data: { + name: "Alice", + email: "alice@prisma.io", + author: { + create: { title: "Hello World" }, + }, + profile: { + create: { bio: "I like turtles" } + } + } + }) + + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + profile: true + }, + }) + console.dir(allUsers, { depth: null }) +} +``` + +This code creates a new `User` record together with new `Post` and `Profile` records using a [nested write](#nested-writes) query. The `User` record is connected to the two other ones via the `Post.author` โ†” `User.posts` and `Profile.user` โ†” `User.profile` [relation fields](../../reference/tools-and-interfaces/prisma-schema/relations#relation-fields) respectively. + +Notice that you're passing the [`include`](../../reference/tools-and-interfaces/prisma-client/field-selection#include) option to `findMany` which tells Prisma Client to include the `posts` and `profile` relations on the returned `User` objects. + + + +Run the code with this command: + +``` +npx ts-node index.ts +``` + + + + + +Run the code with this command: + +``` +npx ts-node index.ts +``` + + + + + +Run the code with this command: + +``` +node index.js +``` + + + +The output should look similar to this: + +```js +[ + { + email: 'alice@prisma.io', + id: 1, + name: 'Alice', + posts: [ + { + content: null, + createdAt: 2020-03-21T16:45:01.246Z, + id: 1, + published: false, + title: 'Hello World', + authorId: 1, + } + ], + profile: { + bio: 'I like turtles', + userId: 1, + } + } +] +``` + + + +Also note that `allUsers` is _statically typed_ thanks to [Prisma Client's generated types](../../reference/tools-and-interfaces/prisma-client/advanced-usage-of-generated-types). You can observe the type by hovering over the `allUsers` variable in your editor. It should be typed as follows: + +```ts +const allUsers: (User & { + posts: Post[]; +})[] + +export type Post = { + id: number + title: string + content: string | null + published: boolean + authorId: number | null +} +``` + + + +The query added new records to the `User` and the `Post` tables: + +**User** + +| **id** | **email** | **name** | +| :----- | :------------------ | :-------- | +| `1` | `"alice@prisma.io"` | `"Alice"` | + +**Post** + +| **id** | **createdAt** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------- | :-------------- | :---------- | :------------ | :--------- | +| `1` | `2020-03-21T16:45:01.246Z` | `"Hello World"` | `null` | `false` | `1` | + +**Profile** + +| **id** | **bio** | **userId** | +| :----- | :------------------ | :-------- | +| `1` | `"I like turtles"` | `1` | + +> **Note**: The numbers in the `authorId` column on `Post` and `userId` column on `Profile` both reference the `id` column of the `User` table: the `id` value `1` column therefore refers to the first (and only) `User` record in the database. + +Before moving on to the next section, you'll "publish" the `Post` record you just created using an `update` query. Adjust the `main` function as follows: + +```js +async function main() { + const post = await prisma.post.update({ + where: { id: 1 }, + data: { published: true }, + }) + console.log(post) +} +``` + + + +Now run the code using the same command as before: + +``` +npx ts-node index.ts +``` + + + + + +Now run the code using the same command as before: + +``` +node index.js +``` + + + +You will see the following output: + +```js +{ + id: 1, + title: 'Hello World', + content: null, + published: true, + authorId: 1 +} +``` + +The `Post` record with an `id` of `1` now got updated in the database: + +**Post** + +| **id** | **title** | **content** | **published** | **authorId** | +| :----- | :------------------------------ | :---------- | :------------ | :--------- | +| `1` | `"Hello World"` | `null` | `true` | `1` | + +Fantastic, you just wrote new data into your database for the first time using Prisma Client ๐Ÿš€ + +## Next steps + +This section lists a number of potential next steps you can now take from here. Feel free to explore those or read the [Introduction](../../understand-prisma/introduction) page to get a high-level overview of Prisma. + +### Continue exploring the Prisma Client API + +You can send a variety of different queries with the Prisma Client API. Check out the [API reference](../../reference/tools-and-interfaces/prisma-client/api) and use your existing database setup from this guide to try them out. + +**Tip**: You can use your editor's auto-completion feature to learn about the different API calls and the arguments it takes. Auto-completion is commonly invoked by hitting CTRL+SPACE on your keyboard. + +
    Expand for more Prisma Client API examples + +Here are a few suggestions for a number of more queries you can send with Prisma Client: + +**Filter all `Post` records that contain `"hello"`** + +```js +const filteredPosts = await prisma.post.findMany({ + where: { + OR: [ + { title: { contains: "hello" }, + { content: { contains: "hello" }, + ], + }, +}) +``` + +**Create a new `Post` record and connect it to an existing `User` record** + +```js +const post = await prisma.post.create({ + data: { + title: "Join us for Prisma Day 2020", + posts: { + connect: { email: "alice@prisma.io" }, + }, + }, +}) +``` + +**Use the fluent relations API to retrieve the `Post` records of a `User` by traversing the relations** + +```js +const posts = await prisma.profile + .findOne({ + where: { id: 1 }, + }) + .user() + .posts() +``` + +**Delete a `User` record** + +```js +const deletedUser = await prisma.user.delete({ + where: { email: "sarah@prisma.io" }, +}) +``` + +
    + +--- + +### Explore the data in Prisma Studio (experimental) + +Prisma Studio is a visual editor for the data in your database. You can use it by running the following command: + +``` +npx prisma studio --experimental +``` + +--- + +### Try a Prisma example + +The [`prisma-examples`](https://github.com/prisma/prisma-examples/) repository contains a number of ready-to-run examples: + +**TypeScript** + +| Demo | Stack | Description | +| :----------------------------------------------------------------------------------------------------------------- | :----------- | --------------------------------------------------------------------------------------------------- | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a GraphQL API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/typescript/grpc) | Backend only | Simple gRPC API | + +**JavaScript (Node.js)** + +| Demo | Stack | Description | +| :----------------------------------------------------------------------------------------------------------------- | :----------- | :-------------------------------------------------------------------------------------------------- | +| [`rest-nextjs`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-nextjs) | Fullstack | Simple [Next.js](https://nextjs.org/) app (React) with a REST API | +| [`graphql-apollo-server`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/graphql-apollo-server) | Backend only | Simple GraphQL server based on [`apollo-server`](https://www.apollographql.com/docs/apollo-server/) | +| [`rest-express`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/rest-express) | Backend only | Simple REST API with Express.JS | +| [`grpc`](https://github.com/prisma/prisma-examples/tree/prisma2/javascript/grpc) | Backend only | Simple gRPC API | + + + + + +