From 358926e1513467f23290d194cc6cb2fe873d7dbf Mon Sep 17 00:00:00 2001 From: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> Date: Fri, 17 Nov 2023 05:57:37 +0600 Subject: [PATCH 01/32] fix: remove legacy billing for data platform (#5458) * fix: add redirects for broken links --- vercel.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vercel.json b/vercel.json index c2ffe27757..3eb266760a 100644 --- a/vercel.json +++ b/vercel.json @@ -1722,6 +1722,14 @@ { "source": "/docs/data-platform/classic-projects/platform/billing", "destination": "https://www.prisma.io/pricing" + }, + { + "source": "/docs/data-platform/classic-projects/platform/billing/plans-and-quotas", + "destination": "https://www.prisma.io/pricing" + }, + { + "source": "/docs/data-platform/classic-projects/platform/billing/manage-plans", + "destination": "https://www.prisma.io/pricing" } ] } From e0b55aabd3af3b841e21468f62f4af656b0a608f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Rudge?= Date: Fri, 17 Nov 2023 00:44:46 -0700 Subject: [PATCH 02/32] add prisma-generator-fake-data to 'Community generators' (#4606) Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Co-authored-by: Nikolas --- .../100-components/01-prisma-schema/03-generators.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx b/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx index c1f8bc6c91..503185a232 100644 --- a/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx +++ b/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx @@ -95,4 +95,5 @@ The following is a list of community created generators. If you want to create y - [`prisma-generator-graphql-typedef`](https://github.com/mavvy22/prisma-generator-graphql-typedef): Generates graphql schema. - [`prisma-markdown`](https://github.com/samchon/prisma-markdown): Generates markdown document composed with ERD diagrams and their descriptions. Supports pagination of ERD diagrams through `@namespace` comment tag. - [`prisma-models-graph`](https://github.com/dangchinh25/prisma-models-graph): Generates a bi-directional models graph for schema without strict relationship defined in the schema, works via a custom schema annotation. +- [`https://github.com/luisrudge/prisma-generator-fake-data`](https://github.com/luisrudge/prisma-generator-fake-data): Generates realistic-looking fake data for your Prisma models that can be used in unit/integration tests, demos, and more. From f8f8b88f476a918c294bc1aa98a95d830b2c6cbd Mon Sep 17 00:00:00 2001 From: Rogier van den Berg Date: Fri, 17 Nov 2023 08:45:32 +0100 Subject: [PATCH 03/32] Add docs --name flag for prisma migrate dev command (#4803) Co-authored-by: Nikolas --- .../400-reference/200-api-reference/200-command-reference.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/400-reference/200-api-reference/200-command-reference.mdx b/content/400-reference/200-api-reference/200-command-reference.mdx index 93fd0d962e..d1a2db4863 100644 --- a/content/400-reference/200-api-reference/200-command-reference.mdx +++ b/content/400-reference/200-api-reference/200-command-reference.mdx @@ -1222,7 +1222,8 @@ See also: | `--create-only` | No | Creates a new migration based on the changes in the schema but does not apply that migration. Run `migrate dev` to apply migration. | | | `--skip-seed` | No | Skip triggering seed | | | `--skip-generate` | No | Skip triggering generators (for example, Prisma Client) | | -| `--help` / `--h` | No | Displays the help message | +| `--name` / `-n` | No | Name the migration (e.g. `prisma migrate dev --name added_job_title`) | | +| `--help` / `-h` | No | Displays the help message | From c5cdc5f604d3ba5e92f5c55366d582945dbb4689 Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Fri, 17 Nov 2023 09:58:54 +0100 Subject: [PATCH 04/32] docs: update database connector docs (#5459) update driver adapter mentions to state it's in Preview and Prisma Client Co-authored-by: Jan Piotrowski --- content/200-concepts/200-database-connectors/03-postgresql.mdx | 2 +- content/200-concepts/200-database-connectors/04-mysql.mdx | 2 +- content/200-concepts/200-database-connectors/05-sqlite.mdx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/content/200-concepts/200-database-connectors/03-postgresql.mdx b/content/200-concepts/200-database-connectors/03-postgresql.mdx index e382a6acad..e1d6e77d08 100644 --- a/content/200-concepts/200-database-connectors/03-postgresql.mdx +++ b/content/200-concepts/200-database-connectors/03-postgresql.mdx @@ -8,7 +8,7 @@ metaDescription: 'This page explains how Prisma can connect to a PostgreSQL data The PostgreSQL data source connector connects Prisma to a [PostgreSQL](https://www.postgresql.org/) database server. -By default, the PostgreSQL connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) to connect to your database using a Node.js database driver. +By default, the PostgreSQL connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) (Preview) to connect to your database using a JavaScript database driver from Prisma Client. diff --git a/content/200-concepts/200-database-connectors/04-mysql.mdx b/content/200-concepts/200-database-connectors/04-mysql.mdx index 4124337e9e..e52c2cda73 100644 --- a/content/200-concepts/200-database-connectors/04-mysql.mdx +++ b/content/200-concepts/200-database-connectors/04-mysql.mdx @@ -8,7 +8,7 @@ metaDescription: 'This page explains how Prisma can connect to a MySQL database The MySQL data source connector connects Prisma to a [MySQL](https://www.mysql.com/) database server. -By default, the MySQL connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) to connect to your database using a Node.js database driver. +By default, the MySQL connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) (Preview) to connect to your database using a JavaScript database driver from Prisma Client. diff --git a/content/200-concepts/200-database-connectors/05-sqlite.mdx b/content/200-concepts/200-database-connectors/05-sqlite.mdx index cf2e893386..7b59653f7a 100644 --- a/content/200-concepts/200-database-connectors/05-sqlite.mdx +++ b/content/200-concepts/200-database-connectors/05-sqlite.mdx @@ -8,7 +8,7 @@ metaDescription: 'This page explains how Prisma can connect to a SQLite database The SQLite data source connector connects Prisma to a [SQLite](https://www.sqlite.org/) database file. These files always have the file ending `.db` (e.g.: `dev.db`). -By default, the SQLite connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) to connect to your database using a Node.js database driver. +By default, the SQLite connector contains a database driver responsible for connecting to your database. You can use a [driver adapter](/concepts/components/database-drivers#driver-adapters) (Preview) to connect to your database using a JavaScript database driver from Prisma Client. From cbedb7abf4099c18b210f6f1cedc8b66147b36d3 Mon Sep 17 00:00:00 2001 From: meletj <70962362+meletj@users.noreply.github.com> Date: Fri, 17 Nov 2023 11:01:57 +0100 Subject: [PATCH 05/32] cloud to console link (#5466) --- content/100-getting-started/index.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/100-getting-started/index.mdx b/content/100-getting-started/index.mdx index 9fde0e99dc..899e9a1a48 100644 --- a/content/100-getting-started/index.mdx +++ b/content/100-getting-started/index.mdx @@ -12,9 +12,9 @@ Welcome to the Prisma getting started section! 👋 Prisma is an [open source](h - [**Prisma Migrate**](/concepts/components/prisma-migrate): Migration tool to easily evolve your database schema from prototyping to production - [**Prisma Studio**](/concepts/components/prisma-studio): GUI to view and edit data in your database -Prisma is also available on the [Prisma Data Platform](https://cloud.prisma.io), a cloud-based, collaborative environment for teams and organizations to develop type-safe applications. The platform focuses on developer productivity with GitHub integration for your code and schema, a visual data browser, an online query console, and an optional data proxy for handling database connections. For more information, refer to the Prisma Data Platform [documentation](/data-platform). +Prisma is also available on the [Prisma Data Platform](https://console.prisma.io), a cloud-based, collaborative environment for teams and organizations to develop type-safe applications. The platform focuses on developer productivity with GitHub integration for your code and schema, a visual data browser, an online query console, and an optional data proxy for handling database connections. For more information, refer to the Prisma Data Platform [documentation](/data-platform). -For a more detailed breakdown of what problems Prisma solves, and why it's **built to make you more productive**, see the [Why Prisma](/concepts/overview/why-prisma) section. +For a more detailed breakdown of what problems Prisma solves and why it's **built to make you more productive**, see the [Why Prisma](/concepts/overview/why-prisma) section. From 0392b9d446971e085867daefbbac5b41dc516d68 Mon Sep 17 00:00:00 2001 From: Jan Piotrowski Date: Fri, 17 Nov 2023 11:41:56 +0100 Subject: [PATCH 06/32] fix(shadow-database): Add standalone information on "Manually configuring the shadow database" (#4407) Co-authored-by: Nilufar Bava Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> --- cSpell.json | 5 ++-- .../03-prisma-migrate/200-shadow-database.mdx | 28 ++++++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/cSpell.json b/cSpell.json index 054c9665f7..ce34b4139f 100644 --- a/cSpell.json +++ b/cSpell.json @@ -57,7 +57,7 @@ "Snaplet", "Kysely", "Turso", - "inshellisense", + "autocompletions", "Formbricks", "Openform", "Documenso", @@ -88,7 +88,8 @@ "Vitess", "libgcc", "libc", - "Distroless" + "Distroless", + "inshellisense", ], "patterns": [ { diff --git a/content/200-concepts/100-components/03-prisma-migrate/200-shadow-database.mdx b/content/200-concepts/100-components/03-prisma-migrate/200-shadow-database.mdx index 3b1093cfff..64c69ff269 100644 --- a/content/200-concepts/100-components/03-prisma-migrate/200-shadow-database.mdx +++ b/content/200-concepts/100-components/03-prisma-migrate/200-shadow-database.mdx @@ -41,7 +41,7 @@ When you run `prisma migrate dev` to create a new migration, Prisma Migrate uses To detect drift in development, Prisma Migrate: -1. Creates a fresh copy of the shadow database (or performs a soft reset if the shadow database is cloud-hosted) +1. Creates a fresh copy of the shadow database (or performs a soft reset if the shadow database is configured via [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) 1. Reruns the **current** migration history in the shadow database. 1. **Introspects** the shadow database to generate the 'current state' of your Prisma schema. 1. Compares the end state of the current migration history to the development database. @@ -78,14 +78,33 @@ Assuming Prisma Migrate did not [detect schema drift](#detecting-schema-drift), 1. Compares the end state of the existing migration history and the target schema, and generates steps to get from one to the other. 1. Renders these steps to a SQL string and saves it in the new migration file. 1. Applies the generated migration to the development database (assuming you have not specified the `--create-only` flag) -1. Drops the shadow database (cloud-hosted databases cannot be dropped, but are reset at the start of the `migrate dev` command) +1. Drops the shadow database (shadow databases configured via [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) are not dropped, but are reset at the start of the `migrate dev` command) + +## Manually configuring the shadow database + +In some cases it might make sense (e.g. when [creating and dropping databases is not allowed on cloud-hosted databases](#cloud-hosted-shadow-databases-must-be-created-manually)) to manually define the connection string and name of the database that should be used as the shadow database for `migrate dev`. In such a case you can: + +1. Create a dedicated database that should be used as the shadow database +2. Add the connection string of that database your environment variable `SHADOW_DATABASE_URL` (or `.env` file) +3. Add the [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) field reading this environment variable: + +```prisma highlight=4;normal +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} +``` + +> **Important**: Do not use the exact same values for `url` and `shadowDatabaseUrl` as that might delete all your database in your database. ## Cloud-hosted shadow databases must be created manually Some cloud providers do not allow you to drop and create databases with SQL. Some require to create or drop the database via an online interface, and some really limit you to 1 database. If you **develop** in such a cloud-hosted environment, you must: 1. Create a dedicated cloud-hosted shadow database -2. Add the URL to the [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) field: +2. Add the URL to your environment variable `SHADOW_DATABASE_URL` +3. Add the [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) field reading this environment variable: ```prisma highlight=4;normal datasource db { @@ -110,7 +129,7 @@ In order to create and delete the shadow database when using `migrate dev`, Pris > If you use a cloud-hosted database for development and can not use these permissions, see: [Cloud-hosted shadow databases](#cloud-hosted-shadow-databases-must-be-created-manually) -> Note: The automatic creation of shadow databases is disabled on Azure SQL. +> Note: The automatic creation of shadow databases is disabled on Azure SQL for example. Prisma Migrate throws the following error if it cannot create the shadow database with the credentials your connection URL supplied: @@ -122,6 +141,7 @@ Database error: Error querying the database: db error: ERROR: permission denied To resolve this error: - If you are working locally, we recommend that you update the database user's privileges. +- If you are developing against a database that does not allow creating and dropping databases (for any reason) see [Manually configuring the shadow database](#manually-configuring-the-shadow-database) - If you are developing against a cloud-based database (for example, on Heroku, Digital Ocean, or Vercel Postgres) see: [Cloud-hosted shadow databases](#cloud-hosted-shadow-databases-must-be-created-manually). - If you are developing against a cloud-based database (for example, on Heroku, Digital Ocean, or Vercel Postgres) and are currently **prototyping** such that you don't care about generated migration files and only need to apply your Prisma data model to the database schema, you can run [`prisma db push`](/reference/api-reference/command-reference#db) instead of the `prisma migrate dev` command. From d22eaf947cc278276073eea47898fcb8ae9289bb Mon Sep 17 00:00:00 2001 From: Jeremy Cohen Hoffing Date: Fri, 17 Nov 2023 04:59:01 -0800 Subject: [PATCH 07/32] Add indexes to the explicit relations example (#4739) Co-authored-by: Nikolas --- .../200-working-with-many-to-many-relations.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/content/300-guides/500-other/880-troubleshooting-orm/100-help-articles/200-working-with-many-to-many-relations.mdx b/content/300-guides/500-other/880-troubleshooting-orm/100-help-articles/200-working-with-many-to-many-relations.mdx index 1383f4a2d3..a20509a2df 100644 --- a/content/300-guides/500-other/880-troubleshooting-orm/100-help-articles/200-working-with-many-to-many-relations.mdx +++ b/content/300-guides/500-other/880-troubleshooting-orm/100-help-articles/200-working-with-many-to-many-relations.mdx @@ -98,6 +98,8 @@ model PostTags { tag Tag? @relation(fields: [tagId], references: [id]) postId Int? tagId Int? + + @@index([postId, tagId]) } model Tag { From a2ca8ae6a167e3dfc1905f472f2041fcf34bd21c Mon Sep 17 00:00:00 2001 From: Nikolas Date: Fri, 17 Nov 2023 14:57:55 +0100 Subject: [PATCH 08/32] Update 100-soft-delete-middleware.mdx (#5470) --- .../054-middleware/100-soft-delete-middleware.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/02-prisma-client/054-middleware/100-soft-delete-middleware.mdx b/content/200-concepts/100-components/02-prisma-client/054-middleware/100-soft-delete-middleware.mdx index 4039ac9d3b..d6c5d5e41c 100644 --- a/content/200-concepts/100-components/02-prisma-client/054-middleware/100-soft-delete-middleware.mdx +++ b/content/200-concepts/100-components/02-prisma-client/054-middleware/100-soft-delete-middleware.mdx @@ -658,7 +658,7 @@ Number of SOFT deleted posts: 95 ### Can I add a global includeDeleted to the Post model? -You may be tempted to 'hack' your API by adding a `includedDeleted` property to the `Post` model and make the following query possible: +You may be tempted to 'hack' your API by adding a `includeDeleted` property to the `Post` model and make the following query possible: ```ts prisma.post.findMany({ where: { includeDeleted: true } }) From 361207a721a75b2099ae6e1f19d2b329c037f9ed Mon Sep 17 00:00:00 2001 From: Jordan Becker Date: Fri, 17 Nov 2023 15:18:36 +0100 Subject: [PATCH 09/32] Update 058-transactions.mdx (#4614) Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> --- .../100-components/02-prisma-client/058-transactions.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/200-concepts/100-components/02-prisma-client/058-transactions.mdx b/content/200-concepts/100-components/02-prisma-client/058-transactions.mdx index 4050b98c6a..ed181f4cc1 100644 --- a/content/200-concepts/100-components/02-prisma-client/058-transactions.mdx +++ b/content/200-concepts/100-components/02-prisma-client/058-transactions.mdx @@ -202,8 +202,8 @@ Alice is expected to be able to make 1 transfer for $100 while the other transfe import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() -async function transfer(from: string, to: string, amount: number) { - return await prisma.$transaction(async (tx) => { +function transfer(from: string, to: string, amount: number) { + return prisma.$transaction(async (tx) => { // 1. Decrement amount from the sender. const sender = await tx.account.update({ data: { From 755cfaa86c379045bab2736ccb926a5e1e009181 Mon Sep 17 00:00:00 2001 From: Nurul Sundarani Date: Fri, 17 Nov 2023 19:54:53 +0530 Subject: [PATCH 10/32] Add Example for `now()` attribute function (#4760) Co-authored-by: Nikolas --- .../100-prisma-schema-reference.mdx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx index f57ed24776..0f926bb7ec 100644 --- a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx +++ b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx @@ -3234,6 +3234,34 @@ Set a timestamp of the time when a record is created. - Implemented at Prisma level +#### Examples + +##### Set current timestamp value when a record is created + +, ]}> + + +```prisma +model User { + id String @id + createdAt DateTime @default(now()) +} +``` + + + + +```prisma +model User { + id String @id @default(auto()) @map("_id") @db.ObjectId + createdAt DateTime @default(now()) +} +``` + + + + + ### dbgenerated() Represents **default values** that cannot be expressed in the Prisma schema (such as `random()`). From 224929d0f473d4f79b0a4573f56baeb4233930e6 Mon Sep 17 00:00:00 2001 From: Zach Tilev <103522279+zachtil@users.noreply.github.com> Date: Fri, 17 Nov 2023 16:39:35 +0200 Subject: [PATCH 11/32] Separate open source from hosted supported databases in reference table (#3894) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jan Piotrowski Co-authored-by: Zach Tilev Co-authored-by: Joël Galeran Co-authored-by: Nilufar Bava Co-authored-by: Nikolas --- .../03-supported-databases.mdx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/content/400-reference/300-database-reference/03-supported-databases.mdx b/content/400-reference/300-database-reference/03-supported-databases.mdx index 600dc84e67..a0f4284210 100644 --- a/content/400-reference/300-database-reference/03-supported-databases.mdx +++ b/content/400-reference/300-database-reference/03-supported-databases.mdx @@ -21,17 +21,22 @@ Prisma currently supports the following databases: | MySQL | 5.7 | | MySQL | 8 | | MariaDB | 10 | -| PlanetScale | \* | | SQLite | \* | -| AWS Aurora | \* | -| AWS Aurora Serverless ¹ | \* | -| Microsoft SQL Server | 2022 | -| Microsoft SQL Server | 2019 | | Microsoft SQL Server | 2017 | -| Azure SQL | \* | +| Microsoft SQL Server | 2019 | +| Microsoft SQL Server | 2022 | | MongoDB | 4.2+ | | CockroachDB | 21.2.4+ | +## Managed databases + +| PlanetScale | \* | +| AWS Aurora | \* | +| AWS Aurora Serverless ¹ | \* | +| Azure SQL | \* | +| CockroachDB-as-a-Service | \* | +| MongoDB Atlas | \* | + Note that a fixed version of SQLite is shipped with every Prisma release. An asterisk (\*) indicates that the version number is not relevant; either all versions are supported, there is not a public version number, etc. @@ -48,7 +53,7 @@ Support for the following databases is available as a Preview: | Database | Version | | ----------- | ------- | -| PlanetScale | \* | +| foo | \* | --> From 6ba30201bf6b8fbf6e0ab526be1e13005d2b2d36 Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Fri, 17 Nov 2023 16:09:57 +0100 Subject: [PATCH 12/32] docs: add content on introspection warnings (#5461) Co-authored-by: Nikolas --- .../100-components/04-introspection.mdx | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/04-introspection.mdx b/content/200-concepts/100-components/04-introspection.mdx index f0d6880f20..288be7bf86 100644 --- a/content/200-concepts/100-components/04-introspection.mdx +++ b/content/200-concepts/100-components/04-introspection.mdx @@ -357,4 +357,42 @@ 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](prisma-client/working-with-prismaclient/generating-prisma-client), you can add the [`@@ignore` attribute](../../reference/api-reference/prisma-schema-reference#ignore-1) to the model definition in your Prisma schema. Ignored models are excluded from the generated Prisma Client. +If your goal is to exclude certain models from the [Prisma Client generation](prisma-client/working-with-prismaclient/generating-prisma-client), you can add the [`@@ignore` attribute](/reference/api-reference/prisma-schema-reference#ignore-1) to the model definition in your Prisma schema. Ignored models are excluded from the generated Prisma Client. + +## Introspection warnings for unsupported features + +The Prisma Schema Language (PSL) can express a majority of the database features of the [target databases](/reference/database-reference/supported-databases) Prisma supports. However, there are features and functionality the Prisma Schema Language still needs to express. + +For these features, the Prisma CLI will surface detect usage of the feature in your database and return a warning. The Prisma CLI will also add a comment in the models and fields the features are in use in the Prisma schema. The warnings will also contain a workaround suggestion. + +The `prisma db pull` command will surface the following unsupported features: + +- From version [4.13.0](https://github.com/prisma/prisma/releases/tag/4.13.0): + - [Partitioned tables](https://github.com/prisma/prisma/issues/1708) + - [PostgreSQL Row Level Security](https://github.com/prisma/prisma/issues/12735) + - [Index sort order, `NULLS FIRST` / `NULLS LAST`](https://github.com/prisma/prisma/issues/15466) + - [CockroachDB row-level TTL](https://github.com/prisma/prisma/issues/13982) + - [Comments](https://github.com/prisma/prisma/issues/8703) + - [PostgreSQL deferred constraints](https://github.com/prisma/prisma/issues/8807) +- From version [4.14.0](https://github.com/prisma/prisma/releases/tag/4.14.0): + - [Check Constraints](https://github.com/prisma/prisma/issues/3388) (MySQL + PostgreSQL) + - [Exclusion Constraints](https://github.com/prisma/prisma/issues/17514) + - [MongoDB $jsonSchema](https://github.com/prisma/prisma/issues/8135) +- From version [4.16.0](https://github.com/prisma/prisma/releases/tag/4.16.0): + - [Expression indexes](https://github.com/prisma/prisma/issues/2504) + +You can find the list of features we intend to support on [GitHub (labeled with `topic:database-functionality`)](https://github.com/prisma/prisma/issues?q=is%3Aopen+label%3A%22topic%3A+database-functionality%22+label%3Ateam%2Fschema+sort%3Aupdated-desc+). + +### Workaround for introspection warnings for unsupported features + +If you are using a relational database and either one of the above features listed in the previous section: + +1. Create a draft migration: + ```terminal + npx prisma migrate dev --create-only + ``` +2. Add the SQL that adds the feature surfaced in the warnings. +3. Apply the draft migration to your database: + ```terminal + npx prisma migrate dev + ``` From 6f2548164fc48e26450b66a087e3384943e5d633 Mon Sep 17 00:00:00 2001 From: Tasin Ishmam Date: Fri, 17 Nov 2023 21:29:52 +0600 Subject: [PATCH 13/32] Add documentation on prepared statement caching (#4648) Co-authored-by: Jan Piotrowski Co-authored-by: Nikolas --- .../200-database-connectors/03-postgresql.mdx | 60 +++++++++++++------ 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/content/200-concepts/200-database-connectors/03-postgresql.mdx b/content/200-concepts/200-database-connectors/03-postgresql.mdx index e1d6e77d08..96f2889c1e 100644 --- a/content/200-concepts/200-database-connectors/03-postgresql.mdx +++ b/content/200-concepts/200-database-connectors/03-postgresql.mdx @@ -70,23 +70,24 @@ postgresql://USER:PASSWORD@HOST:PORT/DATABASE?KEY1=VALUE&KEY2=VALUE&KEY3=VALUE The following arguments can be used: -| Argument name | Required | Default | Description | -| :----------------- | :------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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](/concepts/components/prisma-client/working-with-prismaclient/connection-pool) | -| `connect_timeout` | No | `5` | Maximum number of seconds to wait for a new connection to be opened, `0` means no timeout | -| `pool_timeout` | No | `10` | Maximum number of seconds to wait for a new connection from the pool, `0` means no timeout | -| `sslmode` | No | `prefer` | Configures whether to use TLS. Possible values: `prefer`, `disable`, `require` | -| `sslcert` | No | | Path of the server certificate. Certificate paths are [resolved relative to the `./prisma folder`](/concepts/components/prisma-schema/data-sources#securing-database-connections) | -| `sslidentity` | No | | Path to the PKCS12 certificate | -| `sslpassword` | No | | Password that was used to secure the PKCS12 file | -| `sslaccept` | No | `accept_invalid_certs` | Configures whether to check for missing values in the certificate. Possible values: `accept_invalid_certs`, `strict` | -| `host` | No | | Points to a directory that contains a socket to be used for the connection | -| `socket_timeout` | No | | Maximum number of seconds to wait until a single query terminates | -| `pgbouncer` | No | `false` | Configure the Engine to [enable PgBouncer compatibility mode](/guides/performance-and-optimization/connection-management/configure-pg-bouncer) | -| `application_name` | No | | Since 3.3.0: Specifies a value for the application_name configuration parameter | -| `channel_binding` | No | `prefer` | Since 4.8.0: Specifies a value for the channel_binding configuration parameter | -| `options` | No | | Since 3.8.0: Specifies command line options to send to the server at connection start | +| Argument name | Required | Default | Description | +| :--------------------- | :------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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](/concepts/components/prisma-client/working-with-prismaclient/connection-pool) | +| `connect_timeout` | No | `5` | Maximum number of seconds to wait for a new connection to be opened, `0` means no timeout | +| `pool_timeout` | No | `10` | Maximum number of seconds to wait for a new connection from the pool, `0` means no timeout | +| `sslmode` | No | `prefer` | Configures whether to use TLS. Possible values: `prefer`, `disable`, `require` | +| `sslcert` | No | | Path of the server certificate. Certificate paths are [resolved relative to the `./prisma folder`](/concepts/components/prisma-schema/data-sources#securing-database-connections) | +| `sslidentity` | No | | Path to the PKCS12 certificate | +| `sslpassword` | No | | Password that was used to secure the PKCS12 file | +| `sslaccept` | No | `accept_invalid_certs` | Configures whether to check for missing values in the certificate. Possible values: `accept_invalid_certs`, `strict` | +| `host` | No | | Points to a directory that contains a socket to be used for the connection | +| `socket_timeout` | No | | Maximum number of seconds to wait until a single query terminates | +| `pgbouncer` | No | `false` | Configure the Engine to [enable PgBouncer compatibility mode](/guides/performance-and-optimization/connection-management/configure-pg-bouncer) | +| `statement_cache_size` | No | `500` | Since 2.1.0: Specifies the number of [prepared statements](#prepared-statement-caching) cached per connection | +| `application_name` | No | | Since 3.3.0: Specifies a value for the application_name configuration parameter | +| `channel_binding` | No | `prefer` | Since 4.8.0: Specifies a value for the channel_binding configuration parameter | +| `options` | No | | Since 3.8.0: Specifies command line options to send to the server at connection start | As an example, if you want to connect to a schema called `myschema`, set the connection pool size to `5` and configure a timeout for queries of `3` seconds. You can use the following arguments: @@ -214,3 +215,28 @@ model Device { data Unsupported("circle") } ``` + +## Prepared statement caching + +A [prepared statement](https://www.postgresql.org/docs/current/sql-prepare.html) is a feature that can be used to optimize performance. A prepared statement is parsed, compiled, and optimized only once and then can be executed directly multiple times without the overhead of parsing the query again. + +By caching prepared statements, Prisma Client's [query engine](https://www.prisma.io/docs/concepts/components/prisma-engines/query-engine) does not repeatedly compile the same query which reduces database CPU usage and query latency. + + +For example, here is the generated SQL for two different queries made by Prisma Client: + +```sql +SELECT * FROM user WHERE name = "John"; +SELECT * FROM user WHERE name = "Brenda"; +``` + +The two queries after parameterization will be the same, and the second query can skip the preparing step, saving database CPU and one extra roundtrip to the database. Query after parameterization: + +```sql +SELECT * FROM user WHERE name = $1 +``` + + +Every database connection maintained by Prisma has a separate cache for storing prepared statements. The size of this cache can be tweaked with the `statement_cache_size` parameter in the connection string. By default, Prisma Client caches 500 statements per connection. + +Due to the nature of pgBouncer, if the `pgbouncer` parameter is set to `true`, the prepared statement cache is automatically disabled for that connection. From 5bf9aa35f69e875914c325cda5041752e8089467 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Rudge?= Date: Fri, 17 Nov 2023 08:37:53 -0700 Subject: [PATCH 14/32] Update prisma-generator-fake-data text (#5471) --- .../100-components/01-prisma-schema/03-generators.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx b/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx index 503185a232..51a192d22f 100644 --- a/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx +++ b/content/200-concepts/100-components/01-prisma-schema/03-generators.mdx @@ -95,5 +95,5 @@ The following is a list of community created generators. If you want to create y - [`prisma-generator-graphql-typedef`](https://github.com/mavvy22/prisma-generator-graphql-typedef): Generates graphql schema. - [`prisma-markdown`](https://github.com/samchon/prisma-markdown): Generates markdown document composed with ERD diagrams and their descriptions. Supports pagination of ERD diagrams through `@namespace` comment tag. - [`prisma-models-graph`](https://github.com/dangchinh25/prisma-models-graph): Generates a bi-directional models graph for schema without strict relationship defined in the schema, works via a custom schema annotation. -- [`https://github.com/luisrudge/prisma-generator-fake-data`](https://github.com/luisrudge/prisma-generator-fake-data): Generates realistic-looking fake data for your Prisma models that can be used in unit/integration tests, demos, and more. +- [`prisma-generator-fake-data`](https://github.com/luisrudge/prisma-generator-fake-data): Generates realistic-looking fake data for your Prisma models that can be used in unit/integration tests, demos, and more. From cc7fd2f3c56f909e7b338f00bb097f5cfcdf5145 Mon Sep 17 00:00:00 2001 From: Nikolas Date: Fri, 17 Nov 2023 21:21:02 +0100 Subject: [PATCH 15/32] docs: update landing page for getting started (#5468) Co-authored-by: meletj <70962362+meletj@users.noreply.github.com> --- content/100-getting-started/index.mdx | 54 ++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/content/100-getting-started/index.mdx b/content/100-getting-started/index.mdx index 899e9a1a48..62dc3d4d22 100644 --- a/content/100-getting-started/index.mdx +++ b/content/100-getting-started/index.mdx @@ -6,27 +6,29 @@ metaDescription: 'Get started' -Welcome to the Prisma getting started section! 👋 Prisma is an [open source](https://github.com/prisma/prisma) next-generation ORM. It consists of the following parts: +Welcome to the Prisma getting started section! 👋 -- [**Prisma Client**](/concepts/components/prisma-client): Auto-generated and type-safe query builder for Node.js & TypeScript -- [**Prisma Migrate**](/concepts/components/prisma-migrate): Migration tool to easily evolve your database schema from prototyping to production -- [**Prisma Studio**](/concepts/components/prisma-studio): GUI to view and edit data in your database +Explore our range of products defined to make working with data easy: -Prisma is also available on the [Prisma Data Platform](https://console.prisma.io), a cloud-based, collaborative environment for teams and organizations to develop type-safe applications. The platform focuses on developer productivity with GitHub integration for your code and schema, a visual data browser, an online query console, and an optional data proxy for handling database connections. For more information, refer to the Prisma Data Platform [documentation](/data-platform). +[**Prisma ORM**](/concepts/overview/what-is-prisma) is an [open source](https://github.com/prisma/prisma) next-generation database toolkit that helps with data modeling, data access, schema migrations and more. -For a more detailed breakdown of what problems Prisma solves and why it's **built to make you more productive**, see the [Why Prisma](/concepts/overview/why-prisma) section. +[**Prisma Accelerate**](/data-platform/accelerate/what-is-accelerate) is a global database cache with scalable connection pooling. + +[**Prisma Pulse**](/data-platform/pulse/what-is-pulse) allows you to build reactive, real-time applications in a type-safe manner. ## Which tutorial is right for me? -To get up and running with Prisma in your local environment, follow our [Quickstart guide](./quickstart). It makes no assumptions about your knowledge level and offers the **fastest** way from install to query! +### Get started with Prisma ORM + +To get up and running with Prisma in your local environment, follow our Quickstart guide It makes no assumptions about your knowledge level and offers the **fastest** way from install to query! Quickstart -If you're looking to incorporate Prisma with an **existing project**, choose whether you want to use a SQL database or MongoDB: +If you're looking to incorporate Prisma with an **existing project**, choose whether you want to use a SQL database or MongoDB. -To learn how to **create a project** with Prisma from scratch, choose between SQL and MongoDB. Both tutorials will guide you through creating a project, connecting your database, and querying your data. +To learn how to **create a new project** with Prisma from scratch, choose between SQL and MongoDB. Both tutorials will guide you through creating a project, connecting your database, and querying your data. +If you're interested in learning how Prisma integrates with your favorite library or framework, such as Next.js, Express, Apollo GraphQL, NestJS, etc, you can check out our **ready-to-run examples**. + + + Examples + + +### Get started with Prisma Accelerate + +Add **Accelerate** to your app to use connection pooling and global database caching. + + + Get started with Accelerate + + +### Get started with Prisma Pulse + +Add **Pulse** to your app to subscribe to real-time updates from your database using Prisma Client. + + + Get started with Pulse + + ## Prisma with different tooling Prisma can be used with a wide range of tooling and frameworks, the following links outline how to get started with some of them: From fde141db653bccf3365aeecc1f2b40f8f68e673f Mon Sep 17 00:00:00 2001 From: Nikolas Date: Mon, 20 Nov 2023 10:45:06 +0100 Subject: [PATCH 16/32] Update 03-supported-databases.mdx (#5474) --- .../03-supported-databases.mdx | 21 +++++++------------ 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/content/400-reference/300-database-reference/03-supported-databases.mdx b/content/400-reference/300-database-reference/03-supported-databases.mdx index a0f4284210..a1ece2fc64 100644 --- a/content/400-reference/300-database-reference/03-supported-databases.mdx +++ b/content/400-reference/300-database-reference/03-supported-databases.mdx @@ -6,7 +6,11 @@ metaDescription: 'This page lists all the databases and their versions that are -Prisma currently supports the following databases: +Prisma currently supports the following databases. + + + +## Self-hosted databases | Database | Version | | ---------------------------- | ------- | @@ -30,6 +34,8 @@ Prisma currently supports the following databases: ## Managed databases +| Database | Version | +| ---------------------------- | ------- | | PlanetScale | \* | | AWS Aurora | \* | | AWS Aurora Serverless ¹ | \* | @@ -43,18 +49,5 @@ An asterisk (\*) indicates that the version number is not relevant; either all v ¹ This does not include support for [Data API for Aurora Serverless](https://github.com/prisma/prisma/issues/1964). - - - See also: [System requirements](/reference/system-requirements) From 414a16e7e4f84b65d051f5f27cda3338c2a76508 Mon Sep 17 00:00:00 2001 From: Pavel Savchenko Date: Mon, 20 Nov 2023 09:54:00 +0000 Subject: [PATCH 17/32] docs(db-push): clarify the migration table note (#5130) --- .../100-components/03-prisma-migrate/150-db-push.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/03-prisma-migrate/150-db-push.mdx b/content/200-concepts/100-components/03-prisma-migrate/150-db-push.mdx index 6a9400bf91..020230babe 100644 --- a/content/200-concepts/100-components/03-prisma-migrate/150-db-push.mdx +++ b/content/200-concepts/100-components/03-prisma-migrate/150-db-push.mdx @@ -20,7 +20,7 @@ The Prisma CLI has a dedicated command for prototyping schemas: [`db push`](/ref > **Notes**: > -> - `db push` does not interact with or rely on migrations. The migrations table will not be updated, and no migration files will be generated. +> - `db push` does not interact with or rely on migrations. The migrations table `_prisma_migrations` will not be created or updated, and no migration files will be generated. > - When working with PlanetScale, we recommend that you use `db push` instead of `migrate`. For details refer to our Getting Started documentation, either [Start from scratch](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-planetscale) or [Add to existing project](/getting-started/setup-prisma/add-to-existing-project/relational-databases-typescript-planetscale) depending on your situation. From 976d1c8bea722927b778d3cbe54f3df689404c14 Mon Sep 17 00:00:00 2001 From: Vaibhav Dangra Date: Mon, 20 Nov 2023 15:45:27 +0530 Subject: [PATCH 18/32] fix: broken link (#4676) From 8ff58bdca4d560ce9d52a8c8d5070dcfbac54781 Mon Sep 17 00:00:00 2001 From: Olivier Lacan Date: Mon, 20 Nov 2023 06:43:24 -0500 Subject: [PATCH 19/32] Offer clear field @map example (#5473) --- .../200-api-reference/100-prisma-schema-reference.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx index 0f926bb7ec..660aab63ed 100644 --- a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx +++ b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx @@ -385,7 +385,7 @@ model User { - Typically spelled in camelCase - Must adhere to the following regular expression: `[A-Za-z][A-Za-z0-9_]*` -> **Note**: You can use the [`@map` attribute](#map) to map a field name (for example, `MyField`) to a column with a different name that does not match field naming conventions (for example, `myField`). +> **Note**: You can use the [`@map` attribute](#map) to [map a field name to a column](/concepts/components/prisma-client/working-with-prismaclient/use-custom-model-and-field-names) with a different name that does not match field naming conventions: e.g. `myField @map("my_field")`. ## model field scalar types From 781284c72fa6bd82c23f6009910ee859db2c2bb0 Mon Sep 17 00:00:00 2001 From: Olivier Lacan Date: Mon, 20 Nov 2023 06:43:56 -0500 Subject: [PATCH 20/32] Fix typo in Order of Fields section (#5472) --- .../200-api-reference/100-prisma-schema-reference.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx index 660aab63ed..e97e3fc2bb 100644 --- a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx +++ b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx @@ -343,7 +343,7 @@ Defines a Prisma [model](/concepts/components/prisma-schema/data-model#defining- #### Order of fields -- In version 2.3.0 and later, introspection lists model fields same order as the corresponding columns in the database. Relation fields are listed after scalar fields. +- In version 2.3.0 and later, introspection lists model fields in the same order as the corresponding columns in the database. Relation fields are listed after scalar fields. ### Examples From 0b82cc8970d2c141c1a01b14511a83bee2e08ccd Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Mon, 20 Nov 2023 18:29:12 +0100 Subject: [PATCH 21/32] add `prisma-paginate` extension to docs (#5469) --- .../053-client-extensions/200-extension-examples.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx b/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx index 7b105ffe7f..c3cce06400 100644 --- a/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx +++ b/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx @@ -27,6 +27,7 @@ The following is a list of extensions created by the community. If you want to c | [`prisma-extension-caching`](https://github.com/isaev-the-poetry/prisma-extension-caching) | Transforms SQL data from queries in streams to improve performance in larger datasets | | [`prisma-extension-cache-manager`](https://github.com/random42/prisma-extension-cache-manager) | Caches model queries with any [cache-manager](https://www.npmjs.com/package/cache-manager) compatible cache | | [`prisma-extension-random`](https://github.com/nkeil/prisma-extension-random) | Lets you query for random rows in your database | +| [`prisma-paginate](https://github.com/sandrewTx08/prisma-paginate) | Adds support for paginating read queries | If you have built an extension and would like to see it featured, feel free to add it to the list by opening a pull request. From b3f9adf9dcc11b255cc301814966bd7d97ffe6bf Mon Sep 17 00:00:00 2001 From: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Date: Mon, 20 Nov 2023 18:32:44 +0100 Subject: [PATCH 22/32] add missing backtick (#5478) --- .../053-client-extensions/200-extension-examples.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx b/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx index c3cce06400..4f9cf7b8a3 100644 --- a/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx +++ b/content/200-concepts/100-components/02-prisma-client/053-client-extensions/200-extension-examples.mdx @@ -27,7 +27,7 @@ The following is a list of extensions created by the community. If you want to c | [`prisma-extension-caching`](https://github.com/isaev-the-poetry/prisma-extension-caching) | Transforms SQL data from queries in streams to improve performance in larger datasets | | [`prisma-extension-cache-manager`](https://github.com/random42/prisma-extension-cache-manager) | Caches model queries with any [cache-manager](https://www.npmjs.com/package/cache-manager) compatible cache | | [`prisma-extension-random`](https://github.com/nkeil/prisma-extension-random) | Lets you query for random rows in your database | -| [`prisma-paginate](https://github.com/sandrewTx08/prisma-paginate) | Adds support for paginating read queries | +| [`prisma-paginate`](https://github.com/sandrewTx08/prisma-paginate) | Adds support for paginating read queries | If you have built an extension and would like to see it featured, feel free to add it to the list by opening a pull request. From 73a275e5d8aef3f6b35280f67c81c3546a6c8414 Mon Sep 17 00:00:00 2001 From: Alberto Schiabel Date: Mon, 20 Nov 2023 19:54:26 +0100 Subject: [PATCH 23/32] feat: update "binaryTargets" reference for Linux Alpine arm64 (#4491) Co-authored-by: Nikolas Co-authored-by: Jan Piotrowski --- .../100-prisma-schema-reference.mdx | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx index e97e3fc2bb..3ee62fe8a7 100644 --- a/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx +++ b/content/400-reference/200-api-reference/100-prisma-schema-reference.mdx @@ -176,12 +176,14 @@ A `generator` block accepts the following fields: The following tables list all supported operating systems with the name of platform to specify in [`binaryTargets`](/concepts/components/prisma-schema/generators#binary-targets). +Unless specified otherwise, the default supported CPU architecture is x86_64. + ##### macOS -| Build OS | Prisma engine build name | -| :-------------- | :----------------------- | -| macOS Intel x86 | `darwin` | -| macOS ARM64 | `darwin-arm64` | +| Build OS | Prisma engine build name | +| :----------------- | :----------------------- | +| macOS Intel x86_64 | `darwin` | +| macOS ARM64 | `darwin-arm64` | ##### Windows @@ -189,18 +191,23 @@ The following tables list all supported operating systems with the name of platf | :------- | :----------------------- | | Windows | `windows` | -##### Linux (Alpine) +##### Linux (Alpine on x86_64 architectures) -| Build OS | Prisma engine build name | OpenSSL | -| :------------------------------ | :----------------------------------- | :-----: | -| Alpine (3.16 and older), x86_64 | `linux-musl` | 1.1.x | -| Alpine (3.17 and newer), x86_64 | `linux-musl-openssl-3.0.x`\* | 3.0.x | -| Alpine (3.16 and older), ARM64 | `linux-musl-arm64-openssl-1.1.x`\*\* | 1.1.x | -| Alpine (3.17 and newer), ARM64 | `linux-musl-arm64-openssl-3.0.x`\*\* | 3.0.x | +| Build OS | Prisma engine build name | OpenSSL | +| :------------------ | :--------------------------- | :-----: | +| Alpine (3.17 and newer) | `linux-musl-openssl-3.0.x`\* | 3.0.x | +| Alpine (3.16 and older) | `linux-musl` | 1.1.x | \* Available in Prisma versions 4.8.0 and later. -\*\* Available in Prisma versions 4.10.0 and later. +##### Linux (Alpine on ARM64 architectures) + +| Build OS | Prisma engine build name | OpenSSL | +| :------------------ | :--------------------------------- | :-----: | +| Alpine (3.17 and newer) | `linux-musl-arm64-openssl-3.0.x`\* | 3.0.x | +| Alpine (3.16 and older) | `linux-musl-arm64-openssl-1.1.x`\* | 1.1.x | + +\* Available in Prisma versions 4.10.0 and later. ##### Linux (Debian), x86_64 @@ -259,7 +266,7 @@ The following tables list all supported operating systems with the name of platf | Arch Linux 2019.09.01 | `debian-openssl-1.1.x` | 1.1.x | | Arch Linux 2023.04.23 | `debian-openssl-3.0.x` | 3.0.x | -##### Linux (most distributions except Alpine), ARM64 +##### Linux ARM64 (all major distros but Alpine) | Build OS | Prisma engine build name | OpenSSL | | :----------------------------- | :-------------------------- | :-----: | From 0aa628c591dfbf7cfc86370ec429cf57e142331e Mon Sep 17 00:00:00 2001 From: Jan Piotrowski Date: Mon, 20 Nov 2023 20:06:21 +0100 Subject: [PATCH 24/32] docs(environment-variables): Rework section (#2186) Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Co-authored-by: Nikolas --- .../040-env-files.mdx | 93 +++++++++++++++++++ .../050-environment-variables/index.mdx | 88 +----------------- 2 files changed, 95 insertions(+), 86 deletions(-) create mode 100644 content/300-guides/125-development-environment/050-environment-variables/040-env-files.mdx diff --git a/content/300-guides/125-development-environment/050-environment-variables/040-env-files.mdx b/content/300-guides/125-development-environment/050-environment-variables/040-env-files.mdx new file mode 100644 index 0000000000..94d6acac28 --- /dev/null +++ b/content/300-guides/125-development-environment/050-environment-variables/040-env-files.mdx @@ -0,0 +1,93 @@ +--- +title: '.env files' +metaTitle: '.env files' +metaDescription: 'Configure environment variables using .env files in Prisma' +--- + + + +Prisma creates a default `.env` file at your projects root. You can choose to replace this file or create a new one in the `prisma` folder, or if you choose to relocate your `prisma.schema` file, alongside that. + + + +### .env file locations + +The Prisma CLI looks for `.env` files, in order, in the following locations: + +1. In the root folder of your project (`./.env`) +1. From the same folder as the schema specified by the `--schema` argument +1. From the same folder as the schema taken from `"prisma": {"schema": "/path/to/schema.prisma"}` in `package.json` +1. From the `./prisma` folder + +If a `.env` file is located in step 1., but additional, clashing `.env` variables are located in steps 2. - 4., the CLI will throw an error. For example, if you specify a `DATABASE_URL` variable in two different `.env` files, you will get the following error: + +``` +Error: There is a conflict between env vars in .env and prisma/.env +Conflicting env vars: + DATABASE_URL + +We suggest to move the contents of prisma/.env to .env to consolidate your env vars. +``` + +The following table describes where the Prisma CLI looks for the `.env` file: + +| **Command** | **Schema file location** | **`.env` file locations checked, in order** | +| :---------------------------------------------- | :--------------------------------------------------------------------------- | :-------------------------------------------------------- | +| `prisma [command]` | `./prisma/schema.prisma` | `./.env`
`./prisma/.env` | +| `prisma [command] --schema=./a/b/schema.prisma` | `./a/b/schema.prisma` | `./.env`
`./a/b/.env`
`./prisma/.env` | +| `prisma [command]` | `"prisma": {"schema": "/path/to/schema.prisma"}` | `.env`
`./path/to/schema/.env`
`./prisma/.env` | +| `prisma [command]` | No schema (for example, when running `prisma db pull` in an empty directory) | `./.env`
`./prisma/.env` | + +Any environment variables defined in that `.env` file will automatically be loaded when running a Prisma CLI command. + + + +**Do not commit your `.env` files into version control**! + + + +Refer to the `dotenv` documentation for information about [what happens if an environment variable is defined in two places](https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set). + +### Expanding variables + +Variables stored in `.env` files can be expanded using the format specified by [dotenv-expand](https://github.com/motdotla/dotenv-expand). + +```env file=.env +DATABASE_URL=postgresql://test:test@localhost:5432/test +DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=public +``` + +This will make the environment variable `DATABASE_URL_WITH_SCHEMA` with value `postgresql://test:test@localhost:5432/test?schema=public` available for Prisma. + +You can also use environment variables in the expansion that are set _outside_ of the `.env` file, for example a database URL that is set on a PaaS like Heroku or similar: + +```terminal +# environment variable already set in the environment of the system +export DATABASE_URL=postgresql://test:test@localhost:5432/test +``` + +```env file=.env +DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=foo +``` + +This will make the environment variable `DATABASE_URL_WITH_SCHEMA` with value `postgresql://test:test@localhost:5432/test?schema=foo` available for Prisma. + +### Example: Set the `DATABASE_URL` environment variable in an `.env` file + +It is common to load your database connection URL from an environment variable: + +```prisma +// schema.prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +You can set the `DATABASE_URL` in your `.env` file: + +```env file=.env +DATABASE_URL=postgresql://test:test@localhost:5432/test?schema=public +``` + +When you run a command that needs access to the database defined via the `datasource` block (for example, `prisma db pull`), the Prisma CLI automatically loads the `DATABASE_URL` environment variables from the `.env` file and makes it available to the CLI. diff --git a/content/300-guides/125-development-environment/050-environment-variables/index.mdx b/content/300-guides/125-development-environment/050-environment-variables/index.mdx index 1842b44ca8..f622c24bcd 100644 --- a/content/300-guides/125-development-environment/050-environment-variables/index.mdx +++ b/content/300-guides/125-development-environment/050-environment-variables/index.mdx @@ -19,6 +19,8 @@ The environment variable belongs to the environment where a process is running. Taking the `TEMP` environment variable as an example, one can query its value to find where to store temporary files. This is a system environment variable and can be queried by any process or application running on the machine. +Any program can read and create these environment variables. They are a cheap and effective way to store simple information. + ## How does Prisma use environment variables? @@ -33,92 +35,6 @@ Looking to use more than one `.env` file? See [Using multiple `.env` files](./us
-## Using .env files - -Prisma creates a default `.env` file at your projects root. You can choose to replace this file or create a new one in the `prisma` folder, or if you choose to relocate your `schema.prisma` file, alongside that. - -### `.env` file locations - -The Prisma CLI looks for `.env` files, in order, in the following locations: - -1. In the root folder of your project (`./.env`) -1. From the same folder as the schema specified by the `--schema` argument -1. From the same folder as the schema taken from `"prisma": {"schema": "/path/to/schema.prisma"}` in `package.json` -1. From the `./prisma` folder - -If a `.env` file is located in step #1, but additional, clashing `.env` variables are located in steps #2 - 4, the CLI will throw an error. For example, if you specify a `DATABASE_URL` variable in two different `.env` files, you will get the following error: - -``` -Error: There is a conflict between env vars in .env and prisma/.env -Conflicting env vars: - DATABASE_URL - -We suggest to move the contents of prisma/.env to .env to consolidate your env vars. -``` - -The following table describes where the Prisma CLI looks for the `.env` file: - -| **Command** | **Schema file location** | **`.env` file locations checked, in order** | -| :---------------------------------------------- | :--------------------------------------------------------------------------- | :-------------------------------------------------------- | -| `prisma [command]` | `./prisma/schema.prisma` | `./.env`
`./prisma/.env` | -| `prisma [command] --schema=./a/b/schema.prisma` | `./a/b/schema.prisma` | `./.env`
`./a/b/.env`
`./prisma/.env` | -| `prisma [command]` | `"prisma": {"schema": "/path/to/schema.prisma"}` | `.env`
`./path/to/schema/.env`
`./prisma/.env` | -| `prisma [command]` | No schema (for example, when running `prisma db pull` in an empty directory) | `./.env`
`./prisma/.env` | - -Any environment variables defined in that `.env` file will automatically be loaded when running a Prisma CLI command. - - - -**Do not commit your `.env` files into version control**! - - - -Refer to the `dotenv` documentation for information about [what happens if an environment variable is defined in two places](https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set). - -### Expanding variables - -Variables stored in `.env` files can be expanded using the format specified by [dotenv-expand](https://github.com/motdotla/dotenv-expand). - -```env file=.env -DATABASE_URL=postgresql://test:test@localhost:5432/test -DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=public -``` - -This will make the environment variable `DATABASE_URL_WITH_SCHEMA` with value `postgresql://test:test@localhost:5432/test?schema=public` available for Prisma. - -You can also use environment variables in the expansion that are set _outside_ of the `.env` file, for example a database URL that is set on a PaaS like Heroku or similar: - -```terminal -# environment variable already set in the environment of the system -export DATABASE_URL=postgresql://test:test@localhost:5432/test -``` - -```env file=.env -DATABASE_URL_WITH_SCHEMA=${DATABASE_URL}?schema=foo -``` - -This will make the environment variable `DATABASE_URL_WITH_SCHEMA` with value `postgresql://test:test@localhost:5432/test?schema=foo` available for Prisma. - -### Example: Set the `DATABASE_URL` environment variable in an `.env` file - -It is common to load your database connection URL from an environment variable: - -```prisma -// schema.prisma -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") -} -``` - -You can set the `DATABASE_URL` in your `.env` file: - -```env file=.env -DATABASE_URL=postgresql://test:test@localhost:5432/test?schema=public -``` - -When you run a command that needs access to the database defined via the `datasource` block (for example, `prisma db pull`), the Prisma CLI automatically loads the `DATABASE_URL` environment variables from the `.env` file and makes it available to the CLI. - ### Using environment variables in your code If you want environment variables to be evaluated at runtime, you need to load them manually in your application code (for example, by using [`dotenv`](https://github.com/motdotla/dotenv)): From 7e0428216517e55dc61a1cdf37bcff97699bca91 Mon Sep 17 00:00:00 2001 From: Jan Piotrowski Date: Mon, 20 Nov 2023 20:10:12 +0100 Subject: [PATCH 25/32] feat(multiSchema): Definition of relation table in multi schema cases + fixes (#4273) Co-authored-by: Nilufar Bava --- .../06-relations/300-many-to-many-relations.mdx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx b/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx index 4433a1735f..c46d607cd1 100644 --- a/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx +++ b/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx @@ -350,19 +350,23 @@ Implicit m-n relations: If you obtain your data model from [introspection](/concepts/components/introspection), you can still use implicit m-n-relations by following Prisma's [conventions for relation tables](#conventions-for-relation-tables-in-implicit-m-n-relations). The following example assumes you want to create a relation table to get an implicit m-n-relation for two models called `Post` and `Category`. -##### Table names +##### Relation table If you want a relation table to be picked up by introspection as an implicit m-n-relation, the name must follow this exact structure: - It must start with an underscore `_` -- Then the name of the first table in alphabetical order (in this case `Category`) +- Then the name of the first model in alphabetical order (in this case `Category`) - Then `To` -- Then the name of the second table in alphabetical order (in this case `Post`) +- Then the name of the second model in alphabetical order (in this case `Post`) In the example, the correct table name is `_CategoryToPost`. When creating an implicit m-n-relation yourself in the Prisma schema file, you can [configure the relation](#configuring-the-name-of-the-relation-table-in-implicit-many-to-many-relations) to have a different name. This will change the name given to the relation table in the database. For example, for a relation named `"MyRelation"` the corresponding table will be called `_MyRelation`. +###### Multi-schema + +If your implicit many-to-many relationship spans multiple database schemas (using the [`multiSchema` preview feature](/guides/database/multi-schema)), the relation table (with the name defined directly above, in the example `_CategoryToPost`) must be present in the same database schema as the first model in alphabetical order (in this case `Category`). + ##### Columns A relation table for an implicit m-n-relation must have exactly two columns: From 9ee6c8821f0d55154c1fbe622b2c3b9825dec950 Mon Sep 17 00:00:00 2001 From: Petra Donka Date: Tue, 21 Nov 2023 14:41:36 +0100 Subject: [PATCH 26/32] update ORM description on the Get Started page (#5480) --- content/100-getting-started/index.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/100-getting-started/index.mdx b/content/100-getting-started/index.mdx index 62dc3d4d22..3aa8f6e95d 100644 --- a/content/100-getting-started/index.mdx +++ b/content/100-getting-started/index.mdx @@ -10,7 +10,7 @@ Welcome to the Prisma getting started section! 👋 Explore our range of products defined to make working with data easy: -[**Prisma ORM**](/concepts/overview/what-is-prisma) is an [open source](https://github.com/prisma/prisma) next-generation database toolkit that helps with data modeling, data access, schema migrations and more. +[**Prisma ORM**](/concepts/overview/what-is-prisma) is an [open source](https://github.com/prisma/prisma) next-generation Node.js and TypeScript ORM that unlocks a new level of developer experience when working with databases thanks to its intuitive data model, automated migrations, type-safety & auto-completion. [**Prisma Accelerate**](/data-platform/accelerate/what-is-accelerate) is a global database cache with scalable connection pooling. From a3f1d0bcbd9caeb818e3a47bcb0ab3814e513bd0 Mon Sep 17 00:00:00 2001 From: Jon Harrell <4829245+jharrell@users.noreply.github.com> Date: Wed, 22 Nov 2023 02:13:59 -0600 Subject: [PATCH 27/32] Add guide for using SafeQL and extensions to help unsupported features. (#5419) Co-authored-by: Jan Piotrowski Co-authored-by: Alex Ruheni <33921841+ruheni@users.noreply.github.com> Co-authored-by: Nikolas --- .../06-typesafe-raw-sql/01-safeql.mdx | 369 ++++++++++++++++++ .../06-typesafe-raw-sql/index.mdx | 16 + 2 files changed, 385 insertions(+) create mode 100644 content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/01-safeql.mdx create mode 100644 content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/index.mdx diff --git a/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/01-safeql.mdx b/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/01-safeql.mdx new file mode 100644 index 0000000000..c4f1c69dfc --- /dev/null +++ b/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/01-safeql.mdx @@ -0,0 +1,369 @@ +--- +title: 'Create custom, type-safe Prisma Client queries for raw SQL' +metaTitle: 'Create custom, type-safe Prisma Client queries for raw SQL (Guide)' +metaDescription: 'Learn how to use SafeQL and Prisma Client extensions to work around features not natively supported by Prisma, such as PostGIS.' +--- + +## Overview + +This page explains how to improve the experience of writing raw SQL in Prisma ORM. It uses [Prisma Client extensions](/concepts/components/prisma-client/client-extensions) and [SafeQL](https://safeql.dev) to create custom, type-safe Prisma Client queries which abstract custom SQL that your app might need (using `$queryRaw`). + +The example will be using [PostGIS](https://postgis.net/) and PostgreSQL, but is applicable to any raw SQL queries that you might need in your application. + +## What is SafeQL? + +[SafeQL](https://safeql.dev/) allows for advanced linting and type safety within raw SQL queries. After setup, SafeQL works with Prisma `$queryRaw` and `$executeRaw` to provide type safety when raw queries are required. + +SafeQL runs as an [ESLint](https://eslint.org/) plugin and is configured using ESLint rules. This guide doesn't cover setting up ESLint and we will assume that you already having it running in your project. + +## Prerequisites + +To follow along, you will be expected to have: + +- A [PostgreSQL](https://www.postgresql.org/) database with PostGIS installed +- Prisma set up in your project +- ESLint set up in your project + +## Geographic data support in Prisma + +At the time of writing, Prisma does not support working with geographic data, specifically using [PostGIS](https://github.com/prisma/prisma/issues/2789). + +A model that has geographic data columns will be stored using the [`Unsupported`](/reference/api-reference/prisma-schema-reference#unsupported) data type. Fields with `Unsupported` types are present in the generated Prisma Client and will be typed as `any`. A model with a required `Unsupported` type does not expose write operations such as `create`, and `update`. + +Prisma supports write operations on models with a required `Unsupported` field using `$queryRaw` and `$executeRaw`. You can use Prisma Client extensions and SafeQL to improve the type-safety when working with geographical data in raw queries. + +## 1. Set up Prisma for use with PostGIS + +If you haven't already, enable the `postgresqlExtensions` Preview feature and add the `postgis` PostgreSQL extension in your Prisma schema: + +```prisma highlight=3,9;add +generator client { + provider = "prisma-client-js" + previewFeatures = ["postgresqlExtensions"] +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + extensions = [postgis] +} +``` + + + +If you are not using a hosted database provider, you will likely need to install the `postgis` extension. Refer to [PostGIS's docs](http://postgis.net/documentation/getting_started/#installing-postgis) to learn more about how to get started with PostGIS. If you're using Docker Compose, you can use the following snippet to set up a PostgreSQL database that has PostGIS installed: + +```yaml +version: '3.6' +services: + pgDB: + image: postgis/postgis:13-3.1-alpine + restart: always + ports: + - '5432:5432' + volumes: + - db_data:/var/lib/postgresql/data + environment: + POSTGRES_PASSWORD: password + POSTGRES_DB: geoexample +volumes: + db_data: +``` + + + +Next, create a migration and execute a migration to enable the extension: + +```terminal +npx prisma migrate dev --name add-postgis +``` + +For reference, the output of the migration file should look like the following: + +```sql file=migrations/TIMESTAMP_add_postgis/migration.sql +-- CreateExtension +CREATE EXTENSION IF NOT EXISTS "postgis"; +``` + +You can double-check that the migration has been applied by running `prisma migrate status`. + +## 2. Create a new model that uses a geographic data column + +Add a new model with a column with a `geography` data type once the migration is applied. For this guide, we'll use a model called `PointOfInterest`. + +```prisma +model PointOfInterest { + id Int @id @default(autoincrement()) + name String + location Unsupported("geography(Point, 4326)") +} +``` + +You'll notice that the `location` field uses an [`Unsupported`](/reference/prisma-schema-reference#unsupported) type. This means that we lose a lot of the benefits of Prisma when working with `PointOfInterest`. We'll be using [SafeQL](https://safeql.dev/) to fix this. + +Like before, create and execute a migration using the `prisma migrate dev` command to create the `PointOfInterest` table in your database: + +```terminal +npx prisma migrate dev --name add-poi +``` + +For reference, here is the output of the SQL migration file generated by Prisma Migrate: + +```sql file=migrations/TIMESTAMP_add_poi/migration.sql +-- CreateTable +CREATE TABLE "PointOfInterest" ( + "id" SERIAL NOT NULL, + "name" TEXT NOT NULL, + "location" geography(Point, 4326) NOT NULL, + + CONSTRAINT "PointOfInterest_pkey" PRIMARY KEY ("id") +); +``` + +## 3. Integrate SafeQL + +SafeQL is easily integrated with Prisma in order to lint `$queryRaw` and `$executeRaw` Prisma operations. You can reference [SafeQL's integration guide](https://safeql.dev/compatibility/prisma.html) or follow the steps below. + +### 3.1. Install the @ts-safeql/eslint-plugin npm package + +```terminal +npm install -D @ts-safeql/eslint-plugin +``` + +This ESLint plugin is what will allow for queries to be linted. + +### 3.2. Add @ts-safeql/eslint-plugin to your ESLint plugins + +Next, add `@ts-safeql/eslint-plugin` to your list of ESLint plugins. In our example we are using an `.eslintrc.js` file, but this can be applied to any way that you [configure ESLint](https://eslint.org/docs/latest/use/configure/). + +```js file=.eslintrc.js highlight=3 +/** @type {import('eslint').Linter.Config} */ +module.exports = { + "plugins": [..., "@ts-safeql/eslint-plugin"], + ... +} +``` + +### 3.3 Add @ts-safeql/check-sql rules + +Now, setup the rules that will enable SafeQL to mark invalid SQL queries as ESLint errors. + +```js file=.eslintrc.js highlight=4-22;add +/** @type {import('eslint').Linter.Config} */ +module.exports = { + plugins: [..., '@ts-safeql/eslint-plugin'], + rules: { + '@ts-safeql/check-sql': [ + 'error', + { + connections: [ + { + // The migrations path: + migrationsDir: './prisma/migrations', + targets: [ + // This makes `prisma.$queryRaw` and `prisma.$executeRaw` commands linted + { tag: 'prisma.+($queryRaw|$executeRaw)', transform: '{type}[]' }, + ], + }, + ], + }, + ], + }, +} +``` + +> **Note**: If your `PrismaClient` instance is called something different than `prisma`, you need to adjust the value for `tag` accordingly. For example, if it is called `db`, the value for `tag` should be `'db.+($queryRaw|$executeRaw)'`. + +### 3.4. Connect to your database + +Finally, set up a `connectionUrl` for SafeQL so that it can introspect your database and retrieve the table and column names you use in your schema. SafeQL then uses this information for linting and highlighting problems in your raw SQL statements. + +Our example relies on the [`dotenv`](https://github.com/motdotla/dotenv) package to get the same connection string that is used by Prisma. We recommend this in order to keep your database URL out of version control. + +If you haven't installed `dotenv` yet, you can install it as follows: + +```terminal +npm install dotenv +``` + +Then update your ESLint config as follows: + +```js file=.eslintrc.js highlight=1,6-9,16;add +require('dotenv').config() + +/** @type {import('eslint').Linter.Config} */ +module.exports = { + plugins: ['@ts-safeql/eslint-plugin'], + // exclude `parserOptions` if you are not using TypeScript + parserOptions: { + project: './tsconfig.json', + }, + rules: { + '@ts-safeql/check-sql': [ + 'error', + { + connections: [ + { + connectionUrl: process.env.DATABASE_URL, + // The migrations path: + migrationsDir: './prisma/migrations', + targets: [ + // what you would like SafeQL to lint. This makes `prisma.$queryRaw` and `prisma.$executeRaw` + // commands linted + { tag: 'prisma.+($queryRaw|$executeRaw)', transform: '{type}[]' }, + ], + }, + ], + }, + ], + }, +} +``` + +SafeQL is now fully configured to help you write better raw SQL using Prisma Client. + +## 4. Creating extensions to make raw SQL queries type-safe + +In this section, we'll create two [`model`](/concepts/components/prisma-client/client-extensions/model) extensions with custom queries to be able to work conveniently with the `PointOfInterest` model: + +1. A `create` query that allows us to create new `PointOfInterest` records in the database +1. A `findClosestPoints` query that returns the `PointOfInterest` records that are closest to a given coordinate + +### 4.1. Adding an extension to create `PointOfInterest` records + +The `PointOfInterest` model in the Prisma schema uses an `Unsupported` type. As a consequence, the generated `PointOfInterest` type in Prisma Client can't be used to carry values for latitude and longitude. + +We will resolve this by defining two custom types that better represent our model in TypeScript: + +```ts +type MyPoint = { + latitude: number + longitude: number +} + +type MyPointOfInterest = { + name: string + location: Point +} +``` + +Next, you can add a `create` query to the `pointOfInterest` property of your Prisma Client: + +```ts highlight=19;normal +const prisma = new PrismaClient().$extends({ + model: { + pointOfInterest: { + async create(data: { + name: string + latitude: number + longitude: number + }) { + // Create an object using the custom types from above + const poi: MyPointOfInterest = { + name: data.name, + location: { + latitude: data.latitude, + longitude: data.longitude, + }, + } + + // Insert the object into the database + const point = `POINT(${poi.location.longitude} ${poi.location.latitude})` + await prisma.$queryRaw` + INSERT INTO "PointOfInterest" (name, location) VALUES (${poi.name}, ST_GeomFromText(${point}, 4326)); + ` + + // Return the object + return poi + }, + }, + }, +}) +``` + +Notice that the SQL in the line that's highlighted in the code snippet gets checked by SafeQL! For example, if you change the name of the table from `"PointOfInterest"` to `"PointOfInterest2"`, the following error appears: + +``` +error Invalid Query: relation "PointOfInterest2" does not exist @ts-safeql/check-sql +``` + +This also works with the column names `name` and `location`. + +You can now create new `PointOfInterest` records in your code as follows: + +```ts +const poi = await prisma.pointOfInterest.create({ + name: 'Berlin', + latitude: 52.52, + longitude: 13.405, +}) +``` + +### 4.2. Adding an extension to query for closest to `PointOfInterest` records + +Now let's make a Prisma Client extension in order to query this model. We will be making an extension that finds the closest points of interest to a given longitude and latitude. + +```ts +const prisma = new PrismaClient().$extends({ + model: { + pointOfInterest: { + async create(data: { + name: string + latitude: number + longitude: number + }) { + // ... same code as before + }, + + async findClosestPoints(latitude: number, longitude: number) { + // Query for clostest points of interests + const result = await prisma.$queryRaw< + { + id: number | null + name: string | null + st_x: number | null + st_y: number | null + }[] + >`SELECT id, name, ST_X(location::geometry), ST_Y(location::geometry) + FROM "PointOfInterest" + ORDER BY ST_DistanceSphere(location::geometry, ST_MakePoint(${latitude}, ${longitude})) DESC` + + // Transform to our custom type + const pois: MyPointOfInterest[] = result.map((data) => { + return { + name: data.name, + location: { + latitude: data.st_x || 0, + longitude: data.st_y || 0, + }, + } + }) + + // Return data + return pois + }, + }, + }, +}) +``` + +Now, you can use our Prisma Client as normal to find close points of interest to a given longitude and latitude using the custom method created on the `PointOfInterest` model. + +```ts +const closestPointOfInterest = await prisma.pointOfInterest.findClosestPoints( + 53.5488, + 9.9872 +) +``` + +Similar to before, we again have the benefit of SafeQL to add extra type safety to our raw queries. For example, if we removed the cast to `geometry` for `location` by changing `location::geometry` to just `location`, we would get linting errors in the `ST_X`, `ST_Y` or `ST_DistanceSphere` functions respectively. + +```terminal +error Invalid Query: function st_distancesphere(geography, geometry) does not exist @ts-safeql/check-sql +``` + +## Conclusion + +While you may sometimes need to drop down to raw SQL when using Prisma, you can use various techniques to make the experience of writing raw SQL queries with Prisma better. + +In this article, you have used SafeQL and Prisma Client extensions to create custom, type-safe Prisma Client queries to abstract PostGIS operations which are currently not natively supported in Prisma ORM. diff --git a/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/index.mdx b/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/index.mdx new file mode 100644 index 0000000000..11f43e00f0 --- /dev/null +++ b/content/300-guides/500-other/900-advanced-database-tasks/06-typesafe-raw-sql/index.mdx @@ -0,0 +1,16 @@ +--- +title: Advanced features using raw SQL +metaTitle: Advanced features using raw SQL (Guides) +metaDescription: Learn how to use raw SQL and Prisma Client extensions to cover areas not natively supported by Prisma. +toc: false +--- + + + +There are certain database features that are not natively supported by Prisma. In these cases, it's possible to use [Prisma Client extensions](/concepts/components/prisma-client/client-extensions) and tools like [SafeQL](https://safeql.dev/) in order to keep the great developer experience of Prisma when working with raw SQL. + + + +## In this section + + From a904bf16be82c0b2355b997a2b94ad487c4e8de4 Mon Sep 17 00:00:00 2001 From: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> Date: Wed, 22 Nov 2023 20:34:49 +0600 Subject: [PATCH 28/32] feat: document more error codes for Accelerate (#5481) Co-authored-by: Nikolas --- .../200-api-reference/250-error-reference.mdx | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/content/400-reference/200-api-reference/250-error-reference.mdx b/content/400-reference/200-api-reference/250-error-reference.mdx index cba546a1dd..1e100fd233 100644 --- a/content/400-reference/200-api-reference/250-error-reference.mdx +++ b/content/400-reference/200-api-reference/250-error-reference.mdx @@ -525,6 +525,22 @@ Interactive transaction error: Accelerate-related errors start with `P6xxx`. +#### P6000 (ServerError) + +Generic error to catch all other errors. + +#### P6001 (InvalidDataSource) + +The URL is malformed; for instance, it does not use the `prisma://` protocol. + +#### P6002 (Unauthorized) + +The API Key in the connection string is invalid. + +#### P6003 (PlanLimitReached) + +The included usage of the current plan has been exceeded. This can only occur on the [free plan](https://www.prisma.io/pricing). + #### P6004 (QueryTimeout) The global timeout of Accelerate has been exceeded. You can find the limit [here](/data-platform/accelerate/limitations#query-timeout-limit). @@ -533,6 +549,14 @@ The global timeout of Accelerate has been exceeded. You can find the limit [here The user supplied invalid parameters. Currently only relevant for transaction methods. For example, setting a timeout that is too high. You can find the limit [here](/data-platform/accelerate/limitations#interactive-transactions-query-timeout-limit). +#### P6006 (VersionNotSupported) + +The chosen Prisma version is not compatible with Accelerate. This may occur when a user uses an unstable development version that we occasionally prune. + +#### P6008 (ConnectionError|EngineStartError) + +The engine failed to start. For example, it couldn't establish a connection to the database. + #### P6009 (ResponseSizeLimitExceeded) The global response size limit of Accelerate has been exceeded. You can find the limit [here](/data-platform/accelerate/limitations#response-size-limit). From 36201fe443b3e142e13d8c9965dbb96202169c74 Mon Sep 17 00:00:00 2001 From: Jan Piotrowski Date: Thu, 23 Nov 2023 09:05:03 +0100 Subject: [PATCH 29/32] fix(pagination): Explain what happens when cursor does not exist (#5405) --- .../100-components/02-prisma-client/055-pagination.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/content/200-concepts/100-components/02-prisma-client/055-pagination.mdx b/content/200-concepts/100-components/02-prisma-client/055-pagination.mdx index e7293e3e27..25627e6d40 100644 --- a/content/200-concepts/100-components/02-prisma-client/055-pagination.mdx +++ b/content/200-concepts/100-components/02-prisma-client/055-pagination.mdx @@ -158,6 +158,10 @@ If you guess the value of the next cursor, you will page to an unknown location No, cursor pagination does not use cursors in the underlying database ([e.g. PostgreSQL](https://www.postgresql.org/docs/9.2/plpgsql-cursors.html)). +#### What happens if the cursor value does not exist? + +Using a nonexistent cursor returns `null`. Prisma does not try to locate adjacent values. + ### ✔ Pros of cursor-based pagination - Cursor-based pagination **scales**. The underlying SQL does not use `OFFSET`, but instead queries all `Post` records with an ID greater than the value of `cursor`. From 0b2e22e2f2a7a71a9ebb71587545e4e65cab2a1a Mon Sep 17 00:00:00 2001 From: samad barbast Date: Thu, 23 Nov 2023 11:49:44 +0330 Subject: [PATCH 30/32] Update 500-troubleshooting-relations.mdx (#5275) --- .../06-relations/500-troubleshooting-relations.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/01-prisma-schema/06-relations/500-troubleshooting-relations.mdx b/content/200-concepts/100-components/01-prisma-schema/06-relations/500-troubleshooting-relations.mdx index 03aa18ef86..9828114096 100644 --- a/content/200-concepts/100-components/01-prisma-schema/06-relations/500-troubleshooting-relations.mdx +++ b/content/200-concepts/100-components/01-prisma-schema/06-relations/500-troubleshooting-relations.mdx @@ -24,7 +24,7 @@ model Animal { } ``` -The resulting relation table in SQL looks as follows, where `A` represents prey (`a_eats`) and `B` represents predators (`a_eatenBy`): +The resulting relation table in SQL looks as follows, where `A` represents prey (`a_eats`) and `B` represents predators (`b_eatenBy`): | A | B | | :----------- | :--------- | From dc86179130475088f6f42d0fda9328b4ab97f031 Mon Sep 17 00:00:00 2001 From: Nikolas Date: Thu, 23 Nov 2023 09:58:36 +0100 Subject: [PATCH 31/32] Update 07-mongodb.mdx (#5489) --- content/200-concepts/200-database-connectors/07-mongodb.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/content/200-concepts/200-database-connectors/07-mongodb.mdx b/content/200-concepts/200-database-connectors/07-mongodb.mdx index 6ccecc7254..0188af6dc3 100644 --- a/content/200-concepts/200-database-connectors/07-mongodb.mdx +++ b/content/200-concepts/200-database-connectors/07-mongodb.mdx @@ -107,6 +107,8 @@ Any field (most commonly IDs and relation scalar fields) that maps to an `Object - Must include the `@db.ObjectId` attribute - Can optionally use `@default(auto())` to auto-generate a valid `ObjectId` on document creation +Here is an example that uses `String`: + ```prisma model User { id String @id @default(auto()) @map("_id") @db.ObjectId @@ -114,6 +116,8 @@ model User { } ``` +And here is another example that uses `Bytes`: + ```prisma model User { id Bytes @id @default(auto()) @map("_id") @db.ObjectId From de9e561f883eb6ecfcf6fd779cb9f644500ad823 Mon Sep 17 00:00:00 2001 From: LIU HANCHENG Date: Thu, 23 Nov 2023 17:13:00 +0800 Subject: [PATCH 32/32] Update many-to-many relations doc (#5486) Co-authored-by: Nikolas --- .../300-many-to-many-relations.mdx | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx b/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx index c46d607cd1..362c31b8b4 100644 --- a/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx +++ b/content/200-concepts/100-components/01-prisma-schema/06-relations/300-many-to-many-relations.mdx @@ -356,7 +356,7 @@ If you want a relation table to be picked up by introspection as an implicit m-n - It must start with an underscore `_` - Then the name of the first model in alphabetical order (in this case `Category`) -- Then `To` +- Then the relationship (in this case `To`) - Then the name of the second model in alphabetical order (in this case `Post`) In the example, the correct table name is `_CategoryToPost`. @@ -413,6 +413,49 @@ CREATE TABLE "Post" ( ); ``` +And you can define multiple many-to-many relations between two tables by using the different relationship name. This example shows how the Prisma introspection works under such case: + +```sql +CREATE TABLE IF NOT EXISTS "User" ( + "id" SERIAL PRIMARY KEY +); +CREATE TABLE IF NOT EXISTS "Video" ( + "id" SERIAL PRIMARY KEY +); +CREATE TABLE IF NOT EXISTS "_UserLikedVideos" ( + "A" SERIAL NOT NULL, + "B" SERIAL NOT NULL, + CONSTRAINT "_UserLikedVideos_A_fkey" FOREIGN KEY ("A") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "_UserLikedVideos_B_fkey" FOREIGN KEY ("B") REFERENCES "Video" ("id") ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE TABLE IF NOT EXISTS "_UserDislikedVideos" ( + "A" SERIAL NOT NULL, + "B" SERIAL NOT NULL, + CONSTRAINT "_UserDislikedVideos_A_fkey" FOREIGN KEY ("A") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "_UserDislikedVideos_B_fkey" FOREIGN KEY ("B") REFERENCES "Video" ("id") ON DELETE CASCADE ON UPDATE CASCADE +); +CREATE UNIQUE INDEX "_UserLikedVideos_AB_unique" ON "_UserLikedVideos"("A", "B"); +CREATE INDEX "_UserLikedVideos_B_index" ON "_UserLikedVideos"("B"); +CREATE UNIQUE INDEX "_UserDislikedVideos_AB_unique" ON "_UserDislikedVideos"("A", "B"); +CREATE INDEX "_UserDislikedVideos_B_index" ON "_UserDislikedVideos"("B"); +``` + +If you run `prisma db pull` on this database, the Prisma CLI will generate the following schema through introspection: + +```prisma +model User { + id Int @id @default(autoincrement()) + Video_UserDislikedVideos Video[] @relation("UserDislikedVideos") + Video_UserLikedVideos Video[] @relation("UserLikedVideos") +} + +model Video { + id Int @id @default(autoincrement()) + User_UserDislikedVideos User[] @relation("UserDislikedVideos") + User_UserLikedVideos User[] @relation("UserLikedVideos") +} +``` + #### Configuring the name of the relation table in implicit many-to-many relations When using Prisma Migrate, you can configure the name of the relation table that's managed by Prisma using the `@relation` attribute. For example, if you want the relation table to be called `_MyRelationTable` instead of the default name `_CategoryToPost`, you can specify it as follows: