Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.'
---
Expand All @@ -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.

:::

Expand Down
Original file line number Diff line number Diff line change
@@ -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

<Prerequisites />

You also need:

- A [PlanetScale](https://planetscale.com) account
- A PlanetScale Postgres database
- Database connection credentials from PlanetScale

## 1. Create a new project

<CreateProject />

## 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: '[email protected]',
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

<ExploreData />

## Next steps

<NextSteps />

## 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)
Original file line number Diff line number Diff line change
@@ -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.'
---
Expand All @@ -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.

:::

Expand Down
Loading
Loading