Skip to content
Closed
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
Expand Up @@ -4,7 +4,7 @@ summary: Connect Hyperdrive to a Google Cloud SQL for Postgres database instance
pcx_content_type: example
title: Google Cloud SQL
sidebar:
order: 12
order: 13
description: Connect Hyperdrive to a Google Cloud SQL for Postgres database instance.
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
type: example
summary: Connect Hyperdrive to a Prisma Postgres database.
pcx_content_type: example
title: Prisma Postgres
sidebar:
order: 12
description: Connect Hyperdrive to a Prisma Postgres database.
---

import { Render, TabItem, Tabs } from "~/components";

This example shows you how to connect Hyperdrive to a [Prisma Postgres](https://www.prisma.io/postgres) database.

## 1. Allow Hyperdrive access

You can connect Hyperdrive to any existing Prisma Postgres database by using your existing database connection string.

### Prisma Data Platform

1. Go to the [**Prisma Data Platform Console**](https://console.prisma.io/) and select the project (database) you wish to connect to.
2. Navigate to your database settings, select **Connect to your database**, select **Any client**, and copy the connection string for your Prisma Postgres database.
3. You must append **`postgres`** as the database in your connection string. Ensure the connection string includes the necessary credentials according to the format documented below:
```txt
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
```

With the connection string, you can now create a Hyperdrive database configuration.

## 2. Create a database configuration

<Render file="create-hyperdrive-config" product="hyperdrive" />

## 4. Configure Hyperdrive maximum connections

Prisma Postgres has limits on the amount of connections that can be made direct to the database using Hyperdrive. Refer to [Prisma Postgres limits](https://www.prisma.io/docs/postgres/database/direct-connections?utm_source=website&utm_medium=postgres-page#connection-limit) to know the specific limits that apply to your database.

:::note

Hyperdrive's origin connection limit refers to the amount of database connections that Hyperdrive makes to your origin database (in this case, Prisma Postgres).
This number should be less than your Prisma Postgres database since Hyperdrive's limit is a soft limit, and Hyperdrive may create more connections in the event of networking disruptions that prevent existing connections from being used.

:::

<Tabs>

<TabItem label={"Dashboard"}>
1. From the [Cloudflare Hyperdrive dashboard](https://dash.cloudflare.com/?to=/:account/workers/hyperdrive), select your newly created Hyperdrive configuration.
2. Navigate to **Settings**.
3. In **Origin connection limit**, select **Edit Settings** and set your max connections to a number that is less than your Prisma connection limit.
</TabItem>
<TabItem label={"Wrangler CLI"}>

1. Edit your existing Hyperdrive configuration with the `--origin-connection-limit` parameter:

```bash
npx wrangler hyperdrive update \<HYPERDRIVE_ID\> --origin-connection-limit=10
```

Replace `<HYPERDRIVE_ID>` with your Hyperdrive configuration ID and set the connection limit to a number that is less than your Prisma connection limit.

2. Verify the configuration change:

```bash
npx wrangler hyperdrive get \<HYPERDRIVE_ID\>
```

</TabItem>
</Tabs>

:::note

When connecting to a Prisma Postgres database with Hyperdrive, you should use a driver like [node-postgres (pg)](/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/node-postgres/) or [Postgres.js](/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/postgres-js/) to connect directly to the underlying PostgreSQL database instead of the Prisma Accelerate extension. Hyperdrive is optimized for database access for Workers and will perform global connection pooling and fast query routing by connecting directly to your database.

:::

<Render file="create-hyperdrive-config-next-steps" product="hyperdrive" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
---
pcx_content_type: example
title: Prisma ORM
sidebar:
order: 4
meta:
title: Using Prisma ORM with Hyperdrive for PostgreSQL
---

import { Render, Steps, PackageManagers } from "~/components";

[Prisma ORM](https://www.prisma.io/docs) is a Node.js and TypeScript ORM with a focus on type safety and developer experience. This example demonstrates how to use Prisma ORM with PostgreSQL via Cloudflare Hyperdrive in a Workers application.

## Prerequisites

- A Cloudflare account with Workers access
- A PostgreSQL database (such as [Prisma Postgres](https://www.prisma.io/postgres))
- A [Hyperdrive configuration to your PostgreSQL database](/hyperdrive/get-started/#3-connect-hyperdrive-to-a-database)

## 1. Install Prisma ORM

Install Prisma CLI as a dev dependency:

<PackageManagers pkg="prisma" dev />

Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`:

<PackageManagers pkg="dotenv-cli" dev />

Install the `pg` driver for use with Hyperdrive:

<PackageManagers pkg="pg@>8.13.0" />

If using TypeScript, install the types package:

<PackageManagers pkg="@types/pg" dev />

Add the required Node.js compatibility flags and Hyperdrive binding to your `wrangler.toml` file:

<Render file="hyperdrive-node-compatibility-requirement" product="hyperdrive" />

## 2. Configure Prisma ORM

### 2.1. Initialize Prisma

Initialize Prisma in your application:

```sh
npx prisma init
```

This creates a `prisma` folder with a `schema.prisma` file and an `.env` file.

### 2.2. Define a schema

Define your database schema in the `prisma/schema.prisma` file:

```prisma title="prisma/schema.prisma"
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}
```

### 2.3. Set up environment variables

Rename the `.env` file to `.dev.vars` (since Workers doesn't support `.env` files):

```sh
mv .env .dev.vars
```

Add your database connection string to `.dev.vars`:

```env title=".dev.vars"
DATABASE_URL="postgres://user:password@host:port/database"
```

Add helper scripts to your `package.json`:

```json title="package.json"
"scripts": {
"migrate": "dotenv -e .dev.vars -- npx prisma migrate dev",
"generate": "dotenv -e .dev.vars -- npx prisma generate --no-engine",
"studio": "dotenv -e .dev.vars -- npx prisma studio"
}
```

### 2.4. Run migrations

Generate and apply the database schema:

```sh
npm run migrate
```

When prompted, provide a name for the migration (for example, `init`).

## 3. Connect Prisma ORM to Hyperdrive

Use your Hyperdrive configuration when using Prisma ORM. Update your `src/index.ts` file:

```ts title="src/index.ts"
import { PrismaClient } from "@prisma/client/edge";

export interface Env {
HYPERDRIVE: Hyperdrive;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
// Create Prisma client using Hyperdrive connection string
const prisma = new PrismaClient({
datasourceUrl: env.HYPERDRIVE.connectionString,
});

// Sample query to create and fetch users
const user = await prisma.user.create({
data: {
name: "John Doe",
email: `john.doe.${Date.now()}@example.com`,
},
});

const allUsers = await prisma.user.findMany();

return Response.json({
newUser: user,
allUsers: allUsers,
});
},
} satisfies ExportedHandler<Env>;
```

:::note

When using Prisma ORM with Hyperdrive, you connect directly to the underlying PostgreSQL database through Hyperdrive's connection pooling. This means you don't need Prisma-specific connection pooling extensions like Prisma Accelerate, since Hyperdrive handles the connection pooling at the network level.

:::

## 4. Deploy your Worker

Deploy your Worker:

```bash
npx wrangler deploy
```

<Render file="create-hyperdrive-config-next-steps" product="hyperdrive" />
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,16 @@ import { Render, PackageManagers, Tabs, TabItem } from "~/components";

:::note

You can connect to PlanetScale using [Hyperdrive](/hyperdrive) (recommended), or using the PlanetScale serverless driver, `@planetscale/database`. Both provide connection pooling and reduce the amount of round trips required to create a secure connection from Workers to your database.
You can connect to PlanetScale using the PlanetScale serverless driver, `@planetscale/database`, or [Hyperdrive](/hyperdrive). Both approaches provide comparable performance with different tradeoffs.

Hyperdrive can provide lower latencies because it performs the database connection setup and connection pooling across Cloudflare's network. Hyperdrive supports native database drivers, libraries, and ORMs, and is included in all [Workers plans](/hyperdrive/platform/pricing/). Learn more about Hyperdrive in [How Hyperdrive Works](/hyperdrive/configuration/how-hyperdrive-works/).
The PlanetScale serverless driver provides connection pooling and is designed specifically for PlanetScale's platform, offering simplicity and built-in optimizations for the PlanetScale ecosystem.

Hyperdrive provides the lowest possible latencies due to its globally distributed nature and allows you to use any standard MySQL driver. Hyperdrive performs database connection setup and connection pooling across Cloudflare's network and supports native database drivers, libraries, and ORMs. Learn more about Hyperdrive in [How Hyperdrive Works](/hyperdrive/configuration/how-hyperdrive-works/).

:::

<Tabs>
<TabItem label="Hyperdrive (recommended)">

To connect to PlanetScale using [Hyperdrive](/hyperdrive), follow these steps:

<Render file="planetscale-partial" product="hyperdrive"/>
</TabItem>
<TabItem label="PlanetScale serverless driver">
<TabItem label="PlanetScale serverless driver">

## Set up an integration with PlanetScale

Expand Down Expand Up @@ -103,5 +99,12 @@ To set up an integration with PlanetScale:

To learn more about PlanetScale, refer to [PlanetScale's official documentation](https://docs.planetscale.com/).

</TabItem>
</TabItem>
<TabItem label="Hyperdrive">

To connect to PlanetScale using [Hyperdrive](/hyperdrive), follow these steps:

<Render file="planetscale-partial" product="hyperdrive"/>

</TabItem>
</Tabs>
Loading
Loading