diff --git a/.gitignore b/.gitignore index b2d6de3062..d815957f75 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,7 @@ npm-debug.log* yarn-debug.log* yarn-error.log* + +# wrangler project +.dev.vars +.wrangler/ diff --git a/docs/200-orm/050-overview/100-introduction/100-what-is-prisma.mdx b/docs/200-orm/050-overview/100-introduction/100-what-is-prisma.mdx index dd091d68c0..0a64dd2c0e 100644 --- a/docs/200-orm/050-overview/100-introduction/100-what-is-prisma.mdx +++ b/docs/200-orm/050-overview/100-introduction/100-what-is-prisma.mdx @@ -249,7 +249,7 @@ With **Prisma Migrate**, Prisma's integrated database migration tool, the workfl 1. Migrate your development database using the `prisma migrate dev` CLI command 1. Use Prisma Client in your application code to access your database -![Typical workflow with Prisma Migrate](/img/prisma-migrate-development-workflow.png) +![Typical workflow with Prisma Migrate](/img/orm/prisma-migrate-development-workflow.png) To learn more about the Prisma Migrate workflow, see: @@ -268,6 +268,6 @@ The typical workflow when using **SQL migrations and introspection** is slightly 1. (Re-)generate Prisma Client 1. Use Prisma Client in your application code to access your database -![Introspect workflow](/img/prisma-evolve-app-workflow.png) +![Introspect workflow](/img/orm/prisma-evolve-app-workflow.png) To learn more about the introspection workflow, please refer the [introspection section](/orm/prisma-schema/introspection). diff --git a/docs/200-orm/050-overview/500-databases/800-sql-server/020-sql-server-local.mdx b/docs/200-orm/050-overview/500-databases/800-sql-server/020-sql-server-local.mdx index f52fd1c524..f2f6dec3e4 100644 --- a/docs/200-orm/050-overview/500-databases/800-sql-server/020-sql-server-local.mdx +++ b/docs/200-orm/050-overview/500-databases/800-sql-server/020-sql-server-local.mdx @@ -14,7 +14,7 @@ To run a Microsoft SQL Server locally on a Windows machine: 1. Use Windows Authentication to log in to Microsoft SQL Server Management Studio (expand the **Server Name** dropdown and click **<Browse for more...>** to find your database engine): -![The New Query button in SQL Server Management Studio](/img/connect-sql-server.png) +![The New Query button in SQL Server Management Studio](/img/orm/connect-sql-server.png) diff --git a/docs/200-orm/100-prisma-schema/50-introspection.mdx b/docs/200-orm/100-prisma-schema/50-introspection.mdx index 553f50b67f..d52e6b3c79 100644 --- a/docs/200-orm/100-prisma-schema/50-introspection.mdx +++ b/docs/200-orm/100-prisma-schema/50-introspection.mdx @@ -18,7 +18,7 @@ However, it can also be [used _repeatedly_ in an application](#introspection-wit Introspection has one main function: Populate your Prisma schema with a data model that reflects the current database schema. -![Introspect your database with Prisma](/img/prisma-db-pull-generate-schema.png) +![Introspect your database with Prisma](/img/orm/prisma-db-pull-generate-schema.png) Here's an overview of its main functions on SQL databases: @@ -63,7 +63,7 @@ The typical workflow for projects that are not using Prisma Migrate, but instead Note that as you evolve the application, [this process can be repeated for an indefinite number of times](#introspection-with-an-existing-schema). -![Introspect workflow](/img/prisma-evolve-app-workflow.png) +![Introspect workflow](/img/orm/prisma-evolve-app-workflow.png) ## Rules and conventions diff --git a/docs/200-orm/200-prisma-client/100-queries/055-pagination.mdx b/docs/200-orm/200-prisma-client/100-queries/055-pagination.mdx index 315509255a..aa451ad2e9 100644 --- a/docs/200-orm/200-prisma-client/100-queries/055-pagination.mdx +++ b/docs/200-orm/200-prisma-client/100-queries/055-pagination.mdx @@ -21,7 +21,7 @@ const results = await prisma.post.findMany({ }) ``` -![](/img/offset-skip-take.png) +![](/img/orm/offset-skip-take.png) To implement pages of results, you would just `skip` the number of pages multiplied by the number of results you show per page. @@ -103,7 +103,7 @@ const firstQueryResults = await prisma.post.findMany({ The following diagram shows the IDs of the first 4 results - or page 1. The cursor for the next query is **29**: -![](/img/cursor-1.png) +![](/img/orm/cursor-1.png) The second query returns the first 4 `Post` records that contain the word `"Prisma"` **after the supplied cursor** (in other words - IDs that are larger than **29**): @@ -130,7 +130,7 @@ const myCursor = lastPostInResults.id // Example: 52 The following diagram shows the first 4 `Post` records **after** the record with ID **29**. In this example, the new cursor is **52**: -![](/img/cursor-2.png) +![](/img/orm/cursor-2.png) ### FAQ @@ -138,15 +138,15 @@ The following diagram shows the first 4 `Post` records **after** the record with If you do not `skip: 1`, your result set will include your previous cursor. The first query returns four results and the cursor is **29**: -![](/img/cursor-1.png) +![](/img/orm/cursor-1.png) Without `skip: 1`, the second query returns 4 results after (and _including_) the cursor: -![](/img/cursor-3.png) +![](/img/orm/cursor-3.png) If you `skip: 1`, the cursor is not included: -![](/img/cursor-2.png) +![](/img/orm/cursor-2.png) You can choose to `skip: 1` or not depending on the pagination behavior that you want. diff --git a/docs/200-orm/200-prisma-client/500-deployment/600-deploy-migrations-from-a-local-environment.mdx b/docs/200-orm/200-prisma-client/500-deployment/600-deploy-migrations-from-a-local-environment.mdx index 8271afb12b..d99c3d8cf2 100644 --- a/docs/200-orm/200-prisma-client/500-deployment/600-deploy-migrations-from-a-local-environment.mdx +++ b/docs/200-orm/200-prisma-client/500-deployment/600-deploy-migrations-from-a-local-environment.mdx @@ -51,4 +51,4 @@ The pipeline should handle deployment to staging and production environments, an When you add Prisma Migrate to an **existing database**, you must [baseline](/orm/prisma-migrate/workflows/baselining) the production database. Baselining is performed **once**, and can be done from a local instance. -![](/img/baseline-production-from-local.png) +![](/img/orm/baseline-production-from-local.png) diff --git a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx index 314eadff69..f939728df1 100644 --- a/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx +++ b/docs/200-orm/800-more/300-upgrade-guides/800-upgrade-from-prisma-1/03-upgrading-the-prisma-layer.mdx @@ -419,7 +419,7 @@ npx prisma db pull Here's a graphical illustration for what happens when `db pull` is invoked: -![Introspect your database with Prisma](/img/prisma-db-pull-generate-schema.png) +![Introspect your database with Prisma](/img/orm/prisma-db-pull-generate-schema.png) For the above Prisma 1 datamodel, this results in the following Prisma 2 schema (note that the models have been reordered to match the initial order of the Prisma 1 datamodel): diff --git a/docs/300-accelerate/100-what-is-accelerate.mdx b/docs/300-accelerate/100-what-is-accelerate.mdx new file mode 100644 index 0000000000..f18880b9d0 --- /dev/null +++ b/docs/300-accelerate/100-what-is-accelerate.mdx @@ -0,0 +1,29 @@ +--- +title: 'What is Accelerate' +metaTitle: 'What is Accelerate' +metaDescription: 'Learn about Accelerate, a global cache and serverless connection pool that makes your database queries faster.' +tocDepth: 3 +toc: true +--- + + + +[Accelerate](https://www.prisma.io/data-platform/accelerate) is a global database cache available in 300 locations that you can use to achieve up to 1000x faster database queries. + +Its main features are: + +- a global cache +- scalable connection pool for serverless and edge applications +- usage of Prisma Client at the edge (e.g. in Cloudflare Workers or Vercel Edge Functions) + +The goal of Accelerate is to improve response times and reduce database load. It works by caching data at the edge using established caching patterns that you control. + +While Accelerate is beneficial for all types of applications, being at the edge provides additional benefits to edge function environments like [Vercel Edge Functions](https://vercel.com/docs/concepts/functions/edge-functions), [Cloudflare Workers](https://workers.cloudflare.com/), and [Deno Deploy](https://deno.com/deploy). Cache hits can be served from data centers near the user regardless of the region of the database. + + + +## See Accelerate in action + +We built a small sample application, [Accelerate Speed Test](https://accelerate-speed-test.prisma.io/). The app compares the performance of cached and uncached queries side by side. The app is [open source](https://github.com/prisma/accelerate-speed-test) and you can clone it to try it yourself. + +![Screenshot of the Accelerate Speed Test app showing cached query performance](/img/accelerate/accelerate.png) diff --git a/docs/300-accelerate/200-getting-started.mdx b/docs/300-accelerate/200-getting-started.mdx new file mode 100644 index 0000000000..d7071ce236 --- /dev/null +++ b/docs/300-accelerate/200-getting-started.mdx @@ -0,0 +1,193 @@ +--- +title: 'Getting started' +metaTitle: 'Getting started with Accelerate' +metaDescription: 'Learn how to get up and running with Accelerate.' +tocDepth: 3 +toc: true +--- + + + + + +## Prerequisites + +To get started with Accelerate, you will need the following: + +- A GitHub account. +- A project that uses [Prisma Client](/orm/prisma-client) `4.16.1` or higher. If your project is using interactive transactions, you need to use `5.1.1` or higher. (We always recommend using the latest version of Prisma.) +- A hosted PostgreSQL, MySQL, PlanetScale, CockroachDB, or MongoDB database. + +## 1. Enable Accelerate in a project + +In order to enable Accelerate, you can log in to [Prisma Data Platform](https://pris.ly/pdp) and create a new project. Follow the instructions in the UI to add Accelerate. + +At the end of the setup process, you'll obtain a connection string that connects to Accelerate. This connection string also contains an API key that you need to use when configuring Prisma Client to use Accelerate. + +## 2. Use Accelerate in your application + +To get started using Accelerate, we recommend using the [latest version of Prisma ORM](https://github.com/prisma/prisma/releases/). + +### 2.1. Update your database connection string + +After enabling Accelerate in your project and creating a new API key, you should be given an Accelerate connection string. + +To use this connection string, update the `datasource` block's `url` field in your Prisma schema: + +```prisma +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} +``` + +Most likely, as shown above, your database connection string in defined in a `.env` file rather than hard-coded into the schema file. + +Update that variable to use the new Accelerate connection string: + +```env file=.env +# __API_KEY__ is a unique API key that Accelerate generates and automatically assigns to a project. +DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" + +# Previous connection string +# DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" +``` + +Prisma Migrate and Introspection do not work with a `prisma://` connection string. In order to continue using these features add a new variable to the `.env` file named `DIRECT_DATABASE_URL` whose value is the direct database connection string: + + + +As of Prisma version `5.2.0` you can use Prisma Studio with the Accelerate connection string. + + + +```env file=.env highlight=3;add +DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__" +DIRECT_DATABASE_URL="postgresql://user:password@host:port/db_name?schema=public" +``` + +Then in your Prisma schema's `datasource` block add a field named `directUrl` with the following: + +```prisma highlight=4;add +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + directUrl = env("DIRECT_DATABASE_URL") +} +``` + +Migrations and introspections will use the `directUrl` connection string rather than the one defined in `url` when this configuration is provided. + +> `directUrl` is useful for you to carry out migrations and introspections. However, you don't need `directUrl` to use Accelerate in your application. + +### 2.2. Install the Accelerate Prisma Client extension + +Run the following command to install the Accelerate extension for Prisma Client: + +```terminal +npm install @prisma/extension-accelerate +``` + +### 2.3. Generate Prisma Client for Accelerate + +If you're using Prisma version `5.2.0` or greater, Prisma Client will automatically determine how it should connect to the database depending on the protocol in the database connection string. If the connection string in the `DATABASE_URL` starts with `prisma://`, Prisma Client will try to connect to your database using Prisma Accelerate. + +When using Prisma Accelerate in long-running application servers, such as a server deployed on AWS EC2, you can generate the Prisma Client by executing the following command: + +```terminal +npx prisma generate +``` + +When using Prisma Accelerate in a Serverless or an Edge application, we recommend you to run the following command to generate Prisma Client: + +```terminal +npx prisma generate --no-engine +``` + + + +The `--no-engine` flag prevents a Query Engine file from being included in the generated Prisma Client, this ensures the bundle size of your application remains small. + + + + + +If your Prisma version is below `5.2.0`, generate Prisma Client with the `--accelerate` option: + +```terminal +npx prisma generate --accelerate +``` + +If your Prisma version is below `5.0.0`, generate Prisma Client with the `--data-proxy` option: + + +### 2.4. Extend your Prisma Client instance to add the Accelerate extension + +To use Accelerate, you must extend Prisma Client with the Accelerate extension. +Extend your Prisma Client instance to add the Accelerate extension: + +```ts +import { PrismaClient } from '@prisma/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient().$extends(withAccelerate()) +``` + +If you are going to deploy to an edge runtime (like Cloudflare Workers, Vercel Edge Functions, Deno Deploy, or Netlify Edge Functions), use our edge client instead: + +```ts +import { PrismaClient } from '@prisma/client/edge' +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient().$extends(withAccelerate()) +``` + +If VS Code does not recognize the `$extends` method, refer to [this section](/accelerate/faq#vs-code-does-not-recognize-the-extends-method) on how to resolve the issue. + + + +If you are using [Prisma Middleware](/orm/prisma-client/client-extensions/middleware) in your application, make sure they are added before any Prisma Client extensions (like Accelerate). For example: + +```ts +const prisma = new PrismaClient().$use(middleware).$extends(withAccelerate()) +``` + + + +### 2.5. Use Accelerate in your database queries + +The `withAccelerate` extension primarily does two things: + +- Gives you access to the `cacheStrategy` field within each applicable model method that allows you to define a cache strategy per-query. +- Routes all of your queries through a connection pooler. + +#### No cache strategy to only use connection pool + +If you simply want to take advantage of Accelerate's connection pooling feature without applying a cache strategy, you may run your query the same way you would have without Accelerate. + +By enabling Accelerate and supplying the Accelerate connection string, your queries now use the connection pooler by default. + +#### Define a cache strategy + +Update a query with the new `cacheStrategy` property which allows you to define a cache strategy for that specific query: + +```ts +const user = await prisma.user.findMany({ + where: { + email: { + contains: 'alice@prisma.io', + }, + }, + cacheStrategy: { swr: 60, ttl: 60 }, +}) +``` + +In the example above, `swr: 60` and `ttl: 60` means Accelerate will serve cached data for 60 seconds and then another 60 seconds while Accelerate fetches fresh data in the background. + +You should now see improved performance for your cached queries. + + + +For information about which strategy best serves your application, see [Select a cache strategy](/accelerate/caching#selecting-a-cache-strategy). + + diff --git a/docs/300-accelerate/250-connection-pooling.mdx b/docs/300-accelerate/250-connection-pooling.mdx new file mode 100644 index 0000000000..007dde554f --- /dev/null +++ b/docs/300-accelerate/250-connection-pooling.mdx @@ -0,0 +1,65 @@ +--- +title: 'Connection Pooling' +metaTitle: 'Accelerate: Connection Pooling' +metaDescription: "Learn about everything you need to know to use Accelerate's connection pooling." +--- + +## Connection pooling + +A [connection pool](https://en.wikipedia.org/wiki/Connection_pool#:~:text=In%20software%20engineering%2C%20a%20connection,executing%20commands%20on%20a%20database.) is a storage of database connections that can be reused for future requests to the database. When a new connection is requested, it is retrieved from the pool if one is available. Once the connection is no longer needed, it is returned to the pool for reuse. + +[Connection pooling](https://www.prisma.io/dataguide/database-tools/connection-pooling) is important as it allows you to reuse existing connections instead of creating new ones, which can be an expensive operation. + +The efficient management of database connections allows the database to process more queries without exhausting the available database connections, making your application more scalable. + +Accelerate provides built-in connection pooling by default. By simply using Accelerate, you get the benefits of connection pooling without having to configure anything. However, you can also configure the connection pool to suit your needs. + + + +For more information about connection pooling in Prisma, see the documentation [here](/orm/prisma-client/setup-and-configuration/databases-connections/connection-pool). + + + +### Default connection pool size + +By default, Accelerate calculates a default connection pool size using the formula `num_physical_cpus * 2 + 1`. + + + +For example, a machine with 2 physical CPUs will have a default connection pool size of `2 * 2 + 1` or `5`. + + + +This means that Accelerate will create a maximum of 5 connections to the database. If more than 5 connections are requested, Accelerate will queue the requests until a connection is available. + +### Configuring the connection pool size + +The connection pool size can be configured to a value other than the default via the _database connection string_. + +![Update database connection string in Accelerate](/img/accelerate/accelerate-update-database-connection-string.png) + +To adjust the connection pool size, you can add the `connection_limit` parameter to the database connection string. The value of `connection_limit` is the maximum number of connections that Accelerate will open against your database. + +For example, here is how you can set a connection pool size of 10: + +```env no-copy +postgresql://user:password@localhost:5432/db?connection_limit=10 +``` + +### Configuring the connection pool timeout + +The connection pool timeout is the duration, measured in seconds, during which the query engine must process a specific query; failing to do so within this timeframe results in an exception being thrown, and the system proceeds to the next query in the queue. + +Similar to the connection pool size, you may also configure the connection pool timeout via the _database connection string_. To adjust this value, you may add the `pool_timeout` parameter to the database connection string. + +For example: + +```env no-copy +postgresql://user:password@localhost:5432/db?connection_limit=10&pool_timeout=20 +``` + + + +The default value for `pool_timeout` is `10` seconds. + + diff --git a/docs/300-accelerate/300-caching.mdx b/docs/300-accelerate/300-caching.mdx new file mode 100644 index 0000000000..b02f7f9c81 --- /dev/null +++ b/docs/300-accelerate/300-caching.mdx @@ -0,0 +1,104 @@ +--- +title: 'Caching' +metaTitle: 'Accelerate: Caching' +metaDescription: "Learn everything you need to know to use Accelerate's global database caching." +--- + +## Cache strategies + +For all read queries in Prisma Client, you can define the `cacheStrategy` parameter that configures cache behavior. The cache strategy allows you to define two main characteristics of the cache: + +- **Time-to-live (TTL):** Duration in seconds a cached response is considered _fresh_. +- **Stale-while-Revalidating (SWR):** Duration in seconds a stale cache response is considered acceptable while the cache is refreshed in the background + +## Time-to-live (TTL) + +Time-to-Live (TTL) determines how long cached data is considered fresh. By specifying the `ttl` in seconds, you can control the duration for which data in the cache remains valid. When a read query is executed, if the cached response is within the `ttl` limit, Prisma Client retrieves the data from the cache without querying the database. If the cached data is not available or has expired, Prisma Client queries the database and stores the results in the cache for future requests. + +Use `ttl` in `cacheStrategy` and specify the TTL of the query in seconds: + +```javascript +await prisma.user.findMany({ + cacheStrategy: { ++ ttl: 60, + }, +}); +``` + +With a specified TTL of 60 seconds, the majority of requests will result in +a cache hit throughout the TTL duration: + +![TTL](/img/accelerate/ttl.png) + +TTL is useful for reducing database load and latency for data that does not require frequent updates. + +## Stale-While-Revalidate (SWR) + +Stale-While-Revalidate (SWR) allows you to control how long Accelerate can serve stale cache data while fetching fresh data in the background. When a read query is executed, Accelerate checks the age of the cached response against the `swr` duration. If the cache data is within the `swr` limit, Accelerate serves the stale data while simultaneously refreshing the cache by fetching the latest data from the database. + +Use `swr` in `cacheStrategy` and specify the SWR of the query in seconds: + +```javascript +await prisma.user.findMany({ + cacheStrategy: { ++ swr: 60, + }, +}); +``` + +When specifying a SWR of 60 seconds, the cache serves stale data until the cache refreshes itself in the background after each request: + +![SWR](/img/accelerate/swr.png) + +## Selecting a cache strategy + +Caching helps you improve query response times and reduce database load. However, it also means you might serve stale data to the client. Whether or not serving stale data is acceptable and to what extent depends on your use case. `ttl` and `swr` are parameters you can use the tweak the cache behavior. + +### Cache strategy using TTL + +Use TTL to reduce database load when stale cached data is acceptable. + +#### Use case: Product catalog in e-commerce applications + +Consider an e-commerce application with a product catalog that doesn't frequently change. By setting a `ttl` of, let's say, 1 hour, Prisma Client can serve cached product data for subsequent user requests within that hour without hitting the database. This significantly reduces the database load and improves the response time for product listing pages. + +### Cache strategy using SWR + +Use SWR to respond quickly to requests with minimal stale data. While it does not reduce database load, it can improve response times significantly. + +#### Use case: User profile in social media platforms + +Imagine a social media platform where user profiles are frequently accessed. By leveraging `swr` with a duration of, let's say, 5 minutes, Accelerate can serve the cached user profile information quickly, reducing the latency for profile pages. Meanwhile, in the background, it refreshes the cache after every request, ensuring that any updates made to the profile are eventually reflected for subsequent requests. + +### Cache strategy using TTL + SWR + +For very fast response times and reduced database load, use both TTL and SWR. You can use this strategy to fine-tune your application’s tolerance for stale data. + +Use `ttl` and `swr` in `cacheStrategy` and specify the TTL and SWR of the query in seconds: + +```javascript +await prisma.user.findMany({ + cacheStrategy: { ++ ttl: 30, ++ swr: 60, + }, +}); +``` + +When specifying a TTL of 30 seconds and SWR of 60 seconds, the cache serves fresh data for the initial 30 seconds. Subsequently, it serves stale data until the cache refreshes itself in the background after each request: + +![ttl_and_swr.png](/img/accelerate/ttl_and_swr.png) + +#### Use case: News articles + +Consider a news application where articles are frequently accessed but don't require real-time updates. By setting a `ttl` of 2 hours and an `swr` duration of 5 minutes, Prisma Client can serve cached articles quickly, reducing latency for readers. As long as the articles are within the `ttl`, users get fast responses. After the `ttl` expires, Prisma Client serves the stale articles for an additional 5 minutes while fetching the latest news from the database, maintaining a balance between performance and freshness. + +## Default cache strategy  + +Accelerate defaults to **no cache** to avoid counterintuitive issues. Caching can be a powerful tool for improving performance but can also be dangerous if not used correctly. + +For example, consider writing a query on a critical path without explicitly defining a cache strategy. If you run the code, you might receive incorrect data without explanation. This could be caused by someone forgetting to disable the default _implicit_ cache behavior. Implicit caching allows these counterintuitive issues to arise, leading to undesirable results. + +You must explicitly opt-in to caching if you want to use it. This makes it clear to developers that caching is not enabled by default and helps prevent counterintuitive issues from occurring. + +> When no cache strategy is specified or during a cache miss, a Prisma Client with the Accelerate extension routes all queries to the database through a connection pool instance near the database region. diff --git a/docs/300-accelerate/400-api-reference.mdx b/docs/300-accelerate/400-api-reference.mdx new file mode 100644 index 0000000000..a78b3d2971 --- /dev/null +++ b/docs/300-accelerate/400-api-reference.mdx @@ -0,0 +1,121 @@ +--- +title: 'API Reference' +metaTitle: 'Accelerate: API Reference' +metaDescription: 'API reference documentation for Accelerate.' +tocDepth: 3 +toc: true +--- + + + +The Accelerate API reference documentation is based on the following schema: + +```prisma +model User { + id Int @id @default(autoincrement()) + name String? + email String @unique +} +``` + +All example are based on the `User` model. + + + +## cacheStrategy + +With the Accelerate extension for Prisma Client, you can use the `cacheStrategy` parameter for model queries and use the [`ttl`](/accelerate/caching#time-to-live-ttl) and [`swr`](/accelerate/caching#stale-while-revalidate-swr) parameters to define a cache strategy for Accelerate. The Accelerate extension requires that you install Prisma Client version `4.10.0`. + +### Options + +The `cacheStrategy` parameter takes an option with the following keys: + +| Option | Example | Type | Required | Description | +| ------ | ------- | ----- | -------- | ------------------------------------------- | +| `swr` | `60` | `Int` | No | The stale-while-revalidate time in seconds. | +| `ttl` | `60` | `Int` | No | The time-to-live time in seconds. | + +### Examples + +Add a caching strategy to a query that defines a 60-second stale-while-revalidate value and 60-second time-to-live value: + +```ts highlight=7;normal +await prisma.user.findMany({ + where: { + email: { + contains: 'alice@prisma.io', + }, + }, + cacheStrategy: { swr: 60, ttl: 60 }, +}) +``` + +### Supported Prisma Client operations + +The following is a list of all read query operations and support `cacheStrategy`: + +- [`findUnique`](/orm/reference/prisma-client-reference#findunique) +- [`findUniqueOrThrow`](/orm/reference/prisma-client-reference#finduniqueorthrow) +- [`findFirst`](/orm/reference/prisma-client-reference#findfirst) +- [`findFirstOrThrow`](/orm/reference/prisma-client-reference#findfirstorthrow) +- [`findMany`](/orm/reference/prisma-client-reference#findmany) +- [`count`](/orm/reference/prisma-client-reference#count) +- [`aggregate`](/orm/reference/prisma-client-reference#aggregate) +- [`groupBy`](/orm/reference/prisma-client-reference#groupby) + + + +The `cacheStrategy` parameter is not supported on any write operations, such as `create`. + + + +## withAccelerateInfo + +Any query that supports the `cacheStrategy` can append `withAccelerateInfo()` to wrap the response data and include additional information about the Accelerate response. + +To retrieve the status of the response, use: + +```ts +const { data, info } = await prisma.user + .count({ + cacheStrategy: { ttl: 60, swr: 600 }, + where: { myField: 'value' }, + }) + .withAccelerateInfo() + +console.dir(info) +``` + + + +Notice the `info` property of the response object. This is where the request information is stored. + + + +### Return type + +The `info` object is of type `AccelerateInfo` and follows the interface below: + +```ts +interface AccelerateInfo { + cacheStatus: 'ttl' | 'swr' | 'miss' | 'none' + lastModified: Date + region: string + requestId: string + signature: string +} +``` + +| Property | Type | Description | +| -------------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `cacheStatus` | "ttl" \| "swr" \| "miss" \| "none" | The cache status of the response.
| +| `lastModified` | `Date` | The date the response was last refreshed. | +| `region` | `String` | The data center region that received the request. | +| `requestId` | `String` | Unique identifier of the request. Useful for troubleshooting. | +| `signature` | `String` | The unique signature of the Prisma operation. | + +## Errors + +Prisma Accelerate-related errors start with `P6xxx`. + +You can find the full error code reference for Prisma Accelerate [here](/orm/reference/error-reference#prisma-accelerate). diff --git a/docs/300-accelerate/500-limitations.mdx b/docs/300-accelerate/500-limitations.mdx new file mode 100644 index 0000000000..dec1b870a6 --- /dev/null +++ b/docs/300-accelerate/500-limitations.mdx @@ -0,0 +1,33 @@ +--- +title: 'Limitations' +metaTitle: 'Accelerate: Limitations' +metaDescription: 'Learn about limitations of Accelerate.' +tocDepth: 3 +toc: true +--- + + + +Below are descriptions of known limitations when using Accelerate. If you are aware of any limitations that are missing, please let us know on the [#accelerate-feedback](https://prisma.slack.com/archives/C04KTN0V2Q0) channel in our community Slack. + + + +## Query timeout limit + +Accelerate has a global timeout of `10s` for each query. Reach out to [support@prisma.io](mailto:support@prisma.io) with your use case if your application requires a greater timeout value. + +## Interactive transactions query timeout limit + +Accelerate has a global timeout of `15s` for each [interactive transaction](/orm/prisma-client/queries/transactions#interactive-transactions). Reach out to [support@prisma.io](mailto:support@prisma.io) with your use case if your application requires a greater timeout value. + +## Response size limit + +Accelerate has a global response size limit of `5MB`. Reach out to [support@prisma.io](mailto:support@prisma.io) with your use case if your application requires a larger response size. + +## Cannot cache raw queries + +At the moment, it is not possible to cache the responses of [raw queries](/orm/prisma-client/queries/raw-database-access/raw-queries). + +## Not compatible with the fluent API + +Client Extensions (which are used in Accelerate) currently do not correctly forward the [fluent API](/orm/prisma-client/queries/relation-queries#fluent-api) types. We hope to get a fix into Client Extensions soon. diff --git a/docs/300-accelerate/550-evaluating.mdx b/docs/300-accelerate/550-evaluating.mdx new file mode 100644 index 0000000000..dd0dd930db --- /dev/null +++ b/docs/300-accelerate/550-evaluating.mdx @@ -0,0 +1,228 @@ +--- +title: 'Evaluating' +metaTitle: 'Accelerate: Evaluating' +metaDescription: 'Learn about evaluating Prisma Accelerate.' +tocDepth: 3 +toc: true +--- + + + +Prisma Accelerate optimizes database interactions through advanced connection pooling and global edge caching. Its connection pooler is available in 16 regions and helps applications load-balance and scale database requests based on demand. + +Considering the information above, we recommend evaluating Accelerate with high volume to see it perform under load. + + + +## How Accelerate's connection pool optimizes performance under load + +Prisma Accelerate employs a dynamic, serverless connection pooling infrastructure. When a request is made, a connection pool is quickly provisioned for the project in the region assigned while configuring Prisma Accelerate. This connection pool remains active, serving many additional requests while reusing established database connections. The connection pool will disconnect after a period of inactivity, so it’s important to evaluate Prisma Accelerate with a consistent stream of traffic. + +**Key Benefits:** + +- **Optimized Query Performance:** The serverless connection pooler adapts to the query load, ensuring the database connections are managed efficiently during peak demand. + + > Prisma Accelerate’s connection pooler cannot improve the performance of queries in the database. In scenarios where query performance is an issue, we recommend optimizing the Prisma query, applying indexes, or utilizing Accelerate’s edge caching. + +- **Maximize Connection Reuse:** Executing a consistent volume of queries helps maintain active instances of Accelerate connection poolers. This increases connection reuse, ensuring faster response times for subsequent queries. + +By understanding and harnessing this mechanism, you can ensure that your database queries perform consistently and efficiently at scale. + +## Evaluating Prisma Accelerate connection pooling performance + +Below you will find an example of how to evaluate Prisma Accelerate using a sample model: + +```prisma +model Notes { + id Int @id @default(autoincrement()) + title String + createdAt DateTime @default(now()) + updatedAt DateTime? @updatedAt +} +``` + +```typescript +import { PrismaClient } from '@prisma/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient().$extends(withAccelerate()) + +function calculateStatistics(numbers: number[]): { + average: number + p50: number + p75: number + p99: number +} { + if (numbers.length === 0) { + throw new Error('The input array is empty.') + } + + // Sort the array in ascending order + numbers.sort((a, b) => a - b) + + const sum = numbers.reduce((acc, num) => acc + num, 0) + const count = numbers.length + + const average = sum / count + const p50 = getPercentile(numbers, 50) + const p75 = getPercentile(numbers, 75) + const p99 = getPercentile(numbers, 99) + + return { average, p50, p75, p99 } +} + +function getPercentile(numbers: number[], percentile: number): number { + if (percentile <= 0 || percentile >= 100) { + throw new Error('Percentile must be between 0 and 100.') + } + + const index = (percentile / 100) * (numbers.length - 1) + if (Number.isInteger(index)) { + // If the index is an integer, return the corresponding value + return numbers[index] + } else { + // If the index is not an integer, interpolate between two adjacent values + const lowerIndex = Math.floor(index) + const upperIndex = Math.ceil(index) + const lowerValue = numbers[lowerIndex] + const upperValue = numbers[upperIndex] + const interpolationFactor = index - lowerIndex + return lowerValue + (upperValue - lowerValue) * interpolationFactor + } +} + +async function main() { + const timings = [] + + // fire a query before going to the loop + await prisma.notes.findMany({ + take: 20, + }) + + // we recommend evaluationg Prisma Accelerate with a large loop + const LOOP_LENGTH = 10000 + + for (let i = 0; i < LOOP_LENGTH; i++) { + const start = Date.now() + await prisma.notes.findMany({ + take: 20, + }) + + timings.push(Date.now() - start) + } + + const statistics = calculateStatistics(timings) + console.log('Average:', statistics.average) + console.log('P50:', statistics.p50) + console.log('P75:', statistics.p75) + console.log('P99:', statistics.p99) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch((e) => { + await prisma.$disconnect() + process.exit(1) + }) +``` + +## Evaluating Prisma Accelerate caching performance + +Prisma Accelerate’s edge cache is also optimized for a high volume of queries. The cache automatically optimizes for repeated queries. As a result, the cache hit rate will increase as the query frequency does. Adding a query result to the cache is also non-blocking, so a short burst of queries might not utilize the cache or a sustained load. + +To evaluate Accelerate’s edge caching, you can modify the above script with the below: + +```typescript +import { PrismaClient } from '@prisma/client' +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient().$extends(withAccelerate()) + +function calculateStatistics(numbers: number[]): { + average: number + p50: number + p75: number + p99: number +} { + if (numbers.length === 0) { + throw new Error('The input array is empty.') + } + + // Sort the array in ascending order + numbers.sort((a, b) => a - b) + + const sum = numbers.reduce((acc, num) => acc + num, 0) + const count = numbers.length + + const average = sum / count + const p50 = getPercentile(numbers, 50) + const p75 = getPercentile(numbers, 75) + const p99 = getPercentile(numbers, 99) + + return { average, p50, p75, p99 } +} + +function getPercentile(numbers: number[], percentile: number): number { + if (percentile <= 0 || percentile >= 100) { + throw new Error('Percentile must be between 0 and 100.') + } + + const index = (percentile / 100) * (numbers.length - 1) + if (Number.isInteger(index)) { + // If the index is an integer, return the corresponding value + return numbers[index] + } else { + // If the index is not an integer, interpolate between two adjacent values + const lowerIndex = Math.floor(index) + const upperIndex = Math.ceil(index) + const lowerValue = numbers[lowerIndex] + const upperValue = numbers[upperIndex] + const interpolationFactor = index - lowerIndex + return lowerValue + (upperValue - lowerValue) * interpolationFactor + } +} + +async function main() { + const timings = [] + + // fire a query before going to the loop + await prisma.notes.findMany({ + take: 20, + cacheStrategy: { + ttl: 30, + }, + }) + + // we recommend evaluating Prisma Accelerate with a large loop + const LOOP_LENGTH = 10000 + + for (let i = 0; i < LOOP_LENGTH; i++) { + const start = Date.now() + await prisma.notes.findMany({ + take: 20, + cacheStrategy: { + ttl: 30, + }, + }) + + timings.push(Date.now() - start) + } + + const statistics = calculateStatistics(timings) + console.log('Average:', statistics.average) + console.log('P50:', statistics.p50) + console.log('P75:', statistics.p75) + console.log('P99:', statistics.p99) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch((e) => { + await prisma.$disconnect() + process.exit(1) + }) +``` diff --git a/docs/300-accelerate/580-local-development.mdx b/docs/300-accelerate/580-local-development.mdx new file mode 100644 index 0000000000..ece970a8f4 --- /dev/null +++ b/docs/300-accelerate/580-local-development.mdx @@ -0,0 +1,65 @@ +--- +title: 'Local development' +metaTitle: 'Accelerate: Local development' +metaDescription: 'Learn how to use Prisma Accelerate in a development environment.' +tocDepth: 3 +toc: true +--- + + + +Prisma Accelerate is designed to scale database connections efficiently in production environments. Prisma Accelerate also provides a global cache to reduce the load on your database and reduce query response time. To leverage Prisma Accelerate, it is essential to utilize a publicly accessible database. + +In development environments, you may want to use a local database to minimize expenses. Furthermore, you may consider extending Prisma Client with the Accelerate client extension once so that you can use a local database in development and a hosted database with Accelerate’s connection pooling and caching enabled. This eliminates the need for conditional logic to switch clients between development and production. + +This guide will explain how to use Prisma Accelerate client extension in a development environment with a local database. + + + +## Using Prisma Accelerate client extension in development and production + +
+ + +Accelerate does not work with a local database. However, in a development environment, you can still use Prisma Client with the Accelerate client extension. This setup will not provide Accelerate's connection pooling and caching features. + +The following steps outline how to use Prisma ORM and Prisma Accelerate with a local PostgreSQL database. + +1. Update the `DATABASE_URL` environment variable with your local database's connection string: + + ```.env + DATABASE_URL="postgres://username:password@127.0.0.1:5432/localdb" + ``` + +2. Generate a Prisma Client: + + ```bash + npx prisma generate + ``` + + > Note: The `--no-engine` flag should only be used in preview and production environments. The command generates Prisma Client artifacts without a [Query Engine](/orm/more/under-the-hood/engines) file, which requires an Accelerate connection string. + +3. Set up Prisma Client with the Accelerate client extension: + + ```typescript + import { PrismaClient } from '@prisma/client' + import { withAccelerate } from '@prisma/extension-accelerate' + + const prisma = new PrismaClient().$extends(withAccelerate()) + ``` + + > The extended instance of Prisma Client will use the local database. Hence, Prisma Accelerate will not be used in your development environment to respond to your Prisma Client queries. + + + +If an Accelerate connection string is used as the `DATABASE_URL` environment variable, Prisma Client will route your queries through Accelerate. + +## Using Prisma Accelerate locally in an edge function + +When using an edge function, e.g., [Vercel's edge functions](https://vercel.com/docs/functions/edge-functions), for your development environment, update your Prisma Client import as follows: + +```typescript +import { PrismaClient } from '@prisma/client/edge' +``` + +Generally, edge function environments lack native support for existing APIs enabling TCP-based database connections. Prisma Accelerate provides a connection string that allows querying your database over HTTP, a protocol supported in all edge runtimes. diff --git a/docs/300-accelerate/600-faq.mdx b/docs/300-accelerate/600-faq.mdx new file mode 100644 index 0000000000..0e525c8ca5 --- /dev/null +++ b/docs/300-accelerate/600-faq.mdx @@ -0,0 +1,99 @@ +--- +title: 'FAQ' +metaTitle: 'Accelerate: FAQ' +metaDescription: 'Frequently asked questions about Accelerate.' +tocDepth: 3 +toc: true +--- + +Below are frequently asked questions about Accelerate. + +## Why do I sometimes see unexpected cache behavior? + +Accelerate's cache performs best when it observes a higher load from a project. Many cache operations, such as committing data to cache and refreshing stale data, happen asynchronously. When benchmarking Accelerate, we recommend doing so with loops or a load testing approach. This will mimic higher load scenarios better and reduce outliers from low frequency operations. + +Prisma operations are sent to Accelerate over HTTP. As a result, the first request to Accelerate must establish an HTTP handshake and may have additional latency as a result. We're exploring ways to reduce this initial request latency in the future. + +## What is the pricing of Accelerate? + +You can find more details on our [Accelerate pricing page](https://www.prisma.io/pricing) + +## VS Code does not recognize the `$extends` method + +If you add the Prisma Client extension for Accelerate to an existing project that is currently open in VS Code, the editor might not immediately recognize the `$extends` method. + +This might be an issue with the TypeScript server not yet recognizing the regenerated Prisma Client. To resolve this, you need to restart TypeScript. + +1. In VS Code, open the Command Palette. You can do so when you press F1 or select **View** > **Command Palette**. +2. Enter `typescript` and select and run the **TypeScript: Restart TS server** command. + +VS Code should now recognize the `$extends` method. + +## What regions are Accelerate's cache nodes available in? + +Accelerate runs on Cloudflare's network and cache hits are served from Cloudflare's 300+ locations. You can find the regions where Accelerate's cache nodes are available here: [https://www.cloudflare.com/network/](https://www.cloudflare.com/network/). + +## What regions is Accelerate's connection pool available in? + +When no cache strategy is specified or in the event of a cache miss, the Prisma Client query is routed through Accelerate's connection pool. Currently, queries can be routed through any chosen region among the 16 available locations. + +Currently, the list of available regions are: + +- Asia Pacific, Mumbai (`ap-south-1`) +- Asia Pacific, Seoul (`ap-northeast-2`) +- Asia Pacific, Singapore (`ap-southeast-1`) +- Asia Pacific, Sydney (`ap-southeast-2`) +- Asia Pacific, Tokyo (`ap-northeast-1`) +- Canada, Central (`ca-central-1`) +- Europe, Frankfurt (`eu-central-1`) +- Europe, Ireland (`eu-west-1`) +- Europe, London (`eu-west-2`) +- Europe, Paris (`eu-west-3`) +- Europe, Stockholm (`eu-north-1`) +- South America, Sao Paulo (`sa-east-1`) +- US East, N. Virginia (`us-east-1`) +- US East, Ohio (`us-east-2`) +- US West, N. California (`us-west-1`) +- US West, Oregon (`us-west-2`) + +You can also view the available regions when you're about to set up Accelerate or by visiting the **Settings** tab for Accelerate under the **Region** section in the Prisma Cloud Platform [dashboard](https://pris.ly/pdp). + +## How does Accelerate know what region to fetch the cache from? + +Under the hood, Accelerate uses Cloudflare, which uses [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/) for network addressing and routing. An incoming request will be routed to the nearest data center or "node" in their network that has the capacity to process the request efficiently. To learn more about how this works, we recommend looking into [Anycast](https://www.cloudflare.com/learning/cdn/glossary/anycast-network/). + +## How can I invalidate a cache on Accelerate? + +You can invalidate your cache on a project level up to five times a day. This can be done via the Accelerate configuration page. + +## What is Accelerate's consistency model? + +Accelerate does not have a consistency model. It is not a distributed system where nodes need to reach a consensus (because data is only stored in the cache node(s) closest to the user). However, the data cached in Accelerate's cache nodes doesn't propagate to other nodes, so Accelerate by design doesn't need a consistency model. + +Accelerate implements a [read-through caching strategy](https://www.prisma.io/dataguide/managing-databases/introduction-database-caching#read-through) particularly suitable for read-heavy workloads. + +The freshness of the data served by the cache depends on the cache strategy defined in your query. Refer to [this section](https://www.notion.so/Accelerate-documentation-469a2162ab71487e9027403249d9b58f?pvs=21) for more information on selecting the right cache strategy for your query. + +## How is Accelerate different from other caching tools, such as Redis? + +- Accelerate is a _specialized_ cache that allows you to optimize data access in code at the query level with a cache strategy. On the other hand, tools such as Redis and Memcached are _general-purpose_ caches designed to be adaptable and flexible. +- Accelerate is a managed service that reduces the time, risk, and engineering effort of building and maintaining a cache service. +- By default, Accelerate is globally distributed, reducing the latency of your queries. Other cache tools would require additional configuration to make them available globally. + +## When should I not use Accelerate's caching features? + +Accelerate is a global data cache and connection pool that allows you to optimize data access in code at the query level. While caching with Accelerate can greatly boost the performance of your app, it may not always the best choice for your use case. + +Accelerate's global cache feature may not be a good fit for your app if: + +- Your app is exclusively used within a specific region and both your application server and database are situated in that same region on the same network. For example, database queries will likely be much faster if your application server and database are in the same region and network. However, If your application server is in different regions or networks from your database, Accelerate will speed up your queries because the data will be cached in the closest data center to your application. + +- You _only_ need a general-purpose cache. Accelerate is a connection pooler and a _specialized cache_ that only caches your database query responses in code. A general-purpose cache, such as Redis, would allow you to cache data from multiple sources, such as external APIs, which Accelerate currently doesn't support. If general-purpose caching interests you, please share your feedback with us in the [`#accelerate-feedback`](https://prisma.slack.com/archives/C04KTN0V2Q0) channel on our Slack community. + +- Your application data _always_ needs to be up-to-date on retrieval, which would be difficult to set a reasonable cache strategy. + +Even without using Accelerate's global cache, you can still greatly benefit from Accelerate by using its connection pool, especially in serverless or edge functions, where it is difficult to manage and scale database connections. You can learn more about the serverless challenge [here](/orm/prisma-client/setup-and-configuration/databases-connections#the-serverless-challenge). + +## Can I use Accelerate with other ORMs/query builders/drivers? + +No. We currently do not have any plans for supporting other ORMs/query builders or drivers. However, if you're interested in support for other libraries, feel free to reach out and let us know in our [Discord](https://pris.ly/discord) community in the `#accelerate-feedback` channel. diff --git a/docs/300-accelerate/700-feedback.mdx b/docs/300-accelerate/700-feedback.mdx new file mode 100644 index 0000000000..08755185e4 --- /dev/null +++ b/docs/300-accelerate/700-feedback.mdx @@ -0,0 +1,13 @@ +--- +title: 'Feedback' +metaTitle: 'Accelerate: Feedback' +metaDescription: 'Learn where to submit feedback about Accelerate.' +tocDepth: 3 +toc: true +--- + + + +You can submit any feedback about Accelerate in the [#accelerate-feedback](https://prisma.slack.com/archives/C04KTN0V2Q0) channel in our community [Slack](https://slack.prisma.io/) and in our [Discord server](https://discord.gg/prisma-937751382725886062). + + diff --git a/docs/300-accelerate/index.mdx b/docs/300-accelerate/index.mdx new file mode 100644 index 0000000000..e1e11ae428 --- /dev/null +++ b/docs/300-accelerate/index.mdx @@ -0,0 +1,16 @@ +--- +title: 'Accelerate' +metaTitle: 'Prisma Accelerate' +metaDescription: 'Prisma Accelerate is a global database cache with built-in connection pooling that helps improve database performance in Serverless and Edge applications.' +toc: false +--- + + + +[Prisma Accelerate](https://www.prisma.io/data-platform/accelerate) is a global database cache and scalable connection pool that helps improve database performance in Serverless and Edge applications. + + + +## In this section + + diff --git a/docs/400-pulse/100-what-is-pulse.mdx b/docs/400-pulse/100-what-is-pulse.mdx new file mode 100644 index 0000000000..85b4266ea2 --- /dev/null +++ b/docs/400-pulse/100-what-is-pulse.mdx @@ -0,0 +1,21 @@ +--- +title: 'What is Pulse' +metaTitle: 'What is Pulse' +metaDescription: 'Learn about Pulse, a managed Change Data Capture service that lets you build real-time applications with ease.' +tocDepth: 3 +toc: true +--- + + + +[Pulse](https://www.prisma.io/data-platform/pulse) is a managed [change data capture (CDC)](https://en.wikipedia.org/wiki/Change_data_capture) service that captures change events from your database and delivers them instantly to your applications. With Pulse, you can quickly build real-time applications in a type-safe manner using [Prisma Client](/orm/prisma-client). + + + +Pulse is currently in [Early Access](/platform/maturity-levels#early-access). Although we already have high confidence in it, the nature of an Early Access product is that significant iterations might happen at any time. Therefore, we advise against using it in a system that requires stability.

