Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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,82 @@
---
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, Steps } 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. Select **Connect to your database** > **Any client**.
3. Select **Generate database credentials**. Copy the connection string for your Prisma Postgres database.
4. Edit the connection string to make it compatible with Hyperdrive.
- Add the database name after the port, but before `?sslmode=require`.
- The final string will look like:

```txt ins="database_name"
postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name
```

With this 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 number of direct connections that can be made 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).

:::note
There are two limits to consider here.

- Origin database's connection limit, set by the origin database provider. This is the maximum number of direct database connections that can be made to the origin database.
- Hyperdrive's origin connection limit, set by Hyperdrive. This is the maximum number of database connections that Hyperdrive can make to your origin database (in this case, Prisma Postgres).

Hyperdrive's origin connection limit should be lower than the Prisma Postgres connection limit, since Hyperdrive's origin connection limit is a soft limit, and Hyperdrive may create more connections if there are network disruptions that prevent existing connections from being used.
:::

<Tabs>

<TabItem label={"Dashboard"}>
<Steps>
1. From the [Cloudflare Hyperdrive dashboard](https://dash.cloudflare.com/?to=/:account/workers/hyperdrive), select your newly created Hyperdrive configuration.
2. Go to **Settings**.
3. In **Origin connection limit**, select **Edit Settings**, and set your maximum connections to a number that is lower than your Prisma connection limit.
</Steps>
</TabItem>
<TabItem label={"Wrangler CLI"}>
<Steps>
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>
```
</Steps>
</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 connects directly to your database to perform global connection pooling and fast query routing.

:::

<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)
- An existing [Worker project](/workers/get-started/guide/)

## 1. Install Prisma ORM

Install Prisma CLI as a dev dependency:

<PackageManagers pkg="prisma" dev />

Install the `pg` driver and Prisma driver adapter for use with Hyperdrive:

<PackageManagers pkg="pg@>8.13.0 @prisma/adapter-pg" />

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"
previewFeatures = ["driverAdapters"]
}
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

Add your database connection string to the `.env` file created by Prisma:

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

Add helper scripts to your `package.json`:

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

### 2.4. Generate Prisma Client

Generate the Prisma client with driver adapter support:

```sh
npm run generate
```

### 2.5. 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 { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";

export interface Env {
HYPERDRIVE: Hyperdrive;
}

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

// 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 must use driver adapters to properly utilize the Hyperdrive connection string. The `@prisma/adapter-pg` driver adapter allows Prisma ORM to work with the `pg` driver and Hyperdrive's connection pooling. This approach provides connection pooling at the network level through Hyperdrive, so you don't need Prisma-specific connection pooling extensions like Prisma Accelerate.

:::

## 4. Deploy your Worker

Deploy your Worker:

```bash
npx wrangler deploy
```

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