diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx index 83e2a45062..a9b8392468 100644 --- a/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/600-planetscale.mdx @@ -1,6 +1,6 @@ --- -title: 'Quickstart with Prisma ORM and PlanetScale' -sidebar_label: 'PlanetScale' +title: 'Quickstart with Prisma ORM and PlanetScale MySQL' +sidebar_label: 'PlanetScale MySQL' metaTitle: 'Quickstart: Prisma ORM with PlanetScale MySQL (10 min)' metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale MySQL and generating a Prisma Client for database access.' --- @@ -14,7 +14,7 @@ import NextSteps from '../../_components/_next-steps.mdx' :::note -PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [PostgreSQL quickstart guide](/getting-started/prisma-orm/quickstart/postgresql) instead. +PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale Postgres**, follow the [PlanetScale Postgres quickstart guide](/getting-started/prisma-orm/quickstart/planetscale-postgres) instead. ::: diff --git a/content/100-getting-started/02-prisma-orm/100-quickstart/605-planetscale-postgres.mdx b/content/100-getting-started/02-prisma-orm/100-quickstart/605-planetscale-postgres.mdx new file mode 100644 index 0000000000..77197beaf7 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/100-quickstart/605-planetscale-postgres.mdx @@ -0,0 +1,300 @@ +--- +title: 'Quickstart with Prisma ORM and PlanetScale Postgres' +sidebar_label: 'PlanetScale Postgres' +metaTitle: 'Quickstart: Prisma ORM with PlanetScale Postgres (10 min)' +metaDescription: 'Create a new TypeScript project from scratch by connecting Prisma ORM to PlanetScale Postgres and generating a Prisma Client for database access.' +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import CreateProject from '../../_components/_create-project.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale Postgres**, a fully managed PostgreSQL database with high availability, branching, and built-in connection pooling. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to PlanetScale Postgres using Prisma ORM, and generate a Prisma Client for easy, type-safe access to your database. + +:::note + +PlanetScale also offers MySQL databases (powered by Vitess). If you're using **PlanetScale MySQL**, follow the [PlanetScale MySQL quickstart guide](/getting-started/prisma-orm/quickstart/planetscale) instead. + +::: + +## Prerequisites + + + +You also need: + +- A [PlanetScale](https://planetscale.com) account +- A PlanetScale Postgres database +- Database connection credentials from PlanetScale + +## 1. Create a new project + + + +## 2. Install required dependencies + +Install the packages needed for this quickstart: + +```terminal +npm install prisma @types/node @types/pg --save-dev +npm install @prisma/client @prisma/adapter-pg pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma migrate`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`pg`** - The node-postgres database driver +- **`@types/pg`** - TypeScript type definitions for node-postgres +- **`dotenv`** - Loads environment variables from your `.env` file + +## 3. Configure ESM support + +Update `tsconfig.json` for ESM compatibility: + +```json file=tsconfig.json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true, + "ignoreDeprecations": "6.0" + } +} +``` + +Update `package.json` to enable ESM: + +```json file=package.json +{ + // add-start + "type": "module", + // add-end +} +``` + +## 4. Initialize Prisma ORM + +You can now invoke the Prisma CLI by prefixing it with `npx`: + +```terminal +npx prisma +``` + +Next, set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider postgresql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection and schema models +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 5. Configure your connection + +PlanetScale Postgres offers two connection types: + +| Type | Port | Use case | +|------|------|----------| +| **Direct** | `5432` | Prisma CLI commands (migrations, introspection), Prisma Studio | +| **PgBouncer** | `6432` | Application connections, serverless environments | + +For production applications, we recommend using PgBouncer for application connections while keeping a direct connection for Prisma CLI commands. + +Update your `.env` file with your PlanetScale connection string using the PgBouncer port: + +```env file=.env +DATABASE_URL="postgresql://{username}:{password}@{host}:6432/postgres?sslmode=verify-full" +``` + +Replace the placeholders with your actual PlanetScale credentials from your database dashboard. + +The generated `prisma.config.ts` reads the connection string from the environment: + +```typescript file=prisma.config.ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 6. Define your data model + +Open `prisma/schema.prisma` and add the following models: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} + +//add-start +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} + +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId Int +} +//add-end +``` + +## 7. Create and apply your first migration + +Create your first migration to set up the database tables: + +```terminal +npx prisma migrate dev --name init +``` + +This command creates the database tables based on your schema. + +Now run the following command to generate the Prisma Client: + +```terminal +npx prisma generate +``` + +## 8. Instantiate Prisma Client + +Now that you have all the dependencies installed, you can instantiate Prisma Client. Pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor using the pooled connection: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 9. Write your first query + +Create a `script.ts` file to test your setup: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Create a new user with a post + const user = await prisma.user.create({ + data: { + name: 'Alice', + email: 'alice@prisma.io', + posts: { + create: { + title: 'Hello World', + content: 'This is my first post!', + published: true, + }, + }, + }, + include: { + posts: true, + }, + }) + console.log('Created user:', user) + + // Fetch all users with their posts + const allUsers = await prisma.user.findMany({ + include: { + posts: true, + }, + }) + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +You should see the created user and all users printed to the console! + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PlanetScale Postgres database connector](/orm/overview/databases/planetscale-postgres) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database connection management](/orm/prisma-client/setup-and-configuration/databases-connections) +- [PlanetScale Postgres documentation](https://planetscale.com/docs/postgres) diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx index 9f0ebb0fe0..69a4cb8da3 100644 --- a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/600-planetscale.mdx @@ -1,6 +1,6 @@ --- -title: 'Add Prisma ORM to an existing PlanetScale project' -sidebar_title: 'PlanetScale' +title: 'Add Prisma ORM to an existing PlanetScale MySQL project' +sidebar_title: 'PlanetScale MySQL' metaTitle: 'How to add Prisma ORM to an existing project using PlanetScale MySQL (15 min)' metaDescription: 'Add Prisma ORM to an existing TypeScript project with PlanetScale MySQL and learn database introspection and querying.' --- @@ -13,7 +13,7 @@ import NextSteps from '../../_components/_next-steps.mdx' :::note -PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale PostgreSQL**, follow the [Add to existing PostgreSQL project guide](/getting-started/prisma-orm/add-to-existing-project/postgresql) instead. +PlanetScale also offers PostgreSQL databases. If you're using **PlanetScale Postgres**, follow the [Add to existing PlanetScale Postgres project guide](/getting-started/prisma-orm/add-to-existing-project/planetscale-postgres) instead. ::: diff --git a/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/605-planetscale-postgres.mdx b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/605-planetscale-postgres.mdx new file mode 100644 index 0000000000..53db58c868 --- /dev/null +++ b/content/100-getting-started/02-prisma-orm/200-add-to-existing-project/605-planetscale-postgres.mdx @@ -0,0 +1,279 @@ +--- +title: 'Add Prisma ORM to an existing PlanetScale Postgres project' +sidebar_title: 'PlanetScale Postgres' +metaTitle: 'How to add Prisma ORM to an existing project using PlanetScale Postgres (15 min)' +metaDescription: 'Add Prisma ORM to an existing TypeScript project with PlanetScale Postgres and learn database introspection, baselining, and querying.' +--- + +import Prerequisites from '../../_components/_prerequisites.mdx' +import ExploreData from '../../_components/_explore-data.mdx' +import NextSteps from '../../_components/_next-steps.mdx' + +[PlanetScale](https://planetscale.com) is a serverless database platform. This guide covers **PlanetScale Postgres**, a fully managed PostgreSQL database with high availability, branching, and built-in connection pooling. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PlanetScale Postgres, introspect your existing database schema, and start querying with type-safe Prisma Client. + +:::note + +PlanetScale also offers MySQL databases (powered by Vitess). If you're using **PlanetScale MySQL**, follow the [Add to existing PlanetScale MySQL project guide](/getting-started/prisma-orm/add-to-existing-project/planetscale) instead. + +::: + +## Prerequisites + + + +You also need: + +- A [PlanetScale](https://planetscale.com) account +- An existing PlanetScale Postgres database with data +- Database connection credentials from PlanetScale + +## 1. Set up Prisma ORM + +Navigate to your existing project directory and install the required dependencies: + +```terminal +npm install prisma @types/node @types/pg --save-dev +npm install @prisma/client @prisma/adapter-pg pg dotenv +``` + +Here's what each package does: + +- **`prisma`** - The Prisma CLI for running commands like `prisma init`, `prisma db pull`, and `prisma generate` +- **`@prisma/client`** - The Prisma Client library for querying your database +- **`@prisma/adapter-pg`** - The [`node-postgres` driver adapter](/orm/overview/databases/postgresql#using-the-node-postgres-driver) that connects Prisma Client to your database +- **`pg`** - The node-postgres database driver +- **`@types/pg`** - TypeScript type definitions for node-postgres +- **`dotenv`** - Loads environment variables from your `.env` file + +## 2. Initialize Prisma ORM + +Set up your Prisma ORM project by creating your [Prisma Schema](/orm/prisma-schema) file with the following command: + +```terminal +npx prisma init --datasource-provider postgresql --output ../generated/prisma +``` + +This command does a few things: + +- Creates a `prisma/` directory with a `schema.prisma` file containing your database connection configuration +- Creates a `.env` file in the root directory for environment variables +- Creates a `prisma.config.ts` file for Prisma configuration + +The generated `prisma.config.ts` file looks like this: + +```typescript file=prisma.config.ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +The generated schema uses [the ESM-first `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client) with a custom output path: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +## 3. Connect your database + +PlanetScale Postgres offers two connection types: + +| Type | Port | Use case | +|------|------|----------| +| **Direct** | `5432` | Prisma CLI commands (migrations, introspection), Prisma Studio | +| **PgBouncer** | `6432` | Application connections, serverless environments | + +For production applications, we recommend using PgBouncer for application connections while keeping a direct connection for Prisma CLI commands. + +Update your `.env` file with your PlanetScale connection string using the PgBouncer port: + +```env file=.env +DATABASE_URL="postgresql://{username}:{password}@{host}:6432/postgres?sslmode=verify-full" +``` + +Replace the placeholders with your actual PlanetScale credentials. You can find these in your PlanetScale dashboard by clicking **Connect** on your database. + +The generated `prisma.config.ts` reads the connection string from the environment: + +```typescript file=prisma.config.ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +## 4. Introspect your database + +Run the following command to introspect your existing database: + +```terminal +npx prisma db pull +``` + +This command reads the connection string, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema. + +![Introspect your database with Prisma ORM](/img/getting-started/prisma-db-pull-generate-schema.png) + +After introspection, your Prisma schema will contain models that represent your existing database tables. + +## 5. Baseline your database + +To use Prisma Migrate with your existing database, you need to [baseline your database](/orm/prisma-migrate/getting-started). + +First, create a `migrations` directory: + +```terminal +mkdir -p prisma/migrations/0_init +``` + +Next, generate the migration file with `prisma migrate diff`: + +```terminal +npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql +``` + +Review the generated migration file to ensure it matches your database schema. + +Then, mark the migration as applied: + +```terminal +npx prisma migrate resolve --applied 0_init +``` + +You now have a baseline for your current database schema. + +## 6. Generate Prisma ORM types + +Generate Prisma Client based on your introspected schema: + +```terminal +npx prisma generate +``` + +This creates a type-safe Prisma Client tailored to your database schema in the `generated/prisma` directory. + +## 7. Instantiate Prisma Client + +Create a utility file to instantiate Prisma Client. Pass an instance of Prisma ORM's driver adapter to the `PrismaClient` constructor using the pooled connection: + +```typescript file=lib/prisma.ts +import "dotenv/config"; +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' + +const connectionString = `${process.env.DATABASE_URL}` + +const adapter = new PrismaPg({ connectionString }) +const prisma = new PrismaClient({ adapter }) + +export { prisma } +``` + +## 8. Query your database + +Now you can use Prisma Client to query your database. Create a `script.ts` file: + +```typescript file=script.ts +import { prisma } from './lib/prisma' + +async function main() { + // Example: Fetch all records from a table + // Replace 'user' with your actual model name + const allUsers = await prisma.user.findMany() + console.log('All users:', JSON.stringify(allUsers, null, 2)) +} + +main() + .then(async () => { + await prisma.$disconnect() + }) + .catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) + }) +``` + +Run the script: + +```terminal +npx tsx script.ts +``` + +## 9. Evolve your schema + +To make changes to your database schema: + +### 9.1. Update your Prisma schema file + +Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model: + +```prisma file=prisma/schema.prisma +// add-start +model Post { + id Int @id @default(autoincrement()) + title String + content String? + published Boolean @default(false) + authorId Int + author User @relation(fields: [authorId], references: [id]) +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + name String? + posts Post[] +} +// add-end +``` + +### 9.2. Create and apply a migration: + +```terminal +npx prisma migrate dev --name your_migration_name +``` + +This command will: +- Create a new SQL migration file +- Apply the migration to your database +- Regenerate Prisma Client + +## 10. Explore your data with Prisma Studio + + + +## Next steps + + + +## More info + +- [PlanetScale Postgres database connector](/orm/overview/databases/planetscale-postgres) +- [Prisma Config reference](/orm/reference/prisma-config-reference) +- [Database introspection](/orm/prisma-schema/introspection) +- [Prisma Migrate](/orm/prisma-migrate) +- [PlanetScale Postgres documentation](https://planetscale.com/docs/postgres) diff --git a/content/200-orm/050-overview/500-databases/850-planetscale.mdx b/content/200-orm/050-overview/500-databases/850-planetscale.mdx index d642075e1e..fd2b6819d5 100644 --- a/content/200-orm/050-overview/500-databases/850-planetscale.mdx +++ b/content/200-orm/050-overview/500-databases/850-planetscale.mdx @@ -1,12 +1,18 @@ --- -title: 'PlanetScale' -metaTitle: 'PlanetScale' -metaDescription: 'Guide to PlanetScale' +title: 'PlanetScale MySQL' +metaTitle: 'PlanetScale MySQL' +metaDescription: 'Guide to PlanetScale MySQL' tocDepth: 3 toc: true --- -Prisma and [PlanetScale](https://planetscale.com/) together provide a development arena that optimizes rapid, type-safe development of data access applications, using Prisma's ORM and PlanetScale's highly scalable MySQL-based platform. +Prisma ORM and [PlanetScale](https://planetscale.com/) together provide a development arena that optimizes rapid, type-safe development of data access applications, using Prisma's ORM and PlanetScale's highly scalable MySQL-based platform powered by Vitess. + +:::note + +This guide covers **PlanetScale MySQL** (powered by Vitess). If you're using **PlanetScale Postgres**, see the [PlanetScale Postgres guide](/orm/overview/databases/planetscale-postgres) instead. + +::: This document discusses the concepts behind using Prisma ORM and PlanetScale, explains the commonalities and differences between PlanetScale and other database providers, and leads you through the process for configuring your application to integrate with PlanetScale. diff --git a/content/200-orm/050-overview/500-databases/855-planetscale-postgres.mdx b/content/200-orm/050-overview/500-databases/855-planetscale-postgres.mdx new file mode 100644 index 0000000000..4742c19e5d --- /dev/null +++ b/content/200-orm/050-overview/500-databases/855-planetscale-postgres.mdx @@ -0,0 +1,141 @@ +--- +title: 'PlanetScale Postgres' +metaTitle: 'PlanetScale Postgres' +metaDescription: 'Guide to PlanetScale Postgres' +tocDepth: 3 +toc: true +--- + +Prisma ORM and [PlanetScale Postgres](https://planetscale.com/) work together seamlessly, combining Prisma's type-safe database access with PlanetScale's fully managed, high-availability PostgreSQL platform. + +This document discusses the concepts behind using Prisma ORM with PlanetScale Postgres, explains the commonalities and differences compared to other PostgreSQL providers, and guides you through configuring your application. + +:::note + +This guide covers **PlanetScale Postgres**. If you're using **PlanetScale MySQL** (powered by Vitess), see the [PlanetScale MySQL guide](/orm/overview/databases/planetscale) instead. + +::: + +## What is PlanetScale Postgres? + +[PlanetScale Postgres](https://planetscale.com/docs/postgres) is a managed PostgreSQL service built on modern cloud infrastructure, designed for high availability and operational simplicity. Key features include: + +- **High availability by default.** Production clusters run on a [primary-replica architecture](https://planetscale.com/docs/postgres/postgres-architecture#cluster-design) with one primary and two replicas distributed across availability zones, providing zone-level fault tolerance with automated failover. +- **Database branching.** Create [isolated database environments](https://planetscale.com/docs/postgres/branching) from production data for development and testing, with cost-optimized single-instance architecture for development branches. +- **Built-in connection pooling.** [PgBouncer](https://planetscale.com/docs/postgres/connecting/pgbouncer) is available on port `6432` for efficient connection management, particularly useful for serverless deployments. +- **Automatic backups and point-in-time recovery.** PlanetScale handles [backups automatically](https://planetscale.com/docs/postgres/backups) with configurable retention periods and point-in-time recovery capabilities. +- **Query insights.** Built-in [query performance analysis](https://planetscale.com/docs/postgres/postgres-architecture#insights-and-query-analysis) with automatic detection of slow queries, execution plan analysis, and optimization recommendations. +- **Flexible infrastructure options.** Choose between [ARM64 (Graviton) or x86-64 CPU architectures](https://planetscale.com/docs/postgres/cluster-configuration/cpu-architectures), and between direct-attached NVMe storage (PlanetScale Metal) or network-attached storage with configurable IOPS. + +## Commonalities with other database providers + +PlanetScale Postgres is fully PostgreSQL-compatible, so using it with Prisma ORM works the same as any other PostgreSQL database. You can: + +- Model your database with the [Prisma Schema Language](/orm/prisma-schema) +- Use Prisma ORM's [`postgresql` database connector](/orm/overview/databases/postgresql) in your schema +- Use [Introspection](/orm/prisma-schema/introspection) for existing projects if you already have a database schema +- Use [`prisma migrate dev`](/orm/prisma-migrate/workflows/development-and-production) to manage schema migrations +- Use [`prisma db push`](/orm/prisma-migrate/workflows/prototyping-your-schema) to push changes to your schema +- Use [Prisma Client](/orm/prisma-client) in your application to query your database +- Use foreign key constraints and all standard PostgreSQL features + +## Differences to consider + +While PlanetScale Postgres is fully PostgreSQL-compatible, there are some platform-specific considerations: + +- **Connection pooling.** PlanetScale provides [PgBouncer](https://planetscale.com/docs/postgres/connecting/pgbouncer) for connection pooling on port `6432`. For serverless or high-concurrency applications, use the pooled connection. For migrations and Prisma CLI commands, use the direct connection on port `5432`. +- **Branching model.** PlanetScale Postgres provides [development and production branches](https://planetscale.com/docs/postgres/branching). Unlike PlanetScale MySQL (Vitess), there are no deploy requests — schema changes are applied directly to each branch. +- **Querying replicas.** PlanetScale Postgres allows you to [query replicas directly](https://planetscale.com/docs/postgres/scaling/replicas) for read-heavy workloads, which can help distribute load from your primary. +- **SSL required.** All connections require SSL/TLS encryption (`sslmode=verify-full`). + +## How to connect to PlanetScale Postgres + +### Connection string format + +Your PlanetScale Postgres connection string follows the standard PostgreSQL format: + +```bash +postgresql://{username}:{password}@{host}:{port}/{database}?sslmode=verify-full +``` + +You can find your connection credentials in the [PlanetScale dashboard](https://app.planetscale.com) by navigating to your database and clicking **Connect**. We recommend [creating a dedicated role](https://planetscale.com/docs/postgres/connecting/roles) for your application. + +### Connection types: Direct vs PgBouncer + +PlanetScale Postgres offers two connection types: + +| Type | Port | Use case | +|------|------|----------| +| **Direct** | `5432` | Prisma CLI commands (`migrate`, `db push`, `db pull`), Prisma Studio | +| **PgBouncer** | `6432` | Application connections, serverless environments, high-concurrency workloads | + +## Using connection pooling with PgBouncer + +For production applications, especially serverless deployments, we recommend using PgBouncer for your application connections while keeping a direct connection for Prisma CLI commands. + +Configure your `.env` file with your PlanetScale connection string using the PgBouncer port: + +```env file=.env +DATABASE_URL="postgresql://{username}:{password}@{host}:6432/{database}?sslmode=verify-full" +``` + +Your `prisma.config.ts` reads the connection string from the environment: + +```ts file=prisma.config.ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + schema: 'prisma/schema.prisma', + migrations: { + path: 'prisma/migrations', + }, + datasource: { + url: env('DATABASE_URL'), + }, +}) +``` + +Your Prisma schema uses the PostgreSQL provider: + +```prisma file=prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "postgresql" +} +``` + +Instantiate Prisma Client with the pooled connection using `@prisma/adapter-pg`: + +```ts file=src/db/client.ts +import { PrismaClient } from '../generated/prisma/client' +import { PrismaPg } from '@prisma/adapter-pg' + +const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL }) +export const prisma = new PrismaClient({ adapter }) +``` + +:::info + +Using a driver adapter like `@prisma/adapter-pg` is recommended for serverless environments. For traditional server-based deployments, you can use Prisma Client without an adapter and it will connect using the `DATABASE_URL` from your schema. + +::: + +## Querying replicas + +PlanetScale Postgres production clusters include two read replicas distributed across availability zones. You can [query replicas directly](https://planetscale.com/docs/postgres/scaling/replicas) for read-heavy workloads to distribute load from your primary database. + +Consult the [PlanetScale documentation on replicas](https://planetscale.com/docs/postgres/scaling/replicas) for details on connecting to replicas. + +## More on using PlanetScale Postgres with Prisma ORM + +The fastest way to start using PlanetScale Postgres with Prisma ORM is to refer to our Getting Started documentation: + +- [Start from scratch](/getting-started/prisma-orm/quickstart/planetscale-postgres) +- [Add to existing project](/getting-started/prisma-orm/add-to-existing-project/planetscale-postgres) + +These tutorials will take you through the process of connecting to PlanetScale Postgres, running migrations, and using Prisma Client. diff --git a/content/300-accelerate/900-compare.mdx b/content/300-accelerate/900-compare.mdx index a7c95d72d6..6bc0e91baa 100644 --- a/content/300-accelerate/900-compare.mdx +++ b/content/300-accelerate/900-compare.mdx @@ -28,7 +28,7 @@ Prisma Accelerate is chosen and loved by many for a number of key reasons which Prisma Accelerate offers a powerful global cache, so you can serve data to your users at the edge — the closest point to where the users are located — no matter where your database is hosted. This not only speeds up the experience for users, but also reduces read load on your database as well by avoiding roundtrips. -| | Accelerate | Hyperdrive | Planetscale Boost | +| | Accelerate | Hyperdrive | PlanetScale Boost | | --- | --- | --- | --- | | **Fully Managed** | ✅ | ✅ | ✅ | | **Globally distributed edge infra** | ✅ | ✅ | ✅ | @@ -99,6 +99,6 @@ Prisma Accelerate includes a globally hosted connection pooler, which allows you | --- | --- | --- | --- | --- | --- | --- | --- | | **PostgreSQL** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **MySQL** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| **Planetscale** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| **PlanetScale** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **CockroachDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | **MongoDB** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | diff --git a/sidebars.ts b/sidebars.ts index 9dad533ce8..f7a0ec6359 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -106,7 +106,12 @@ const sidebars: SidebarsConfig = { { type: "doc", id: "getting-started/prisma-orm/quickstart/planetscale", - label: "PlanetScale", + label: "PlanetScale MySQL", + }, + { + type: "doc", + id: "getting-started/prisma-orm/quickstart/planetscale-postgres", + label: "PlanetScale Postgres", }, { type: "doc", @@ -162,7 +167,12 @@ const sidebars: SidebarsConfig = { { type: "doc", id: "getting-started/prisma-orm/add-to-existing-project/planetscale", - label: "PlanetScale", + label: "PlanetScale MySQL", + }, + { + type: "doc", + id: "getting-started/prisma-orm/add-to-existing-project/planetscale-postgres", + label: "PlanetScale Postgres", }, { type: "doc", @@ -497,10 +507,7 @@ const sidebars: SidebarsConfig = { label: "Vibe Coding Tutorials", collapsed: false, collapsible: false, - items: [ - "ai/tutorials/linktree-clone", - "ai/tutorials/typefully-clone", - ], + items: ["ai/tutorials/linktree-clone", "ai/tutorials/typefully-clone"], }, { type: "category", diff --git a/src/data/indexData.ts b/src/data/indexData.ts index 4be0a02a19..04810784ba 100644 --- a/src/data/indexData.ts +++ b/src/data/indexData.ts @@ -176,7 +176,7 @@ export const tabs = [ url: "/getting-started/prisma-orm/add-to-existing-project/planetscale", image: "/img/technologies/planetscale.svg", imageDark: "/img/technologies/planetscaledark.svg", - tech: "Planetscale", + tech: "PlanetScale", }, { url: "/getting-started/prisma-orm/add-to-existing-project/sql-server",