Skip to content

Commit

Permalink
Merge branch 'main' into janpio/external-connection-pooler
Browse files Browse the repository at this point in the history
  • Loading branch information
janpio authored Nov 23, 2023
2 parents 57483e3 + de9e561 commit e303477
Show file tree
Hide file tree
Showing 26 changed files with 807 additions and 167 deletions.
5 changes: 3 additions & 2 deletions cSpell.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"Snaplet",
"Kysely",
"Turso",
"inshellisense",
"autocompletions",
"Formbricks",
"Openform",
"Documenso",
Expand Down Expand Up @@ -89,7 +89,8 @@
"libgcc",
"libc",
"Distroless",
"Supavisor"
"Supavisor",
"inshellisense",
],
"patterns": [
{
Expand Down
54 changes: 45 additions & 9 deletions content/100-getting-started/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,29 @@ metaDescription: 'Get started'

<TopBlock>

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://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 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.

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.

</TopBlock>

## 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!

<ButtonLink color="dark" type="primary" href="./getting-started/quickstart">
Quickstart
</ButtonLink>

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.

<ButtonLink
color="dark"
Expand All @@ -44,7 +46,7 @@ If you're looking to incorporate Prisma with an **existing project**, choose whe
Existing MongoDB project
</ButtonLink>

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.

<ButtonLink
color="dark"
Expand All @@ -62,6 +64,40 @@ To learn how to **create a project** with Prisma from scratch, choose between SQ
New MongoDB project
</ButtonLink>

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

<ButtonLink
color="dark"
type="primary"
href="https://github.com/prisma/prisma-examples/"
>
Examples
</ButtonLink>

### Get started with Prisma Accelerate

Add **Accelerate** to your app to use connection pooling and global database caching.

<ButtonLink
color="dark"
type="primary"
href="/data-platform/accelerate/getting-started"
>
Get started with Accelerate
</ButtonLink>

### Get started with Prisma Pulse

Add **Pulse** to your app to subscribe to real-time updates from your database using Prisma Client.

<ButtonLink
color="dark"
type="primary"
href="/data-platform/pulse/getting-started"
>
Get started with Pulse
</ButtonLink>

## 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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- [`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.

Original file line number Diff line number Diff line change
Expand Up @@ -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 `To`
- Then the name of the second table in alphabetical order (in this case `Post`)
- Then the name of the first model in alphabetical order (in this case `Category`)
- 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`.

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:
Expand Down Expand Up @@ -409,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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| :----------- | :--------- |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ Number of SOFT deleted posts: 95

### Can I add a global <inlinecode>includeDeleted</inlinecode> to the <inlinecode>Post</inlinecode> 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 } })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
</TopBlock>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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) <span class="api"></span> 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) <span class="api"></span> field:
2. Add the URL to your environment variable `SHADOW_DATABASE_URL`
3. Add the [`shadowDatabaseUrl`](/reference/api-reference/prisma-schema-reference#datasource) <span class="api"></span> field reading this environment variable:

```prisma highlight=4;normal
datasource db {
Expand All @@ -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:

Expand All @@ -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.

Expand Down
Loading

0 comments on commit e303477

Please sign in to comment.