+ +We strongly recommend evaluating Pulse with a dedicated database instance that is exclusively used for Pulse and where downtime and data loss would be acceptable. Prisma assumes no responsibility for downtime or data loss. + +
+ +
diff --git a/docs/400-pulse/200-getting-started.mdx b/docs/400-pulse/200-getting-started.mdx new file mode 100644 index 0000000000..f63608c33a --- /dev/null +++ b/docs/400-pulse/200-getting-started.mdx @@ -0,0 +1,209 @@ +--- +title: 'Getting started' +metaTitle: 'Getting started with Pulse' +metaDescription: 'Learn how to get up and running with Pulse.' +tocDepth: 3 +toc: true +--- + + + +## Prerequisites + +To participate in Pulse's Early Access program, you need to meet the following prerequisites: + +- A GitHub account. +- Pulse requires [Prisma Client](/orm/prisma-client) version `4.16.1` or higher and [`@prisma/extension-pulse`](https://www.npmjs.com/package/@prisma/extension-pulse) version `v0.2.1` or higher. +- A publicly accessible PostgreSQL database. +- Ability to use the superuser account of the database instance. In the future, we will support the ability to connect to your database from Pulse with a limited access, non-superuser account. + +You will also need a database with the following configurations: + +- PostgreSQL version 12+. +- Ensure your database is publicly accessible. +- [Set the `wal_level` setting in PostgreSQL to `logical`](/pulse/getting-started#wal_level). +- A database superuser that can be used for connections inside Pulse. +- Connect to the database using `sslmode=disable` if the database provider uses self-signed certificates. + +## 1. Database setup + +### General database configuration + +#### Required settings + +##### [wal_level](https://www.postgresql.org/docs/current/runtime-config-wal.html) + +Some providers may not allow direct access to this setting. If you are unable to change this setting, please refer to the provider-specific guides for further assistance. + +```sql +ALTER SYSTEM SET wal_level = logical; +``` + +You will need to restart the database after changing this setting. + +#### Optional settings + +The following increases the memory usage of the [write-ahead log](https://www.postgresql.org/docs/current/wal-intro.html) on your PostgreSQL database. We suggest setting these values initially and adjusting them if necessary. + +##### [max_replication_slots](https://www.postgresql.org/docs/current/runtime-config-replication.html) + +```sql +ALTER SYSTEM SET max_replication_slots = 20; +``` + +##### [wal_keep_size](https://www.postgresql.org/docs/current/runtime-config-replication.html) + +```sql +ALTER SYSTEM SET wal_keep_size = 2048; +``` + +### Provider specific configuration + +To learn about the database providers that Pulse supports, visit [here](/pulse/faq#what-database-providers-are-supported-with-pulse). + +#### Railway + +[Railway.app](https://railway.app) offers an excellent [templates feature](https://railway.app/templates). If you wish to quickly start with Pulse, you can use either of two templates: + +- [Prisma Pulse DB Only](https://railway.app/template/pulse-pg): Provides a fresh, pre-configured PostgreSQL database which you can use with Pulse. +- [Prisma Pulse DB & App](https://railway.app/template/pulse-starter): Provides a pre-configured PostgreSQL database and a [Pulse starter app](https://github.com/prisma/pulse-starter). + +##### Setup without using a template + +
+1. Change the PostgreSQL database settings + +You can run these queries in the Railway Database **Query** tab, using the [railway cli](https://docs.railway.app/databases/postgresql), or any other way you might run queries on your database. + +1. Drop the Timescale extension: + +```sql +DROP EXTENSION timescaledb; +``` + +2. Set the [wal_level](https://www.postgresql.org/docs/current/runtime-config-wal.html) to `logical`: + +```sql +ALTER SYSTEM SET wal_level = logical; +``` + +3. Set the [max_replication_slots](https://www.postgresql.org/docs/current/runtime-config-replication.html) to `20`: + +```sql +ALTER SYSTEM SET max_replication_slots = 20; +``` + +4. Set the [wal_keep_size](https://www.postgresql.org/docs/current/runtime-config-replication.html) to `2048`: + +```sql +ALTER SYSTEM SET wal_keep_size = 2048; +``` + +5. Reload the PostgreSQL configuration: + +```sql +SELECT pg_reload_conf(); +``` + +
+
+2. Restart your database + +1. Click on your database. + +2. Navigate to the Deployments tab. + +3. Go into the three-dots menu on the latest deployment and click the `Restart` option. + +
+ +##### SSL mode + +As Railway uses a self-signed certificate, you have to use [`sslmode=disable`](/orm/overview/databases/postgresql#configuring-an-ssl-connection) with Pulse. + +## 2. Enable Pulse in a project + +Log into the [Prisma Data Platform](https://console.prisma.io/login), create a new project and enable Pulse for that new project. + +> An API key will be created after you enable and setup Pulse in your [project](/platform/concepts/projects). + +## 3. Use Pulse in your application + + + +We have created an [example repository](https://github.com/prisma/pulse-starter) on GitHub to help you get started using Pulse. If you would like to start there, you can do so. + + + +The following will show how you can utilize Pulse in an existing application. We will be adding Pulse to the [hello-prisma](/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-postgresql) example from our documentation. + +### 3.1. Install the Pulse Prisma Client extension + +In a project using [Prisma Client](/orm/prisma-client), run the following command to install the Pulse extension: + +```terminal +npm install @prisma/extension-pulse +``` + +### Store your Pulse API key in your .env file + +The Pulse extension requires you to use an API key. + + + +You should have received an API key when you added Prisma Pulse to your project in the Platform Console. + + + +In `.env`, add a variable named `PULSE_API_KEY`: + +```env file=.env +PULSE_API_KEY="YOUR-API-KEY" + +# Example: +# PULSE_API_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlfa2V5IjoiNGMxNzM0MGItMmFhYy00MGMxLWE1ZDctNzYyNmRjNjg3NjM4IiwidGVuYW50X2lkIjoiY2VhZjE0NThkZGUyYzJmNTU0ZmNkNTI2MmFmOWY1ODljMWJiZmRhNDU0N2UxMjM1ODk3MGQ2MGI1ZjRlNTU0OCIsImludGVybmFsX3NlY3JldCI6ImM1ZTcxYjJhLTE0NzdawdwDliZS1hM2IzLTczODFkNDM5ZmEwZSJ9.wCUlghC_suFBr2vnk0q_5I8iRNRDyEQo0W9rnhf6mCw" +``` + +### 3.2. Create a Pulse-enabled Prisma Client + +To use Pulse, you must extend Prisma Client with the Pulse extension. +Add the following to extend your existing Prisma Client instance with the Pulse extension: + +```ts +import { PrismaClient } from '@prisma/client' +import { withPulse } from '@prisma/extension-pulse' + +const prisma = new PrismaClient().$extends( + withPulse({ apiKey: process.env.PULSE_API_KEY }) +) +``` + +### 3.3. Create your first Pulse subscription + +With the Pulse extension applied, you may now use Pulse's `subscribe()` method on any model defined in your Prisma Schema to subscribe to data change events. + +In the example below, a subscription is made on a `user` table that listens for _any_ change event on that table: + +```ts +const prisma = new PrismaClient().$extends(withPulse({ apiKey: apiKey })) + +async function main() { + const subscription = await prisma.user.subscribe({}) + + if (subscription instanceof Error) { + throw subscription + } + + for await (const event of subscription) { + console.log('just received an event:', event) + } +} + +main() +``` + + + +Refer to the [API Reference](/pulse/api-reference) section for more detail on the filtering options available to the `subscribe()` method. + + diff --git a/docs/400-pulse/300-concepts.mdx b/docs/400-pulse/300-concepts.mdx new file mode 100644 index 0000000000..022f04ee44 --- /dev/null +++ b/docs/400-pulse/300-concepts.mdx @@ -0,0 +1,23 @@ +--- +title: 'Concepts' +metaTitle: 'Pulse: Concepts' +metaDescription: 'Learn about the concepts that are important to understand when using Pulse.' +tocDepth: 3 +toc: true +--- + + + +## Change data capture + +[Change data capture (CDC)](https://en.wikipedia.org/wiki/Change_data_capture) is a technique used to track and capture changes in a database enabling real-time updates. It allows applications to be informed about the modifications in the database, ensuring data consistency between multiple applications. + +## Logical replication + +Logical replication is a method of replicating data objects and their changes based on their replication identity (usually a primary key). You can read more about logical replication and how it pertains to your database in Postgres' documentation [here](https://www.postgresql.org/docs/current/logical-replication.html). + +## Write-ahead log + +A [write-ahead log (WAL)](https://www.postgresql.org/docs/current/wal-intro.html) is a standard way of ensuring data integrity by only allowing updates to the data in a database _after_ a log has been written to permanent storage describing the change to take place. + +This enhances data integrity because all changes to a database are recorded in these log files. In the event of a database crash, the database is recoverable using those logs and can even be recovered to a specific point in time. diff --git a/docs/400-pulse/400-api-reference.mdx b/docs/400-pulse/400-api-reference.mdx new file mode 100644 index 0000000000..c6a3246039 --- /dev/null +++ b/docs/400-pulse/400-api-reference.mdx @@ -0,0 +1,287 @@ +--- +title: 'API Reference' +metaTitle: 'Pulse: API Reference' +metaDescription: 'API reference documentation for Pulse.' +tocDepth: 4 +toc: true +--- + + + +The Pulse API reference documentation is based on the following schema: + +```prisma +model User { + id Int @id @default(autoincrement()) + name String? + email String @unique +} +``` + +All example are based on the `User` model. + + + +## subscribe + +`subscribe` returns all data change events related to the table you call this method on: + +```ts +const subscription = await prisma.user.subscribe() +``` + +### Remarks + +Passing an empty object to the `subscribe` function will also behaves the same as passing no argument to the function: + +```ts +const subscription = await prisma.user.subscribe({}) +``` + +### Database event filters + +Inside of the `subscribe()` method you can use filters to get specific events and data. The three filter options currently supported are described below: + +#### create + +You can use the `create` filter to retrieve all _create_ events on a table. A create event is triggered when a new record is created in a table. + +Pulse returns the values of the new record as an object named `after`. + +##### Example + + + + +```ts +const subscription = await prisma.user.subscribe({ + create: {}, +}) +``` + + + + +```ts no-copy +{ + action: 'create', + after: { + id: 1, + email: 'marc@prisma.io', + name: 'Marc' + } +} +``` + + + + +#### update + +You can use the `update` filter to retrieve all _update_ events on a table. An update event is triggered when a value in a database record has changed. + +Pulse returns the values of the changed record as an object named `after`. This represents the state of the record _after_ the change event. + +##### Example + + + + +```ts +const subscription = await prisma.user.subscribe({ + update: {}, +}) +``` + + + + +```ts no-copy +{ + action: 'update', + after: { + id: 1, + email: 'updated@prisma.io', + name: 'Marc' + } +} +``` + + + + +#### delete + +You can use the `delete` filter to retrieve all _delete_ events on a table. A delete event is triggered when a record has been removed from the database. + +Pulse returns the values of the changed record as an object named `before`. This represents the state of the record _before_ the change event. + +##### Example + + + + +```ts +const subscription = await prisma.user.subscribe({ + delete: {}, +}) +``` + + + + +```ts no-copy +{ + action: 'delete', + before: { + id: 1, + email: '', + name: null + } +} +``` + + + + + + +By default, the response for `delete` events will only return the primary key of the record. To get the _before_ values of all fields in the record, you must set `REPLICA IDENTITY` to `FULL` on the table(s) you want to get field values for. If this is not configured, defining a filter for deletes will only be possible on the primary key.

+For example, running the following SQL command will set the `REPLICA IDENTITY` to `FULL` on a table named `User`: + +```sql +ALTER TABLE public."User" REPLICA IDENTITY FULL; +``` + +
+ +### Filter conditions and operators + +Pulse allows you to subscribe to change events based on filter conditions and operators. Pulse supports all of Prisma Client’s [supported filter conditions and operators](/orm/reference/prisma-client-reference#filter-conditions-and-operators) except for `search` and `mode`. You also won't be able to define filters that reference other models via relations. + +You must wrap your filter criteria inside a `before` or `after` object depending on the type of event your subscription is listening for: + +- `before`: `delete` events +- `after`: `create` and `update` events + +This makes it explicit that the specified filter criteria apply to the `before` or `after` state of the change event. + + + +In the future, Pulse may support the ability to return both the `before` and `after` state of `update` change events and filter on either state. If these are features you’re interested in, please let us know on the [#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel in our community Slack. + + + +#### Usage in the after state filter + +Using a filter inside of `after` will return changed records that match your filter criteria as applied to the state of the record after the change event. + +##### Examples + +Get `create` events where the value of name is equal to `'Jim'` after the event has occurred: + + + + +```ts +const subscription = await prisma.user.subscribe({ + create: { + after: { + name: 'Jim', + }, + }, +}) +``` + + + + +```ts no-copy +{ + action: 'create', + after: { + id: 6, + email: 'test@test.com', + name: 'Jim' + } +} +``` + + + + +Get `update` events where the value of name is equal to `Jim` after the event has occurred: + + + + +```ts +const subscription = await prisma.user.subscribe({ + update: { + after: { + name: 'Jim', + }, + }, +}) +``` + + + + +```ts no-copy +{ + action: 'update', + after: { + id: 6, + email: 'updated@test.com', + name: 'Jim', + } +} +``` + + + + +#### Usage in the before state filter + +Using a filter inside of `before` will return changed records that match your filter criteria as applied to the state of the record before the change event. + +##### Example + +Get delete events where the value of name was equal to Marc. + + + + +```ts +const subscription = await prisma.user.subscribe({ + delete: { + before: { + name: 'Jim', + }, + }, +}) +``` + + + + +```ts no-copy +{ + action: 'update', + after: { + id: 6, + email: 'updated@test.com', + name: 'Jim', + } +} +``` + + + + + + +Specifying a filter condition for delete events only works if you’ve set the table’s `REPLICA IDENTITY` to `FULL`. See [this section](/pulse/api-reference#delete) for more details. + + diff --git a/docs/400-pulse/500-current-limitations.mdx b/docs/400-pulse/500-current-limitations.mdx new file mode 100644 index 0000000000..832685c361 --- /dev/null +++ b/docs/400-pulse/500-current-limitations.mdx @@ -0,0 +1,63 @@ +--- +title: 'Current limitations' +metaTitle: 'Pulse: Current limitations' +metaDescription: 'Learn about current limitations of Pulse.' +tocDepth: 3 +toc: true +--- + + + +Below are descriptions of known limitations when using Pulse. If you are aware of any limitations that are missing, please let us know on the [#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel in our community Slack. + + + +## Superuser account required + +You must connect to your database instance from Pulse using a superuser account. In the future, we will enable non-superuser accounts with limited access privileges to be used with Pulse. + +## Limited throughput of change events + +While in Early Access, there may be limits to the throughput of change events that can be captured and delivered. We plan to provide transparent scale-up capabilities in the future. + +## Limited to 10 active subscriptions per table + +Initially you will be limited to 10 active subscriptions per table. This limitation will be lifted in the future. + +## Change events are not persisted + +Pulse does not persist change events and does not provide delivery guarantees with regards to ordering or exact-once/at-least-once delivery. + +An application must maintain an active connection to Pulse using the `subscribe()` method to capture change events; change events that occur while a Prisma Client is not subscribed will not be delivered. + +## Front-end use is not possible + +Pulse cannot be used in the front-end portion of an application. + + + +If you would find this capability valuable, please share your thoughts on the[#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel on our community Slack. + + + +## Limited to Postgres versions 12 or higher + +Pulse is currently supported with Postgres versions 12 or higher. It should work with most Postgres providers that expose Postgres’ native logical replication feature. We plan on adding support for MySQL in our GA release. + + + +If you have questions about whether your database is supported, please reach out to us on the [#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel on our community Slack. + + + +## Pulse will not attempt a reconnect or give an indication of the network is disconnected + +Currently, if there is some type of network disconnect while Prisma Client is subscribed to Pulse, there will be no attempts to reconnect or indicate the connection has dropped. + +For example, if you are evaluating Pulse from an application running on your laptop and it goes to sleep resulting in a network disruption, it can appear as though the Prisma Client instance is still subscribed to Pulse when it is not. + +We will soon add heart-beating capability that throws an error to the Prisma Client when the connection is no longer active so the application can reconnect. + +## Self-signed certificates are not supported yet + +Prisma Pulse is not compatible with self-signed certificates yet. Cloud providers using these certificates will only work if the [`sslmode`](/orm/overview/databases/postgresql#configuring-an-ssl-connection) is set to `sslmode=disable`. Pulse works with any certificate provided the `sslmode` is set to `disable`. diff --git a/docs/400-pulse/600-faq.mdx b/docs/400-pulse/600-faq.mdx new file mode 100644 index 0000000000..7cde2af090 --- /dev/null +++ b/docs/400-pulse/600-faq.mdx @@ -0,0 +1,48 @@ +--- +title: 'FAQ' +metaTitle: 'Pulse: FAQ' +metaDescription: 'Frequently asked questions about Pulse.' +tocDepth: 3 +toc: true +--- + +Below are frequently asked questions about Pulse. + +## Does Pulse work in a serverless environment? + +Pulse will natively support serverless environments soon after it launches to [General Availability](/platform/maturity-levels#general-availability). + +While in [Early Access](/platform/maturity-levels#early-access), Pulse works best when it is able to maintain a long-running active connection with your application. However, many serverless runtime providers limit the duration of serverless functions. We’re actively working on improving the experience in serverless applications. + + + +Please reach out to us on the [#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel on our community Slack if having a more native serverless approach to getting data change events is important to you. + + + +## How does Pulse handle schema changes in the database? + +Pulse is designed to work seamlessly with schema changes in your database by utilizing [Change data capture (CDC)](https://en.wikipedia.org/wiki/Change_data_capture) techniques and combining that with the power of schema-driven data access using [Prisma Client](/orm/prisma-client). When your Prisma schema is updated, Pulse automatically adapts to the changes, ensuring that your real-time data synchronization remains consistent and reliable. + +Pulse leverages the type information generated by Prisma to create type-safe database subscriptions, allowing you to catch potential issues at compile time and maintain the integrity of your data throughout the development process. This approach allows Pulse to efficiently capture and propagate data changes while maintaining compatibility with evolving database structures. + +## What databases are supported with Pulse? + +The Pulse Early Access release supports PostgreSQL with plans to extend support to MySQL in the near future. + +Pulse primarily interfaces with a database's write-ahead log (Postgres) or binlog (MySQL) to efficiently capture data change events, offering a more performant solution than regular polling through scheduled queries. Note that Pulse may not work with every Postgres-compatible database, as compatibility depends on the exposure of Postgres-native logical replication capabilities required for change data capture. + + + +Pulse’s database compatibility list will be different from Prisma Client's database compatibility list. If you want to use Pulse with an existing Prisma application, please verify the database and hosting provider are supported by Pulse. + + + +## What database providers are supported with Pulse? + +| Provider | Support | Notes | +| -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Railway | ✅ | Requires [`sslmode=disable`](/orm/overview/databases/postgresql#configuring-an-ssl-connection) due to the use of a self-signed certificate for database connections by Railway. | +| Supabase | ✅ | Requires [`sslmode=disable`](/orm/overview/databases/postgresql#configuring-an-ssl-connection) due to the use of a self-signed certificate for database connections by Supabase. | +| Neon | _Coming_ | Support details coming soon. | +| AWS RDS | _Coming_ | Support details coming soon. | diff --git a/docs/400-pulse/700-feedback.mdx b/docs/400-pulse/700-feedback.mdx new file mode 100644 index 0000000000..defdda8d95 --- /dev/null +++ b/docs/400-pulse/700-feedback.mdx @@ -0,0 +1,13 @@ +--- +title: 'Feedback' +metaTitle: 'Pulse: Feedback' +metaDescription: 'Learn where to submit feedback about Pulse.' +tocDepth: 3 +toc: true +--- + + + +You can submit any feedback about Pulse in the [#pulse-feedback](https://prisma.slack.com/archives/C058GKE3C1E) channel in our community Slack. + + diff --git a/docs/400-pulse/index.mdx b/docs/400-pulse/index.mdx new file mode 100644 index 0000000000..c8072bcb67 --- /dev/null +++ b/docs/400-pulse/index.mdx @@ -0,0 +1,17 @@ +--- +title: 'Pulse' +metaTitle: 'Prisma Pulse' +metaDescription: 'Prisma Pulse enables real-time database events with type-safe Prisma Client subscriptions.' +toc: false +earlyaccess: true +--- + + + +[Prisma Pulse](https://www.prisma.io/data-platform/pulse) enables real-time database events with type-safe Prisma Client subscriptions. + + + +## In this section + + diff --git a/docs/500-platform/10-about.mdx b/docs/500-platform/10-about.mdx new file mode 100644 index 0000000000..430005b288 --- /dev/null +++ b/docs/500-platform/10-about.mdx @@ -0,0 +1,16 @@ +--- +title: 'About' +metaTitle: 'Platform Console: About' +metaDescription: '' +--- + + + +Platform Console enables you to integrate the latest Prisma Data Platform products into your application + +- [Accelerate](/accelerate/what-is-accelerate): Global database cache with scalable connection pooling +- [Pulse](/pulse/what-is-pulse): A managed Change Data Capture (CDC) service that enables real-time database subscriptions + +[Launch Platform Console](https://console.prisma.io) + + diff --git a/docs/500-platform/20-concepts/10-workspaces.mdx b/docs/500-platform/20-concepts/10-workspaces.mdx new file mode 100644 index 0000000000..910b3f6f04 --- /dev/null +++ b/docs/500-platform/20-concepts/10-workspaces.mdx @@ -0,0 +1,19 @@ +--- +title: 'Workspaces' +metaTitle: 'Platform Console: Workspaces' +metaDescription: 'Learn how to manage workspaces via Platform Console.' +tocDepth: 3 +toc: true +--- + + + +Workspaces provide a unified space for team collaboration on projects. Manage membership and billing directly within each Workspace. + + + +## Billing + +For your Workspace, you can choose a subscription plan that aligns closely with your requirements. Every project within a Workspace adds to the collective usage, ensuring a holistic view of consumption. + +More details on our subscription plans will be available soon. diff --git a/docs/500-platform/20-concepts/20-projects.mdx b/docs/500-platform/20-concepts/20-projects.mdx new file mode 100644 index 0000000000..7af0f03a13 --- /dev/null +++ b/docs/500-platform/20-concepts/20-projects.mdx @@ -0,0 +1,17 @@ +--- +title: 'Projects' +metaTitle: 'Platform Console: Projects' +metaDescription: 'Learn how to manage projects via Platform Console.' +tocDepth: 3 +toc: true +--- + + + +Projects embody your applications integrated with our products. Each project is associated with a Workspace and can be configured independently from one another. + + + +## API Keys + +A project API key is required to authenticate requests from your Prisma Client to products such as Accelerate and Pulse. You may generate multiple API keys per project and manage those via the **Settings** tab of a project's page. diff --git a/docs/500-platform/20-concepts/index.mdx b/docs/500-platform/20-concepts/index.mdx new file mode 100644 index 0000000000..2e62e7a25e --- /dev/null +++ b/docs/500-platform/20-concepts/index.mdx @@ -0,0 +1,14 @@ +--- +title: 'Concepts' +metaTitle: 'Platform Console: Concepts' +metaDescription: '' +tocDepth: 4 +--- + + + +Learn about the main building blocks of Platform Console, such as workspaces, projects, and billing. + + + + diff --git a/docs/500-platform/30-maturity-levels.mdx b/docs/500-platform/30-maturity-levels.mdx new file mode 100644 index 0000000000..e878bf221a --- /dev/null +++ b/docs/500-platform/30-maturity-levels.mdx @@ -0,0 +1,43 @@ +--- +title: 'Maturity levels' +metaTitle: 'Platform Console: Maturity levels' +metaDescription: '' +--- + + + +Prisma releases updates to Prisma Data Platform multiple times per week, as opposed to the Prisma ORM that we release on a set schedule every few weeks. This is why we consider the lifecycle and process for maturing features in Prisma Data Platform differently. + +You can [check out the releases and maturity process for the Prisma ORM](/orm/more/releases) for further details. + + + +## + +### Early Access + +If a feature on the Prisma Data Platform is labeled as **Early Access**: + +- We have validated a problem and are considering a solution to it but are not certain whether that solution is complete or a perfect fit. +- We want to gather more feedback and adjust the solution as necessary, knowing that users are prepared for significant breaking changes +- We reserve ourselves the right to throttle or remove access to a feature in Early Access to preserve the stability of the platform, or enforcing its use to stay within the scope defined in our [Terms of Service](https://pris.ly/privacy). + +As always, your feedback in our [Slack](https://slack.prisma.io/) or [Discord](https://pris.ly/discord) is invaluable to shape the design of the features. This will help us ensure that they can solve your problems in the best way possible. + +### Preview + +If a feature on the Prisma Data Platform is labeled as **Preview**: + +- We have refined the software based on the valuable feedback we obtained during the Early Access phase. +- We developed the feature further, bringing it closer to the final version, though it's not completely ready for production usage. +- We have lifted the invite gate, so users no longer need an invitation to access the feature. Users just need to sign up to gain access. +- We have increased the stability of the software compared to the Early Access phase. While there might still be some issues, they should be less frequent and less critical. +- We use the Preview phase as a final stress test to ensure the product is ready for heavy production workloads. + +We recommend testing the product in a staging environment and welcome any feedback in our [Slack](https://slack.prisma.io/) or [Discord](https://pris.ly/discord). This will assist us in improving the product for its final release. + +### General Availability + +If a feature in the Prisma Data Platform is Generally Available: + +- The solution has undergone extensive testing and, based on significant feedback, is deemed stable and ready for production use cases. diff --git a/docs/500-platform/40-limits.mdx b/docs/500-platform/40-limits.mdx new file mode 100644 index 0000000000..888e642bd0 --- /dev/null +++ b/docs/500-platform/40-limits.mdx @@ -0,0 +1,12 @@ +--- +title: 'Limits' +metaTitle: 'Platform Console: Limits' +tocDepth: 3 +toc: true +--- + + + +More details on limits will be available soon. + + diff --git a/docs/500-platform/50-support.mdx b/docs/500-platform/50-support.mdx new file mode 100644 index 0000000000..d058d632d7 --- /dev/null +++ b/docs/500-platform/50-support.mdx @@ -0,0 +1,31 @@ +--- +title: 'Support' +metaTitle: 'Platform console: Support' +metaDescription: '' +tocDepth: 3 +toc: true +--- + + + +Your feedback is invaluable, and we encourage you to share your experiences with us on [Discord](https://pris.ly/discord). + + + +### Community Support + +Reach out to us in our [Discord](https://pris.ly/discord). + +### Standard Support + +- Email support, support@prisma.io +- Mon-Fri, 9am-5pm CET + +### Premium Support + +- Email support, support@prisma.io +- 24/7 + +### Dedicated Support + +Dedicated contact person. diff --git a/docs/500-platform/index.mdx b/docs/500-platform/index.mdx new file mode 100644 index 0000000000..05c12f5fc3 --- /dev/null +++ b/docs/500-platform/index.mdx @@ -0,0 +1,17 @@ +--- +title: 'Platform' +metaTitle: 'Platform' +metaDescription: 'Get started with the Prisma Data Platform with its official documentation, and learn more about its features with reference documentation, guides, and more.' +toc: false +# earlyaccess: false +--- + + + +Learn about the main concepts and workflows of the [Prisma Data Platform](https://prisma.io/data-platform/). + + + +## In this section + + diff --git a/docs/600-about/200-prisma-docs/10-about-the-docs.mdx b/docs/600-about/200-prisma-docs/10-about-the-docs.mdx new file mode 100644 index 0000000000..bc8c45948d --- /dev/null +++ b/docs/600-about/200-prisma-docs/10-about-the-docs.mdx @@ -0,0 +1,31 @@ +--- +title: 'About the docs' +metaTitle: 'About the Prisma documentation' +metaDescription: 'This page gives a meta-overview about different topics that are relevant to better understand and navigate the Prisma documentation.' +tocDepth: 3 +--- + + + +`User` and `Post` are the canonical models that are being used throughout the Prisma docs. This page gives some context on why these have been selected and how to interpret them. + + + +## The `User` and `Post` data model + +The `User` and `Post` models have been selected for the following reasons: + +- These two models do not require domain-specific knowledge. +- They are also commonly used as an example in the ORM space, making them familiar for users coming from other tools. +- Having consistent models makes it easier for the reader when learning about different concepts, since there will be less context switching. +- Less decision making and cognitive overhead for the docs authors. Using the same models reduces decision fatigue and is one less thing to worry about when trying to explain concepts. + +We are actively working on [adding more schema examples](https://github.com/prisma/docs/issues/1626) to the docs to provide you with starting points for common data models, such as ecommerce. + +## Naming conventions for tables and columns + +Table names are generally spelled in [PascalCase](https://en.wikipedia.org/wiki/Camel_case). Column names in [camelCase](https://en.wikipedia.org/wiki/Camel_case). + +## Embrace redundancy + +Meet the user where they are. diff --git a/docs/600-about/200-prisma-docs/20-style-guide/01-writing-style.mdx b/docs/600-about/200-prisma-docs/20-style-guide/01-writing-style.mdx new file mode 100644 index 0000000000..299e0a0073 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/01-writing-style.mdx @@ -0,0 +1,168 @@ +--- +title: 'Writing style' +metaTitle: 'Prisma docs style guide: writing style' +metaDescription: 'This section of the style guide provides guidelines on tone of voice, audience, and other tonal matters.' +tocDepth: 4 +search: false +--- + +## Audience + +We assume that our audience has basic software development knowledge. Our audience know how to use their tools, such as their IDE and a terminal window. Many of our users are familiar with advanced software development concepts and techniques, but we cannot assume this in the docs. We cannot assume that our users have any database knowledge. + +## Simplify + +It's a good principle of technical communication to write as simply as possible. This is harder than it sounds, but the extra work is worth it to make clearer, more readable docs. It's particularly important when you write for a global audience, not all of whom are fluent with English. + +- Use short paragraphs +- Stick to short, simple sentences. Where possible, avoid sentences with multiple clauses. +- English has many synonyms - where possible, choose the simplest available word for the job. Examples: "in" instead of "within", "use" instead of "utilize". +- Use bullet lists to break up complex sentences into component points +- Use examples +- Use [appropriate text emphasis, such as bold and italics](/about/prisma-docs/style-guide/spelling-punctuation-formatting#text-emphasis) to make your writing clearer +- Use tables to set out complex information +- Use diagrams to make complex workflows or concepts easier to visualize + +## Tone of voice + +Write in a calm, assured tone of voice. Our tone is friendly and direct, but [we don't use slang](#avoid-emojis-slang-and-metaphors). + +## Write in US English + +US English is the most globally recognized form of English. Use US English punctuation, grammar, and spelling. For example: + +- `color` over `colour` +- `behavior` over `behaviour` +- `Prisma plans to` over `Prisma plan to` + +## Avoid emojis, slang, and metaphors + +Avoid emojis, idiomatic expressions, slang, and metaphors. Prisma has a global community, and the cultural meaning of these items might be different around the world, and can change over time. + +## Avoid imprecise pronouns like "it" or "that" + +Try to be as specific as possible when you refer to a specific noun. Do not refer to the noun as "it" unless you have just defined the proper noun in a previous sentence or clause. Even then, your writing might be clearer for international audiences if you specify the noun again. In particular, avoid starting sentences with "It". + +## Write in the second person + +The second person ("you") gives a conversational tone and speaks directly to the reader. Avoid the first person ("I", "we", "let's", and "us"). Example: + +> "You must commit the entire `prisma/migrations` folder to source control." + +Exception: Use "we" when you refer to Prisma the organization. For example, here Prisma (the organization) recommends a course of action: + +> "We recommend that you share a single instance of `PrismaClient` across your application". + +## Use inclusive language + +When you refer to one or more people in the third person, use inclusive, gender-neutral language. Use "they/them/their" instead of "he/him/his" or "she/her/her". Avoid gender-specific words like "guys". + +## Jargon + +> Jargon: (n.) special words or expressions that are used by a particular profession or group and are difficult for others to understand. + +The Prisma docs include a lot of technical detail, and jargon is unavoidable. However, we strive to use as little jargon as possible. + +When you use jargon, follow these guidelines: + +- If you can explain the jargon in a few words, then you might prefer to explain it there and then. Use your judgement to decide whether that is best for this doc. + +- For longer explanations, link to a definition elsewhere. + + - If the jargon is specific to Prisma, then link to a definition in our docs. + + - If the jargon is _not_ specific to Prisma, check if you can find the definition quickly with a web search. If so, then do not explain the term or link to a definition. We can reasonably expect users to know the jargon or to find an explanation for themselves. + +- Only link on the first instance of a jargon term in a logical section of the docs. + + A logical section is a section of the docs that we might expect someone to read at one time. Typically, it is a page, or a self-contained part of a page that comprises one or more headed sections. + +- When you link to an external definition, choose a credible source. Wikipedia is acceptable, and official third-party documentation is better. + +## Use active voice + +Use active voice instead of passive voice. It's a more concise and straightforward way to communicate. For example: + +- (passive) The `for` loop in JavaScript is used by programmers to… +- (active) Programmers use the `for` loop in JavaScript to… + +When our software or third-party software does something, state which module or component carries out the action, if this is important to the user. + +- "Prisma Client returns all `DateTime` as ISO 8601-formatted strings." + +Where the module or component is not important to the user, say that Prisma (or the name of the third-party software) carries out the action: + +- "Prisma reads from the system's environment when it looks for environment variables..." +- "This is because MongoDB returns a cursor that is attached to your MongoDB session..." + +Sometimes you can omit the acting component or module altogether: + +- “Refer to the generated log file in `/directoryX`.” + +## Be assertive + +Use assertive language. + +Good: + +- Use the `createMany` method to create multiple records in a single transaction +- You can use nested writes to create a user and that user's posts at the same time + +Avoid: + +- This example tries to... +- You might be able to... +- You could use... + +Assertive language in procedures: + +Good: + +- Install dotenv-cli + +Avoid: + +- Please install dotenv-cli + +## Use "that" to clarify sentences + +Example: "Ensure that you rebuild your schema.". + +See: ["That" as a conjunction for noun clauses](https://academicguides.waldenu.edu/formandstyle/writing/grammarmechanics/that). + +## Use the present simple tense + +- Write in the [present simple](https://en.wikipedia.org/wiki/Simple_present) tense. +- Use present simple even when you want to write about something that will happen as the result of a user action: say that the result happens, not that it will happen. + +```md + + +When you run this command, Prisma writes the following log file. + + + +When you run this command, Prisma will write the following log file. +``` + +## Indicate when something is optional + +When a paragraph or sentence offers an optional path, the beginning of the first sentence should indicate that it’s optional. For example, "if you’d like to learn more about xyz, see our reference guide" is clearer than "Go to the reference guide if you’d like to learn more about xyz." + +This method allows people who would not like to learn more about xyz to stop reading the sentence as early as possible. It also allows people who would like to learn more about xyz to recognize the opportunity to learn quicker instead of accidentally skipping over the paragraph. + +For optional steps in a procedure, a succinct way to convey this is to precede the step with "Optional:". For example: + +5. Optional: In the **Tags** field, specify one or more tags for your file. Separate multiple tags with commas. + +## Code examples + +Start all query examples with a constant. This gives you a noun to refer to later in the document, and in most cases this clarifies the example. + +Example: + +```ts +const aggregations = await prisma.user.aggregate({ + ... +}) +``` diff --git a/docs/600-about/200-prisma-docs/20-style-guide/02-word-choice.mdx b/docs/600-about/200-prisma-docs/20-style-guide/02-word-choice.mdx new file mode 100644 index 0000000000..d2244e84b8 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/02-word-choice.mdx @@ -0,0 +1,332 @@ +--- +title: 'Word choice' +metaTitle: 'Prisma docs style guide: word choice' +metaDescription: 'This section of the style guide provides guidelines on what terms and phrase constructions to use.' +tocDepth: 4 +search: false +--- + +## Avoid words like "easy" and "just" + +Avoid words like "easy", "just", "simple", and "basic". If users have a hard time completing the task that is supposedly "easy," then they will question their abilities, or get aggravated by the docs. Consider using more specific descriptors. For example, when you say the phrase "deployment is easy," what do you really mean? Is it easy because it takes fewer steps than another option? If so, use the most specific descriptor possible, which in that case would be "this deployment method involves fewer steps than other options." + +For even more inclusive docs, avoid phrases that assume a reader’s experience or skill level, like "just deploy it and you’re done" or "for a refresher (when you refer to a completely different doc that someone might not have read)". Often, when you rephrase, you get stronger sentences that work in a wider range of contexts. + +## Avoid Latin terms + +These are common in English, but can be problematic for non-first-language speakers. Some of them can be confusing even to native English speakers. + +For example: + +| Avoid | Good | +| ----- | ----------------------------------------------------------------------------------------------------------- | +| et al | "and others" | +| etc. | "and so on", or list all of the cases | +| i.e. | "in other words" | +| e.g. | "such as" or "for example" | +| via | "with" or other equivalent, as in "Now you can start to send queries with the generated Prisma Client API") | + +## Avoid gerunds ("ing" verb forms) + +Avoid gerunds (the "ing" form of verbs). For example, use "Get started" instead of "Getting started". This guideline applies to headings and body text. + +Examples: + +| Avoid | Good | +| ----------------------------------------------- | ----------------------------------------- | +| Test the certificate using a browser | Test the certificate with a browser | +| Excluding fields | Exclude fields | +| If you are using Node.js version 18 or later... | If you use Node.js version 18 or later... | +| You can do this by rebuilding Prisma Client | To do this, rebuild Prisma Client | +| When designing your schema... | When you design your schema... | + +Note that nouns ending in "ing" are fine - for example "Tracing". + +## Avoid incomplete sentences before lists + +When you introduce a list, do not use an incomplete sentence. + +### Use + +You can configure your schema in the following ways: + +- Item 1 +- Item 2 + +### Avoid + +You can: + +- Item 1 +- Item 2 + +## When you refer to other parts of the docs + +Use the following terms: + +- Page +- Section + +## Records + +Refer to rows in the database as **records**. For example: + +"The following `create` query creates a single `User` **record**." + +Do not use: + +- Entry +- Row +- Object + +## Model property + +Model property refers to the top-level `PrismaClient` properties that refer to models: + +``` + +const result = await prisma.user.findMany(...) // "user" model property +const result = await prisma.post.findMany(...) // "post" model property + +``` + +## Version numbers + +- Refer to version numbers as "version x.x.x" +- When you compare version numbers, use "before" and "after" (or "later") +- Do not use "lower" and "higher" + +```md + + +This feature is in Preview in versions 3.5.0 and later. + + + +This feature is in Preview in v3.5.0 and higher. +``` + +When you write about a specific version, make it clear _what product_ you are referring to. For example, in the following sentence, version 3.11.1 might refer to Prisma or to MongoDB: + +_This filter is available for MongoDB only in versions 3.11.1 and later._ + +When the product is not clear from the context, explicitly mention the product name in front of the version number. + +_This filter is available for MongoDB only in Prisma versions 3.11.1 and later._ + +### In deprecation notices, mention the deprecation version number but not the planned removal version number + +When you explain that a feature is deprecated, include the version number in which it was deprecated. However, plans change. To keep docs lean and accurate, do not mention the version in which Prisma plans to remove the feature. + +```md + + +From v3.0.0, the `command name` command is deprecated. + + + +From v3.0.0, the `command name` command is deprecated. +We plan to remove `command name` in v.4.0.0. +``` + +## Abbreviate terms + +If you want to abbreviate a term, write it out fully first, then put the abbreviation in parentheses. After that, you can use the abbreviation for the rest of the page. For example, "In computer science, an abstract syntax tree (AST) is …". + +See also: [Jargon](/about/prisma-docs/style-guide/writing-style#jargon) + +## Avoid ambiguous English words + +Avoid the following common words in English, because they are ambiguous to many readers. + +| Word to avoid | Reason to avoid | Use the following word instead | +| -------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------ | +| As | Can mean "because" or "at the same time as" | "Because", or "At the same time", as appropriate | +| Since (to mean "because") | Can also mean "after" (as in "since you upgraded") | "Because" | +| May (to mean "might") | Can also mean "is permitted to" | "Might" | +| Should (to mean "ought to") | Can also mean "might happen" | "Must": "You must rebuild Prisma Client", or

Omit: "Rebuild Prisma Client." | +| Once (to mean "when" or "after") | Can also mean "happens once" | "When": "When the build completes..." | +| Wish (to mean "want") | Not always clear internationally | "Want" | + +## Use clear hyperlinks + +Avoid the constructions "click here" or "here" for link text. They are considered bad practice on the web. + +```md + + +Read more in the [Prisma docs](https://www.prisma.io/docs) + + + +Read more in the Prisma docs [here](https://www.prisma.io/docs) +``` + +If your link text is the title of the destination page, use sentence case: + +```md + + +For more information, see [Relation queries](/orm/prisma-client/queries/relation-queries). + + + +For more information, see [Relation Queries](/orm/prisma-client/queries/relation-queries). +``` + +When it is obvious what the link destination is (for example if you've explained the concept in the preceding sentence), then a very concise (and maintainable) way to provide a link to further information is as follows: + +```md +[Learn more](/orm/prisma-client/queries/relation-queries) +``` + +## Specific terms + +### "Preview" and "general availability" + +Use lower case for these. For "GA", the abbreviation of general availability, use all caps. + +```md + + +We made composite types generally available in version 3.12.0. +They were previously available in preview from version 3.10.0. + + + +We made composite types Generally Available in version 3.12.0. +They were previously available in Preview from version 3.10.0. +``` + +### SQL + +Write "a SQL query", not "an SQL query". Example: "A SQL database...". + +### macOS + +Good: macOS + +Bad: Mac OS, MacOS, or any other variant + +### Terminal window + +Use the term "terminal window". Do not use "command prompt" or "shell". Example: + +``` +Open a terminal window. +``` + +### Set up/setup + +This can be a noun ("setup") or verb ("set up") and as such can cause confusion. Try to avoid, and use an alternative term. For example, "configure" or "enable". + +If you must use it, ensure that you use the correct form. Remember to check in code snippets, where it might lurk in the code comments. + +### Relations + +When referring to relations, use the following forms: + +| Avoid | Good | +| ----- | ------------ | +| 1-1 | One-to-one | +| 1-n | One-to-many | +| m-n | Many-to-many | + +### The `prisma` root command + +We often refer to `prisma` CLI commands such as `prisma db push`. + +- The long form of these commands includes the `prisma` root command. For example: `prisma db push`. +- The short form of these commands omits the `prisma` root command. For example: `db push`. + +`prisma` CLI commands only work when the user includes `prisma`. In most cases, use the long form to help docs users who drop into the docs at that point. The long form also let docs users copy and paste a working command into their terminal windows. + +Use the long form in these circumstances: + +- When you include a `prisma` command in a code box. +- When you include a `prisma` command in a procedure. + +It is OK to use the short form in the following circumstances. This can help with brevity and readability in the docs. + +- When you discuss a `prisma` command, for example in reference material. Example: ["`db push` uses the same engine as Prisma Migrate..."](/orm/prisma-migrate/workflows/prototyping-your-schema) +- When you mention a `prisma` command in a heading. [Example](/orm/reference/prisma-cli-reference#init) + +### Possessive s + +Indicate owner and ownership clearly and do not use possessive _s_. + +When you avoid possessive s, you also avoid: + +- stringing together too many nouns +- issues related to localization and how well international readers understand what you document + +```md + + +Change the database connection string of an environment + + + +Change the environment's database connection string +``` + +### enter vs [*provide, type*] + +Use _enter_ for the action of filling out or typing in a text box or input field. + +Do not use _provide_ or _type_. + +```md + + +In **Display Name**, enter a name for your project. + + + +In **Display Name**, type a name for your project. +In **Display Name**, provide a name for your project. +``` + +### _clear_ vs [*deselect*, *unselect*, *uncheck*, *unmark*] + +Use _clear_ to guide readers to remove the check mark from a checkbox. + +```md + + +Clear **Include sample data**. + + + +Deselect the **Include sample data** checkbox. +``` + +### _select_ vs _choose_ + +_Choose_ conveys the idea of making a choice in general, while _select_ works better in the context of fine-picking an option or making a UI selection among a list of options. + +Use _select_ when you guide readers which UI option to select. + +```md + + +From **Payment method**, select **Wire transfer**. +``` + +Use _choose_ when you make a conceptual description of choosing one option over another. + +```md + + +You can choose to host your project in Vercel or Netlify. +``` + +### checkbox vs ~~check box~~ + +Use _checkbox_. + +See [Avoid excessive use of UI terminology](/about/prisma-docs/style-guide/user-interace-guidelines#avoid-excessive-use-of-ui-terminology). + +### Other terms + +We have an [internal terminology page](https://www.notion.so/prismaio/Terminology-Product-Names-and-Usage-WIP-8f763e861d4f4114b17b1210eb3b6d99). When we have agreed on these, we will add them to this page. diff --git a/docs/600-about/200-prisma-docs/20-style-guide/03-spelling-punctuation-formatting.mdx b/docs/600-about/200-prisma-docs/20-style-guide/03-spelling-punctuation-formatting.mdx new file mode 100644 index 0000000000..80680d9ce7 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/03-spelling-punctuation-formatting.mdx @@ -0,0 +1,318 @@ +--- +title: 'Spelling, punctuation, and formatting' +metaTitle: 'Prisma docs style guide: spelling, punctuation, and formatting' +metaDescription: 'This section of the style guide provides guidelines on how to present the information you add.' +tocDepth: 4 +search: false +--- + +## Avoid contractions + +In keeping with our conversational style, some contractions are OK: + +- Contractions that include the words "is" or "are". For example: it's and you're. +- However, use contractions sparingly. + +However, avoid other contractions. For example: + +- It'll (use "It will") + +## Text emphasis + +Use text emphasis (**bold**, and _italic_) sparingly. In keeping with the calm tone of our docs, and to help readability, avoid a sea of emphasized and formatted text. + +Italic and bold text can be a great way to emphasize certain parts of your sentence to the reader. Use bold text more sparingly, and only when you want some text to stand out from the entire paragraph (so that it's visible when a reader only "scans" the page instead of properly reading it). Use italics for words that introduce new concepts for the first time. + +Do not use ALL CAPS to emphasize text. + +If you are in doubt about whether to emphasize some text, then don't do it. + +### UI elements + +For the names of GUI elements (buttons, drop-down menus, and so on), use bold. Also use the same capitalization as in the GUI. For example: + +1. In the **File** menu, select **Open...**. + +### Avoid exclamation points + +In keeping with our calm tone, do not use exclamation points (exclamation marks). Exception: they are acceptable in congratulatory or welcome messages, for example: "Congratulations - you've completed the tutorial!" + +### Capitalize and spell out proper nouns + +Although you might be tempted to use abbreviations like "Postgres" (instead of the official proper noun "PostgreSQL") or not worry about casing when writing "Javascript" (instead of "JavaScript"), we use the official forms of proper nouns. A few common examples are: + +- Node.js (instead of Node or Node.JS) +- JavaScript and TypeScript (instead of JavaScript and Typescript or JS and TS) +- PostgreSQL (instead of Postgres or Postgresql) +- MongoDB (instead of Mongo) +- GitHub (instead of Github) +- For JSON, see [Special case: JSON](#special-case-json) + +If you're not sure about the spelling of a proper noun, check its official web site. + +### Titles and headings + +- Use sentence case for titles and headings: only the initial word is uppercase (exception: [capitalize proper nouns](#capitalize-and-spell-out-proper-nouns)) +- [Avoid gerunds](/about/prisma-docs/style-guide/word-choice#avoid-gerunds-ing-verb-forms) ("Configure the database", not "Configuring the database") +- Do not use punctuation at the end of a title or heading unless a question mark is required +- Use `code` for code in headings - this is required by our navigation elements + +## Tables, bullet lists, and numbered lists + +Tables and lists are often the most concise way to present information. Use these elements whenever they feel appropriate. Here are a few guidelines: + +- Use a bullet list when the order of the list doesn't matter (e.g. an enumeration of the features of a database which don't have an inherent order). +- Use a numbered list only when the order of the list matters (e.g. when providing step-by-step instructions where one step builds on the previous). +- Use a table to describe things that share a number of similar properties/characteristics (e.g. the parameters for an API call which all have a "name", a "type", are required or optional and need a description). +- For both numbered/ordered lists and bullet lists, add a period on the end if it is a complete sentence. This is most common in ordered lists, with a series of steps. + +## Hyphens + +Use hyphens according to these [rules](https://www.grammarbook.com/punctuation/hyphens.asp). + +Sometimes there are some terms where it's not clear whether to use a hyphen or not. To strive for consistency, we list those terms here. + +### Spell without a hyphen + +- Use case +- Command line (when referring to it as a noun: "On the command line". Use a hyphen when it's an adjective: "This command-line option...") +- Auto format +- Type safety (see below for guidelines on "type safe") +- File name +- Compile time (when you use it as a noun: "... at compile time". Use a hyphen when it's an adjective: "This compile-time operation...") + +### Spell as one word + +- Autocomplete +- Codebase + +### Type-safe, type safe, and type safety + +- "The code is type safe." (adjective after the noun) +- "This is type-safe code." (adjective before the noun) +- "A key feature of Prisma ORM is type safety." (noun) + +### Data source and `datasource` + +- The `datasource` block +- "You must regenerate Prisma Client when you introduce a new data source" + +## Files and file types + +When you refer to a file or file type, use lower case and code format, and include the dot. Use "an" as the preposition if the filename extension, when pronounced, starts with a vowel, otherwise use "a": + +- a `.jpg` file +- an `.xls` file +- an `.env` file +- For json files, see [Special case: JSON](#special-case-json) + +Note: when you refer to a specific file, use the capitalization that is used in the file name: + +- the `schema.prisma` file + +### Special case: JSON + +- When you refer to JSON in general, use all caps and no code format +- When you refer to the Prisma `Json` API, use `Json` +- When you refer to a JSON file, use the formatting rules above: "a `.json` file" + +### Use inline code format for paths and file names + +For example: + +- "The generated Prisma Client is located in the `./node_modules/.prisma` folder by default." +- "The `schema.prisma` file is located in..." +- "To use multiple `.env` files..." + +## Use inline code format when referring to strings in text + +For example: + +"The following query returns all records where the `email` field is equal to `Sarah`." + +## Avoid excessive code formatting + +Documents can quickly get visually cluttered if they have too much special formatting. Our docs are highly technical, and we often refer to code snippets or technical keywords that appear in the user's code. For these keywords, it's appropriate for us to use code formatting. However, we should not refer to general technologies (such as JSON) with code formatting: + +For example: + +Prisma automatically converts JavaScript objects (for example, `{ extendedPetsData: "none"}`) to JSON. + +## Make lists clear with the Oxford Comma + +Use the Oxford Comma except in titles. It is a comma used after the penultimate item in a list of three or more items, before "and" or "or". It makes things clearer. Example: "... an Italian painter, sculptor, and architect". + +In rare cases, the Oxford Comma can make a list less clear. In this situation, re-order the list where possible to make the meaning clear. + +## Code snippets + +### Introduce all code snippets + +Write a short introductory sentence that: + +- Explains what the code snippet does +- Links to reference documentation if applicable + +For example: + +This [`createMany`](..) query does the following: + +- Creates several `User` records +- Creates several nested `Post` records +- Creates several nested `Category` records + +### Show the result of a query wherever possible + +Use the [``](/about/prisma-docs/docs-components/mdx-examples#code-with-result) component to show a query and the results of that query. + +### Use the `highlight` property to highlight + +Use the [`highlight` property](/about/prisma-docs/docs-components/mdx-examples#code-block-with-highlighted-code) if you need to highlight your code samples. For example: + +```` +```prisma highlight=3;normal +generator client { + provider = "prisma-client-js" + previewFeatures = ["namedConstraints"] +} +``` +```` + +### Format code blocks and inline code + +Use the following as reference when creating and editing docs: [formatting inline code and code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code). + +### Emphasize placeholders + +Placeholders are a tricky topic in technical documentation and are one of the most common sources of confusion, especially for beginners. To strive for consistency, placeholders in the Prisma docs: + +- are spelled in all-uppercase letters +- are prefixed and suffixed with two underscores +- use descriptive terms + +As an example, consider the following code block where `__DATABASE_CONNECTION_URL__` is a placeholder for the PostgreSQL connection URL: + +```prisma +datasource db { + provider = "postgresql" + url = "__DATABASE_CONNECTION_STRING__" +} +``` + +Whenever you use a placeholder, explain how to obtain a value for the placeholder, or link to another resource that explains this. Explicitly call out that this is a placeholder that must be replaced with a "real value". Include an example of what that real value might look like: + +```prisma +datasource db { + provider = "postgresql" + url = "postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma2" +} +``` + +### Use Prettier code formatting + +Install [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) in VSCode. Prettier helps ensure your code examples and Markdown have consistent formatting, such as line spacing and indentation. + +If you need to force Prettier to ignore a code block or section of Markdown, you can use `// prettier-ignore`: + +```js + +function xyz() { + console.log({a, b}) +} + +``` + +### Use expressive variable names + +Good: + +```ts +const getUsers = (...) +const deleteUsers = (...) +``` + +Bad: + +```ts +const results = (...) // Too generic +const foo = (...) // Too vague +``` + +### Strive for code snippets to be valid + +Ensure that code snippets you include are realistic examples that would work if run in the context presented. + +### Prisma schema naming conventions + +When you create a Prisma schema for an example, follow the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) we advise for users. + +### Lists of shell commands + +When you need to provide a series of CLI commands as instructions to the reader, use a single block. Don't use a list unless you want to provide context for each step: + +#### Bad + +- `cd path/to/server` +- `docker-compose up -d --build` +- `./node_modules/.bin/sequelize db:migrate` or `npx sequelize db:migrate` +- `./node_modules/.bin/sequelize db:seed:all` or `npx sequelize db:seed:all` + +#### Better + +```terminal +cd path/to/server +docker-compose up -d --build +./node_modules/.bin/sequelize db:migrate # or `npx sequelize db:migrate` +./node_modules/.bin/sequelize db:seed:all # or `npx sequelize db:seed:all` +``` + +or + +1. Navigate into the project directory: `cd path/to/server` +1. Start Docker containers: `docker-compose up -d --build` +1. Migrate your database schema: `./node_modules/.bin/sequelize db:migrate` or `npx sequelize db:migrate` +1. Seed the database: `./node_modules/.bin/sequelize db:seed:all` or `npx sequelize db:seed:all` + +### Don't prepend CLI commands with `$` + +Use `terminal` for CLI commands - this type of code block includes a `$`: + +```` +```terminal +npm install prisma +``` +```` + +For example: + +```terminal +npm install prisma +``` + +### npm vs Yarn + +Always use `npm` commands instead of `yarn`. + +### Error message reference + +The [error message reference](/orm/reference/error-reference) is a semi-generated doc. Do not edit the list of error codes manually. Use the script to generate the error codes. + +When you bring the error messages into the page, remove any double quotes around them. + +Bad: + +``` +#### P1008 + +"Operations timed out after `{time}`" +``` + +Good: + +``` +#### P1008 + +Operations timed out after `{time}` +``` + +See also: [Error message generation guide for Prisma technical writers](https://www.notion.so/prismaio/Process-Doc-tools-and-apps-27dfe27810964b9080fc2cc1f217fcb5#c6cc4bbf97af4d53940f7cf8ac798a590) diff --git a/docs/600-about/200-prisma-docs/20-style-guide/04-schema-models.mdx b/docs/600-about/200-prisma-docs/20-style-guide/04-schema-models.mdx new file mode 100644 index 0000000000..58eb43bdb5 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/04-schema-models.mdx @@ -0,0 +1,35 @@ +--- +title: 'Docs example data model' +metaTitle: 'Prisma docs style guide: example data model' +metaDescription: 'This page describes the data models we use in our documentation examples.' +tocDepth: 3 +search: false +--- + + + +`User` and `Post` are the canonical models that we use in our examples throughout the Prisma docs. + + + +## The `User` and `Post` data model + +We chose the `User` and `Post` models for the following reasons: + +- They do not require domain-specific knowledge. +- They are commonly used as an example in the ORM space. This makes them familiar for users coming from other tools. +- Consistent models make it easier for the reader when learning about different concepts, because there will be less context switching. +- Less decision making and cognitive overhead for the docs authors. Using the same models reduces decision fatigue and is one less thing to worry about when trying to explain concepts. + +## Naming conventions + +See the [naming conventions](/orm/reference/prisma-schema-reference#naming-conventions) for Prisma schemas. + +Use the following for table and column names: + +- Format table names in [PascalCase](https://en.wikipedia.org/wiki/PascalCase). +- Format column names in [camelCase](https://en.wikipedia.org/wiki/Camel_case). + +## Standard SQL Dialect + +Throughout the Prisma docs, PostgreSQL's dialect of SQL is used as the standard. If the context of a particular section requires specifying multiple dialects, those may be made available via the technology switcher component (`SwitchTech`) or tabbed code blocks (`TabbedContent`). diff --git a/docs/600-about/200-prisma-docs/20-style-guide/05-prisma-product-names.mdx b/docs/600-about/200-prisma-docs/20-style-guide/05-prisma-product-names.mdx new file mode 100644 index 0000000000..2b7d89b099 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/05-prisma-product-names.mdx @@ -0,0 +1,21 @@ +--- +title: 'Prisma product and component names' +metaTitle: 'Prisma docs style guide: Prisma product and component names' +metaDescription: 'This section of the style guide provides guidelines on how to refer to Prisma products and components.' +tocDepth: 4 +search: false +--- + +## Use the following forms + +- The Prisma Data Platform (or just "PDP" - no definite article - after the first mention) +- Prisma ORM +- Prisma Client (not any variation of "the Client") +- Prisma schema +- Prisma Migrate +- Prisma CLI +- Prisma Studio +- Prisma Accelerate +- Prisma Pulse + +Do not abbreviate any of these names, except where noted above. diff --git a/docs/600-about/200-prisma-docs/20-style-guide/06-image-guidelines.mdx b/docs/600-about/200-prisma-docs/20-style-guide/06-image-guidelines.mdx new file mode 100644 index 0000000000..3a9f795606 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/06-image-guidelines.mdx @@ -0,0 +1,159 @@ +--- +title: 'Prisma docs image guidelines' +metaTitle: 'Prisma docs style guide: image guidelines' +metaDescription: 'This page provides guidelines for images in our docs.' +tocDepth: 4 +search: false +--- + +## Screenshots + +You can take screenshots with your favorite tool. We find it very easy to use SnagIt when you need to edit screenshots or add annotations to them. We suggest its use as a best practice. + +### Style + +- Take focused screenshots of visible and legible areas of the UI. +- Apply minimal styling to screenshots. Do not use unnecessary effects, annotations, or styles. +- Exclude unnecessary UI areas and details. +- Use full-screen screenshots only when needed. +- Apply a centered shadow on the entire image canvas. If not, a screenshot with a white-background UI blends with the default white background of Prisma Docs. +- In SnagIt, you can add a shadow with **Effects** > **Shadow** and configure its parameters as listed below. + + - Position: Centered + - Color: Black + - Opacity: 75% + - Blur: 5pt + + + + **Tip**

+ For larger and full-screen images, adjust the blur in the range of 7 - 10pt to make the shadow more visible on the page. + +
+ + SnagIt - Screenshot canvas shadow + +### Annotations + +If you can, avoid annotations. If necessary, apply annotations that are minimal and similar in style to the screenshot below. + +Data Browser - Save multiple changes + +For details, see the sections below. Again, we suggest the use of SnagIt as a best practice. + +#### Text annotations + +- Use **Helvetica Neue** font. +- Use black font color. +- Use a font size between 18 and 24 pt for text annotations. Adjust depending on the screenshot size. +- The font size of annotations should not be much bigger than the text in the screenshot. +- Apply a white outline on the text. This ensures that the black text will be visible in Dark mode. + +SnagIt - Screenshot text annotations + +#### Arrow and line annotations + +- Use black color for arrows or lines. +- If you have text annotations that use arrows or lines to point to an area on the screenshot, a small part of the line or arrow should appear on the canvas (and outside of the screenshot). +- Apply a centered shadow on each pointer and make the shadow color white. This ensures that the part of the line that is outside of the screenshot remains visible in Dark mode. + SnagIt - Screenshot arrow line annotations + +### File type and path + +- Save screenshots as `.png` files. +- Save SnagIt project files in the same location and with the same filename, but with the newer cross-platform `.snagx` file extension. +- Do not use the older, platform-specific file extensions (`.snag` on Windows, `.snagproj` on macOS). + +### Filename + +- Keep filenames short and descriptive. +- Use only alphanumeric characters. +- Use relevant keywords in filenames for SEO purposes. +- Use hyphens (`-`) to separate keywords. +- Do not use spaces to separate keywords. + +### Keywords in filenames + +- Use only meaningful keywords. +- Do not use randomized characters in the filename. For example, `d0fjlsf81.png`. +- At the beginning of filenames, use keywords that identify the UI context. +- If applicable, follow with keywords that specify the action that you demonstrate in the screenshot. For example: `data-browser-select-model.png`. + +### File location + +To decide where to save images, use the guidelines below. + +- Save screenshots shared between multiple pages in `content/doc-images/`. +- If a page contains up to two images, save the screenshot files as peers to the MDX file. + + ```bash + ... + 06-image-guidelines.mdx + ... + snagit-arrow-line-config.png + snagit-arrow-line-config.snagx + snagit-text-annotation-config.png + snagit-text-annotation-config.snagx + ``` + +- If you need more than two images in an MDX file, create a peer `images/` directory and save the image files in it. + + ```bash + ... + 06-image-guidelines.mdx + ... + images/ + 06-01-snagit-arrow-line-config.png + 06-01-snagit-arrow-line-config.snagx + 06-02-snagit-text-annotation-config.png + 06-02-snagit-text-annotation-config.snagx + ``` + +- At the beginning of each screenshot filename, add the number of the related MDX file. +- After that, use sequential numbering to specify the sequence in which the images appear in the MDX file. + +## Diagrams + +- Use [Figma](https://www.figma.com) to create diagrams. +- For consistency, when you create a new diagram, base it on an existing one. +- Add the URL of the source image to the Markdown page. Use a comment immediately above the image tag, as follows: + +```md + + +![image](trace-diagram.png) +``` + +## Add images to MDX files + +For full-width images, use the shorter image MDX component:`![]()`. + +```markdown +![Alt text](./peer-file.png) +``` + +If you need to shrink an image by width, use the `` component. + +```html +SnagIt - Screenshot text annotations +``` diff --git a/docs/600-about/200-prisma-docs/20-style-guide/07-user-interace-guidelines.mdx b/docs/600-about/200-prisma-docs/20-style-guide/07-user-interace-guidelines.mdx new file mode 100644 index 0000000000..7d23c35703 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/07-user-interace-guidelines.mdx @@ -0,0 +1,272 @@ +--- +title: 'User interface (GUI) guidelines' +metaTitle: 'Prisma docs style guide: GUI guidelines' +metaDescription: 'On this page you can find information about the Prisma guidelines for documenting UI elements and steps to walk users through interfaces.' +tocDepth: 3 +search: false +--- + +## Use numbered lists to document UI steps + +To document a complete task (such as _Create a new project_), use numbered lists to organize separate steps into a sequence of steps. + +- Use indented numbered lists to document substeps. +- Avoid numbered lists that comprise more than 10 steps or steps that comprise more than 10 substeps. +- If you have more than 10 steps or steps with more than 5-10 substeps, consider separating into multiple tasks. + +## Write each step as a single action with a clear verb + +Each step (numbered item) must include a verb that guides the completion of the step. + +```md + + +The status changes to **Completed**. + + + +From **Status**, select **Completed**. +``` + +Make sure that steps are discrete and that their related verbs sound instructive. Do not put more than one action in a single step unless the step finishes with the action to confirm or cancel that involves the click of a specific button or UI control. + +```md + + +When you click **Invite Member** and the **Add member** pop-up opens, select the role for the new team member. + + + +1. Click **Invite Member**. +2. In the **Add member** pop-up, select the role for the new team member and click **Invite**. +``` + +## Document step results only for important outcomes + +If you need to describe the results of a step, separate them with a line break so that they appear indented on a new line under the step. + +```md + + +1. Click **Invite Member**.
+ Your team member receives an email with a link to join the project. +``` + +Avoid the description of obvious results that happen when a user carries out a step. + +```md + + +1. From the **Edit** menu, select **Copy**.
+ The text is copied to the clipboard. +``` + +## Format the names of UI elements with bold + +Use bold for the names of all UI controls. + +| UI element | Example | +| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| buttons | Click **Next**.
Click **Cancel**. | +| radio buttons | Under **Payment method**, select **Wire transfer**. | +| checkboxes | • Select **Include sample data**.
• Clear **Include sample data**. | +| drop-down menus | • From **GitHub Accounts & Organizations**, select an account or organization.
• From **Static IPs**, select **Enabled**.
• From **Branch**, select the repository branch for this environment. | +| links | Click **Learn more**. | +| menu names | Click **File**. | +| menu items | Select **Open**. | +| menu cascades | Select **File** > **Save**. | +| hamburger menu / three-dot menu | • Click the three-dot menu and select **Make default**.
• Click the hamburger menu and select **Make default**. | +| tab | • Select the **macOS** tab.
• Click the **Network** tab. | +| page | On the **Configure project** page, … | +| window | In the **Payment information** pop-up window, enter the details for your payment method. | +| screen/tab | On the **Data Browser** screen, select a record. | +| pane/panel | In the **Configuration** panel, click **Network**. | +| section | Under **Accelerate**, select **Enabled** from **Static IPs**. | + +## Identify UI elements at the beginning of steps + +When you document an interaction with a UI element, begin steps with a reference to the name of the UI element to help readers navigate and scan the listed steps more easily. + +```md + + +1. Enter a name for your project in **Display Name**. +2. Select a GitHub account or an organization from **GitHub Accounts & Organizations**. +3. Select **Create a repository**. +4. (Optional) Enter a name for the repository in **Repository Name**. + + + +1. In **Display Name**, enter a name for your project. +2. From the **GitHub Accounts & Organizations** drop-down menu, select a GitHub account or an organization. +3. Select **Create a repository**. +4. (Optional) In **Repository Name**, enter a name for the repository. +``` + +## Identify optional steps + +Add the text (Optional) at the beginning of optional steps. Do so even when they are written with an “If…” statement. + +```md + + +1. (Optional) From **Static IPs**, select **Enabled** if your database is behind a firewall and you can only configure external access from specific IP addresses. Copy the IP addresses and add them to the allowlist of your database. +2. (Optional) If your database is behind a firewall and you can only configure external access from specific IP addresses, then from **Static IPs**, select **Enabled**. + + + +1. If your database is behind a firewall and you can only configure external access from specific IP addresses, then from **Static IPs**, select **Enabled**. +``` + +## Avoid excessive use of UI terminology + +It can feel excessive to include the UI term for each UI element when you write steps for interacting with UI. + +To make UI steps easier to read, in most cases you can omit the UI term for each UI element. + +
+Example 1: drop-down menu + + + +From the **GitHub Accounts & Organizations** drop-down menu, select a GitHub account or an organization. + + + +From **GitHub Accounts & Organizations**, select a GitHub account or an organization. + +
+ +
+Example 2: text box + + + +In the **Display Name** text box, enter a name for your project. + + + +In **Display Name**, enter a name for your project. + +
+ +
+Example 3: select the option + + + +Select the **Create a repository** option. + + + +Select **Create a repository**. + +
+ +
+Example 4: clear the checkbox + + + +Deselect the **Include sample data** check box to skip seeding the database with sample data. + + + +Clear **Include sample data** to skip seeding the database with sample data. + +
+ +In specific cases, calling out the UI control name brings clarity and makes it easy to document a more complex step. Use your judgement and avoid this rule in such cases. + +
+Example 5: UI control under a section + +```md + + +- Under _Accelerate_, from **Location**, select the geographic location for Prisma Accelerate. +- Under _Accelerate_ and from **Location**, select the geographic location for Prisma Accelerate. + + + +Under _Accelerate_, from the **Location** drop-down menu, select the geographic location for Prisma Accelerate. +``` + +
+ +## Short and obvious steps + +In the middle or at the end of a procedure, the final step is sometimes very short and obvious for readers. + +- Click **Next**. +- Click **OK**. +- Click **Save**. +- Click **Done**. + +Even if developer audiences do not need a reminder to save their files, specific cases exist in which omitting a short step can cause confusion. + +1. Click **Delete** for the item you want to delete. +2. In the confirmation popup, enter the name of the item and click **Delete**. + +In other cases, short steps are not really necessary but still complete a valid procedure. + +One such example can be a **Done** button at the end of a wizard. + +Decide based on context if a short step adds noise or if it is a must to have it. + +## Do not document requirements for input fields (text boxes) + +Text boxes or input fields in modern UIs typically provide immediate validation and feedback when users type in forbidden characters. Because of this, it is not necessary to list: + +- allowed characters +- allowed text length + +```md + + +In **Display Name**, enter a name for your project. + + + +**💡 Note**

+ +Follow the rules below when you enter a display name for your project.

+ +• Include at least one letter
+• Keep the length up to 40 characters~~ +
+ + + +In **Display Name**, enter a name for your project. +``` + +## Fall back to passive voice when the doer is difficult to identify + +In some cases, it is very difficult to identify the doer in a sentence or the doer sounds awkward to name. + +```md + + +The form automatically pre-fills the GitHub repository based on the project name you provide. In the repository name, the form replaces each space with a hyphen. + + + +The GitHub repository name is pre-filled based on the display name and each space is replaced with a hyphen. +``` + +## Match capitalization of UI controls + +Document the user interface as it appears and do not alter UI text in the documentation to meet style guide or other requirements. + +For example, if a button has the text CANCEL, match the all-caps in the documentation. + +```md + + +Click **CANCEL**. + + + +Click **Cancel**. +``` diff --git a/docs/600-about/200-prisma-docs/20-style-guide/10-boilerplate-content.mdx b/docs/600-about/200-prisma-docs/20-style-guide/10-boilerplate-content.mdx new file mode 100644 index 0000000000..dd405a5e42 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/10-boilerplate-content.mdx @@ -0,0 +1,40 @@ +--- +title: 'Boilerplate content' +metaTitle: 'Boilerplate content' +metaDescription: 'Boilerplate content for the Prisma docs.' +tocDepth: 3 +hidePage: false +search: false +toc: true +--- + + + +You can use the following phrases and blocks of content as templates when you work on the docs. + +TBA: link to our docs template files (currently in Notion, but should probably be added to our style guide) + + + +### To introduce a preview feature + +````md +To enable this feature, add `namedConstraints` to `previewFeatures` in your schema: + +```prisma highlight=3;normal +generator client { + provider = "prisma-client-js" + previewFeatures = ["namedConstraints"] +} +``` +```` + +### To make a recommendation + +If it is a recommendation made by Prisma, use: + +> "**We recommend that** you share a single instance of `PrismaClient` across your application." + +If it is an industry standard, use: + +> "**It is recommended practice to** limit the number of database connections to X." diff --git a/docs/600-about/200-prisma-docs/20-style-guide/index.mdx b/docs/600-about/200-prisma-docs/20-style-guide/index.mdx new file mode 100644 index 0000000000..50a4108110 --- /dev/null +++ b/docs/600-about/200-prisma-docs/20-style-guide/index.mdx @@ -0,0 +1,17 @@ +--- +title: 'Prisma docs style guide' +metaTitle: 'Prisma documentation style guide' +metaDescription: 'The Prisma style guide provides contributor guidelines for the Prisma docs.' +tocDepth: 4 +hidePage: false +--- + + + +This guide contains guidelines for contributors to the Prisma docs. Its goal is to ensure consistency throughout the Prisma docs and with other official Prisma materials. + +> This style guide is inspired by the [Gatsby Style Guide](https://www.gatsbyjs.org/contributing/gatsby-style-guide/). + + + + diff --git a/docs/600-about/200-prisma-docs/30-docs-components/01-mdx-examples.mdx b/docs/600-about/200-prisma-docs/30-docs-components/01-mdx-examples.mdx new file mode 100644 index 0000000000..f799c703ce --- /dev/null +++ b/docs/600-about/200-prisma-docs/30-docs-components/01-mdx-examples.mdx @@ -0,0 +1,538 @@ +--- +title: 'MDX components' +metaTitle: 'MDX components in the Prisma docs' +metaDescription: 'MDX components components available on the Prisma documentation site.' +navTitle: 'MDX components' +search: false +--- + + + +This page describes how to use the custom [MDX](https://mdxjs.com/) components (e.g. code blocks) in the Prisma docs. + +Components not listed here are part of the [Docusaurus Markdown features](https://docusaurus.io/docs/markdown-features) + + + +## `TopBlock` + +Required at the top of the page to avoid styling issues: + +```md + + +This page describes how to use [MDX](https://mdxjs.com/) components (e.g. code blocks) in the Prisma docs. + + +``` + +## Code blocks + +Example: + +```js +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Code: + +```` +```js +async function main() { +const allUsers = await prisma.user.findMany() +console.log(allUsers) +} +``` +```` + +### Prisma schema + +Example: + +```prisma +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` + +Code: + +```` +```prisma +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` +```` + +### Code block with file icon + +Example: + +```prisma file=schema.prisma +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` + +Code: + +```` +```prisma file=schema.prisma +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +``` +```` + +### Code block with no copy option + +By default, all the code blocks will have a `copy` icon for copying the code. If you want to disable the `copy` option in the code block, please use `no-copy` property. + +Example: + +```js no-copy +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Code: + +````no-copy +```js no-copy +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` +```` + +### Code block without line numbers + +Example: + +```js no-lines +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` + +Code: + +```` +```js no-lines +async function main() { + const allUsers = await prisma.user.findMany() + console.log(allUsers) +} +``` +```` + +### Terminal styled code block + +Example: + +```terminal +npm run dev +``` + +Code: + +```` +```terminal +npm run dev +``` +```` + +### Code block wrapped + +For code blocks where we _don't_ want to have a scrollable box. + +Example with `wrap`: + +```code wrap +$ this is a single, really long line of code that shouldn't need to be scrollable to check what it says and simply wraps over to the next line, making it all visible in the same box +``` + +Example without `wrap`: + +```code +$ this is a single, really long line of code that shouldn't need to be scrollable to check what it says and simply wraps over to the next line, making it all visible in the same box +``` + +Code: + +```` +```code wrap +$ this is a single, really long line of code that shouldn't need to be scrollable to check what it says and simply wraps over to the next line, making it all visible in the same box +``` +```` + +### Code block with highlighted code + +Example: + +```js file=test.ts highlight=2;add|4;delete|6,7;edit|9-12;normal +async function main() { + added code + + deleted code + + edited + code + + highlights + over multiple + lines can be done by using + a hyphen +} +``` + +Code: + +```` +```js file=test.ts highlight=2;add|4;delete|6,7;edit|9-12;normal +async function main() { + added code + + deleted code + + edited + code + + highlights + over multiple + lines can be done by using + a hyphen +}``` +```` + +## Expand/Collapse section + +Example: + +
+Expand if you want to view more + +Here's more! + +
+ +``` +
+Expand if you want to view more + +Here's more! + +
+``` + +## Code with result + +Example: + + + + + +``` +yarn prisma init +``` + + + + + +```code no-copy wrap +$ yarn prisma init +yarn run v1.22.0 +warning package.json: No license field +$ /Users/nikolasburk/Desktop/tsdf/node_modules/.bin/prisma init + +✔ Your Prisma schema was created at prisma/schema.prisma. + You can now open it in your favorite editor. + +Next steps: +1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started. +2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql or sqlite. +3. Run prisma db pull to turn your database schema into a Prisma data model. +4. Run prisma generate to install Prisma Client. You can then start querying your database. + +More information in our documentation: +https://pris.ly/d/getting-started +``` + + + + + +Code: + +```` + + + + +``` +yarn prisma init +``` + + + + + +```code no-copy wrap +$ yarn prisma init +yarn run v1.22.0 +warning package.json: No license field +$ /Users/nikolasburk/Desktop/tsdf/node_modules/.bin/prisma init + +✔ Your Prisma schema was created at prisma/schema.prisma. + You can now open it in your favorite editor. + +Next steps: +1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started. +2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql or sqlite. +3. Run prisma db pull to turn your database schema into a Prisma data model. +4. Run prisma generate to install Prisma Client. You can then start querying your database. + +More information in our documentation: +https://pris.ly/d/getting-started +``` + + + + +```` + +Example with custom output text + + + + + +``` +yarn prisma init +``` + + + + + +```code no-copy wrap +$ yarn prisma init +yarn run v1.22.0 +warning package.json: No license field +$ /Users/nikolasburk/Desktop/tsdf/node_modules/.bin/prisma init + +✔ Your Prisma schema was created at prisma/schema.prisma. + You can now open it in your favorite editor. + +Next steps: +1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started. +2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql or sqlite. +3. Run prisma db pull to turn your database schema into a Prisma data model. +4. Run prisma generate to install Prisma Client. You can then start querying your database. + +More information in our documentation: +https://pris.ly/d/getting-started +``` + + + + + +Code: + +```` + + + + +``` +yarn prisma init +``` + + + + + +```code no-copy wrap +$ yarn prisma init +yarn run v1.22.0 +warning package.json: No license field +$ /Users/nikolasburk/Desktop/tsdf/node_modules/.bin/prisma init + +✔ Your Prisma schema was created at prisma/schema.prisma. + You can now open it in your favorite editor. + +Next steps: +1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started. +2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql or sqlite. +3. Run prisma db pull to turn your database schema into a Prisma data model. +4. Run prisma generate to install Prisma Client. You can then start querying your database. + +More information in our documentation: +https://pris.ly/d/getting-started +``` + + + + +```` + +## Parallel blocks + +Example: + + + + + +```ts +const posts = await postRepository.find({ + where: { + title: 'Hello World', + }, +}) +``` + + + + + +```ts +const posts = await postRepository.find({ + where: { + title: ILike('Hello World'), + }, +}) +``` + + + + + +Code: + +```` + + + + + + ```ts + const posts = await postRepository.find({ + where: { + title: 'Hello World', + }, + }) + ``` + + + + + + ```ts + const posts = await postRepository.find({ + where: { + title: ILike('Hello World'), + }, + }) + ``` + + + + + +```` diff --git a/docs/600-about/200-prisma-docs/30-docs-components/03-frontmatter.mdx b/docs/600-about/200-prisma-docs/30-docs-components/03-frontmatter.mdx new file mode 100644 index 0000000000..a85ee90ca2 --- /dev/null +++ b/docs/600-about/200-prisma-docs/30-docs-components/03-frontmatter.mdx @@ -0,0 +1,175 @@ +--- +title: Front matter +metaDescription: Supported front matter variables. +search: false +--- + + + +## Meta information + +Front matter that informs the meta information of a page. + +### title + +The `

` title of the page. This title appears at the top of the page, and in the left-hand navigation. + +You do not need to add this text as an `

` because Gatsby generates this heading from the `title` tag. + +Note: + +- You can wrap the `title` text in single quotes, but this is not mandatory. +- If you wrap the `title` text in single quotes, then you cannot include apostrophes in the text. + +### metaTitle + +The `` of the page - falls back to `title` (`h1`). + +This tag is important for Google SEO. If we wish, we can make the `metaTitle` more descriptive than the `title`. + +For good SEO, spell out abbreviations in this tag, unless they are industry standard. For example, spell out "Prisma Data Platform", but it is fine to use the abbreviation "ORM". + +Note: + +- You can wrap the `metaTitle` text in single quotes, but this is not mandatory. +- If you wrap the `metaTitle` text in single quotes, then you cannot include apostrophes in the text. + +## <inlinecode>navTitle</inlinecode> + +Specifies a different, usually shorter title for the left-hand navigation. + +### <inlinecode>metaDescription</inlinecode> + +The `<meta name="description" content="" />` of the page. + +Note: + +- You can wrap the `metaDescription` text in single quotes, but this is not mandatory. +- If you wrap the `metaDescription` text in single quotes, then you cannot include apostrophes in the text. + +## Navigation (left sidebar) + +Front matter that configured the navigation. + +### <inlinecode>staticLink</inlinecode> + +Accepts `true` or `false` (defaults to `false`). + +If `true`, this option turns the page into a heading in the left-hand navigation. This heading cannot be clicked by the docs user. For example on [this page](/orm/overview). + +> **Note**: The page still exists, but docs users can only navigate to it with the breadcrumb trail. We recommend that you add a [subsections](/about/prisma-docs/docs-components/mdx-examples#subsections) MDX component to the page, so that it contains useful content when a user navigates to it with the breadcrumb trail. + +### <inlinecode>duration</inlinecode> + +Accepts a string specifying the duration to read the article. + +Example: `duration: '15 min'` + +### <inlinecode>preview</inlinecode> + +Accepts `true` or `false` (defaults to `false`). + +Adds a `Preview` label to a page in the left-hand navigation. + +### <inlinecode>deprecated</inlinecode> + +Accepts `true` or `false` (defaults to `false`). + +Adds a `Deprecated` label to a page in the left-hand navigation. + +### <inlinecode>hidePage</inlinecode> + +Accepts `true` or `false` (defaults to `false`). + +When set to `true`, hides the page from all navigation. + +``` +hidePage: true +``` + +Note: + +- A page hidden with `hidePage` is not listed by the [subsections](/about/prisma-docs/docs-components/mdx-examples#subsections) MDX component. +- A page hidden with `hidePage` is still findable by docs users with a search. To omit a page from the search results, use the [`search`](#search) tag. + +## Table of Contents (right sidebar) + +### <inlinecode>toc</inlinecode> + +Enable or disable table of contents navigation on the page (defaults to `false`). For example: + +``` +toc: true +``` + +### <inlinecode>tocDepth</inlinecode> + +Controls the depth of headings to show in the in-page ToC: + +``` +tocDepth: 2 +``` + +> **Note**: Currently defaults up to level - `h2` + +## Search + +Front matter that configures search. + +### <inlinecode>search</inlinecode> + +Accepts `true` or `false` (defaults to `true`). + +When set to `false`, omits the page from search results. + +``` +search: false +``` + +Note: + +- A page omitted from search results is still shown in the navigation. To hide it in the navigation, use the [`hidePage`](#hidepage) tag. + +## Page content + +Front matter that configured page content + +### <inlinecode>langSwitcher</inlinecode> + +Accepts an array of languages to be shown in the page as dropdown options in order to switch the context between the pages + +Example: + +``` +langSwitcher: ['typescript', 'node'] +``` + +### <inlinecode>dbSwitcher</inlinecode> + +Accepts an array of database options to be shown in the page as dropdown options in order to switch the context between the pages + +Example: + +``` +dbSwitcher: ['postgresql', 'mysql', 'sqlserver', 'planetscale', 'cockroachdb'] +``` + +## Design + +Front matter to configure the visual appearance of a page. + +### <inlinecode>wide</inlinecode> + +Accepts `true` or `false` (defaults to `false`). + +When set to 'true', this page will have a content width of 988px instead of the default 748px. + +Example: + +``` +wide: true +``` + +Note: + +- Please use this only for pages with unreadable wide tables. diff --git a/docs/600-about/200-prisma-docs/30-docs-components/index.mdx b/docs/600-about/200-prisma-docs/30-docs-components/index.mdx new file mode 100644 index 0000000000..29119086e3 --- /dev/null +++ b/docs/600-about/200-prisma-docs/30-docs-components/index.mdx @@ -0,0 +1,11 @@ +--- +title: 'Prisma docs components' +metaTitle: 'Prisma documentation components' +metaDescription: 'This section describes the Prisma docs file format.' +tocDepth: 4 +search: false +--- + +## In this section + +<Subsections depth="3" /> diff --git a/docs/600-about/200-prisma-docs/40-template.mdx b/docs/600-about/200-prisma-docs/40-template.mdx new file mode 100644 index 0000000000..ff92b0a08e --- /dev/null +++ b/docs/600-about/200-prisma-docs/40-template.mdx @@ -0,0 +1,24 @@ +--- +title: 'Writing template' +metaTitle: 'Writing template (About)' +metaDescription: 'A template for writing Prisma Docs.' +tocDepth: 3 +hidePage: false +search: false +toc: true +deprecated: false +--- + +<TopBlock> + +A short introduction that encourages visitors to read on. The `TopBlock` component is required for styling purposes. + +</TopBlock> + +## A section + +Break your page up into sections. Use the `tocDepth` front matter variable to determine how many levels the table of contents should have - 1 or 2. + +### A subsection + +If possible, avoid too many deeply nested subsections. diff --git a/docs/600-about/200-prisma-docs/index.mdx b/docs/600-about/200-prisma-docs/index.mdx new file mode 100644 index 0000000000..1e74fa1b2f --- /dev/null +++ b/docs/600-about/200-prisma-docs/index.mdx @@ -0,0 +1,12 @@ +--- +title: 'Prisma docs' +metaTitle: 'About Prisma docs' +metaDescription: 'About Prisma docs' +toc: false +staticLink: true +search: false +--- + +## In this section + +<Subsections /> diff --git a/docs/600-about/index.mdx b/docs/600-about/index.mdx new file mode 100644 index 0000000000..594a2b0e24 --- /dev/null +++ b/docs/600-about/index.mdx @@ -0,0 +1,10 @@ +--- +title: 'About' +metaTitle: 'About' +metaDescription: 'About the Prisma docs.' +toc: false +--- + +<TopBlock> + +</TopBlock> diff --git a/static/img/accelerate/accelerate-update-database-connection-string.png b/static/img/accelerate/accelerate-update-database-connection-string.png new file mode 100644 index 0000000000..271d4f2bde Binary files /dev/null and b/static/img/accelerate/accelerate-update-database-connection-string.png differ diff --git a/static/img/accelerate/accelerate.png b/static/img/accelerate/accelerate.png new file mode 100644 index 0000000000..408d30212e Binary files /dev/null and b/static/img/accelerate/accelerate.png differ diff --git a/static/img/accelerate/swr.png b/static/img/accelerate/swr.png new file mode 100644 index 0000000000..7a052bc448 Binary files /dev/null and b/static/img/accelerate/swr.png differ diff --git a/static/img/accelerate/ttl.png b/static/img/accelerate/ttl.png new file mode 100644 index 0000000000..4059acffff Binary files /dev/null and b/static/img/accelerate/ttl.png differ diff --git a/static/img/accelerate/ttl_and_swr.png b/static/img/accelerate/ttl_and_swr.png new file mode 100644 index 0000000000..188f527c12 Binary files /dev/null and b/static/img/accelerate/ttl_and_swr.png differ diff --git a/static/img/baseline-production-from-local.png b/static/img/orm/baseline-production-from-local.png similarity index 100% rename from static/img/baseline-production-from-local.png rename to static/img/orm/baseline-production-from-local.png diff --git a/static/img/connect-sql-server.png b/static/img/orm/connect-sql-server.png similarity index 100% rename from static/img/connect-sql-server.png rename to static/img/orm/connect-sql-server.png diff --git a/static/img/cursor-1.png b/static/img/orm/cursor-1.png similarity index 100% rename from static/img/cursor-1.png rename to static/img/orm/cursor-1.png diff --git a/static/img/cursor-2.png b/static/img/orm/cursor-2.png similarity index 100% rename from static/img/cursor-2.png rename to static/img/orm/cursor-2.png diff --git a/static/img/cursor-3.png b/static/img/orm/cursor-3.png similarity index 100% rename from static/img/cursor-3.png rename to static/img/orm/cursor-3.png diff --git a/static/img/offset-skip-take.png b/static/img/orm/offset-skip-take.png similarity index 100% rename from static/img/offset-skip-take.png rename to static/img/orm/offset-skip-take.png diff --git a/static/img/prisma-db-pull-generate-schema.png b/static/img/orm/prisma-db-pull-generate-schema.png similarity index 100% rename from static/img/prisma-db-pull-generate-schema.png rename to static/img/orm/prisma-db-pull-generate-schema.png diff --git a/static/img/prisma-evolve-app-workflow.png b/static/img/orm/prisma-evolve-app-workflow.png similarity index 100% rename from static/img/prisma-evolve-app-workflow.png rename to static/img/orm/prisma-evolve-app-workflow.png diff --git a/static/img/prisma-migrate-development-workflow.png b/static/img/orm/prisma-migrate-development-workflow.png similarity index 100% rename from static/img/prisma-migrate-development-workflow.png rename to static/img/orm/prisma-migrate-development-workflow.png