diff --git a/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/google-cloud-sql.mdx b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/google-cloud-sql.mdx index 7563fd076ef22d9..e1aa59c5ac81497 100644 --- a/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/google-cloud-sql.mdx +++ b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/google-cloud-sql.mdx @@ -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. --- diff --git a/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/prisma-postgres.mdx b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/prisma-postgres.mdx new file mode 100644 index 000000000000000..70420a030cae4e6 --- /dev/null +++ b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/prisma-postgres.mdx @@ -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 + + + +## 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. + +::: + + + + +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. + + + +1. Edit your existing Hyperdrive configuration with the `--origin-connection-limit` parameter: + +```bash +npx wrangler hyperdrive update \ --origin-connection-limit=10 +``` + +Replace `` 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 \ +``` + + + + +:::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. + +::: + + diff --git a/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/prisma-orm.mdx b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/prisma-orm.mdx new file mode 100644 index 000000000000000..827087d9e463fe4 --- /dev/null +++ b/src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-drivers-and-libraries/prisma-orm.mdx @@ -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: + + + +Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`: + + + +Install the `pg` driver for use with Hyperdrive: + + + +If using TypeScript, install the types package: + + + +Add the required Node.js compatibility flags and Hyperdrive binding to your `wrangler.toml` file: + + + +## 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 { + // 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; +``` + +:::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 +``` + + diff --git a/src/content/docs/workers/databases/third-party-integrations/planetscale.mdx b/src/content/docs/workers/databases/third-party-integrations/planetscale.mdx index 72d3b15a142e1b6..dc847a84313761c 100644 --- a/src/content/docs/workers/databases/third-party-integrations/planetscale.mdx +++ b/src/content/docs/workers/databases/third-party-integrations/planetscale.mdx @@ -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/). ::: - - -To connect to PlanetScale using [Hyperdrive](/hyperdrive), follow these steps: - - - - + ## Set up an integration with PlanetScale @@ -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/). - + + + +To connect to PlanetScale using [Hyperdrive](/hyperdrive), follow these steps: + + + + diff --git a/src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx b/src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx index f69e6fe127c75f3..6bed0d0c816cfdd 100644 --- a/src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx +++ b/src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx @@ -10,15 +10,29 @@ tags: - PostgreSQL --- -import { PackageManagers } from "~/components"; +import { PackageManagers, Tabs, TabItem, Render } from "~/components"; [Prisma Postgres](https://www.prisma.io/postgres) is a managed, serverless PostgreSQL database. It supports features like connection pooling, caching, real-time subscriptions, and query optimization recommendations. +:::note + +You can connect to Prisma Postgres using [Prisma Accelerate](https://www.prisma.io/accelerate) or [Hyperdrive](/hyperdrive). Both approaches provide comparable performance with different tradeoffs. + +Prisma Accelerate provides connection pooling and caching specifically designed for connecting to Prisma Postgres with the [Prisma ORM](https://www.prisma.io/), improving database access from Workers with built-in optimizations for the Prisma ecosystem. + +Hyperdrive provides the lowest possible latencies when connecting to external databases from Workers, allows you to use any standard PostgreSQL driver, and is included in all Workers plans. Hyperdrive performs 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/). + +::: + + + + In this tutorial, you will learn how to: - Set up a Cloudflare Workers project with [Prisma ORM](https://www.prisma.io/docs). - Create a Prisma Postgres instance from the Prisma CLI. - Model data and run migrations with Prisma Postgres. +- Connect to the database using Prisma Accelerate. - Query the database from Workers. - Deploy the Worker to Cloudflare. @@ -142,7 +156,7 @@ After these steps are complete, Prisma ORM is fully set up and connected to your ## 3. Develop the application -Modify the `src/index.ts` file and replace its contents with the following code: +Modify the `src/index.ts` file to use Prisma Postgres with Prisma Accelerate: ```ts title="src/index.ts" import { PrismaClient } from "@prisma/client/edge"; @@ -163,6 +177,7 @@ export default { }, }); + // Connect to Prisma Postgres using Accelerate const prisma = new PrismaClient({ datasourceUrl: env.DATABASE_URL, }).$extends(withAccelerate()); @@ -193,6 +208,7 @@ npm run dev Visit [`https://localhost:8787`](https://localhost:8787) to see your app display the following output: ```sh +Created new user: Jon Doe (Jon123@gmail.com). Number of users in the database: 1 ``` @@ -200,7 +216,7 @@ Every time you refresh the page, a new user is created. The number displayed wil ## 4. Deploy the application to Cloudflare -When the application is deployed to Cloudflare, it needs access to the `DATABASE_URL` environment variable that is defined locally in `.dev.vars`. You can use the [`npx wrangler secret put`](/workers/configuration/secrets/#adding-secrets-to-your-project) command to upload the `DATABASE_URL` to the deployment environment: +When using Prisma Accelerate, you need to add the `DATABASE_URL` as a secret. Use the [`npx wrangler secret put`](/workers/configuration/secrets/#adding-secrets-to-your-project) command: ```sh npx wrangler secret put DATABASE_URL @@ -228,6 +244,253 @@ If you belong to multiple accounts, select the account where you want to deploy Once the deployment completes, verify the deployment by visiting the live URL provided in the deployment output, such as `https://{PROJECT_NAME}.workers.dev`. If you encounter any issues, ensure the secrets were added correctly and check the deployment logs for errors. + + + +In this tutorial, you will learn how to: + +- Set up a Cloudflare Workers project with [Prisma ORM](https://www.prisma.io/docs). +- Create a Prisma Postgres instance from the Prisma CLI. +- Model data and run migrations with Prisma Postgres. +- Configure Hyperdrive for connection pooling. +- Query the database from Workers using Hyperdrive. +- Deploy the Worker to Cloudflare. + +## Prerequisites + +To follow this guide, ensure you have the following: + +- Node.js `v18.18` or higher installed. +- An active [Cloudflare account](https://dash.cloudflare.com/). +- A basic familiarity with installing and using command-line interface (CLI) applications. + +## 1. Create a new Worker project + +Begin by using [C3](/pages/get-started/c3/) to create a Worker project in the command line: + +```sh +npm create cloudflare@latest prisma-postgres-worker -- --type=hello-world --ts=true --git=true --deploy=false +``` + +Then navigate into your project: + +```sh +cd ./prisma-postgres-worker +``` + +Your initial `src/index.ts` file currently contains a simple request handler: + +```ts title="src/index.ts" +export default { + async fetch(request, env, ctx): Promise { + return new Response("Hello World!"); + }, +} satisfies ExportedHandler; +``` + +## 2. Setup Prisma in your project + +In this step, you will set up Prisma ORM with a Prisma Postgres database using the CLI. Then you will create and execute helper scripts to create tables in the database and generate a Prisma client to query it. + +### 2.1. Install required dependencies + +Install Prisma CLI as a dev dependency: + + + +Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`: + + + +Install the `pg` driver for use with Hyperdrive: + + + +If using TypeScript, install the types package: + + + +### 2.2. Create a Prisma Postgres database and initialize Prisma + +Initialize Prisma in your application: + + + +If you do not have a [Prisma Data Platform](https://console.prisma.io/) account yet, or if you are not logged in, the command will prompt you to log in using one of the available authentication providers. A browser window will open so you can log in or create an account. Return to the CLI after you have completed this step. + +Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region. + +Once the command has terminated, it will have created: + +- A project in your [Platform Console](https://console.prisma.io/) containing a Prisma Postgres database instance. +- A `prisma` folder containing `schema.prisma`, where you will define your database schema. +- An `.env` file in the project root, which will contain the Prisma Postgres database url `DATABASE_URL=`. + +Note that Cloudflare Workers do not support `.env` files. You will use a file called `.dev.vars` instead of the `.env` file that was just created. + +### 2.3. Prepare environment variables + +Rename the `.env` file in the root of your application to `.dev.vars` file: + +```sh +mv .env .dev.vars +``` + +### 2.4. Apply database schema changes + +Open the `schema.prisma` file in the `prisma` folder and add the following `User` model to your database: + +```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()) + email String + name String +} +``` + +Next, add the following helper scripts to the `scripts` section of 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", + // Additional worker scripts... +} +``` + +Run the migration script to apply changes to the database: + +```sh +npm run migrate +``` + +When prompted, provide a name for the migration (for example, `init`). + +After these steps are complete, Prisma ORM is fully set up and connected to your Prisma Postgres database. + +## 3. Configure Hyperdrive + +Create a Hyperdrive configuration that connects to your Prisma Postgres database. Replace the connection string with your actual Prisma Postgres connection string from `.dev.vars`: + +```sh +npx wrangler hyperdrive create prisma-postgres-hyperdrive --connection-string="postgres://your-connection-string-here" +``` + +:::note + +When configuring Hyperdrive for Prisma Postgres, set the maximum connections to 15 to stay within Prisma Postgres connection limits. You can configure this in the Cloudflare dashboard under Hyperdrive settings, or contact support if you need to adjust connection pooling settings. + +::: + +Add the Hyperdrive binding to your `wrangler.toml` file, along with the required Node.js compatibility settings: + +```toml title="wrangler.toml" +name = "prisma-postgres-worker" +main = "src/index.ts" +compatibility_date = "2024-09-23" +compatibility_flags = ["nodejs_compat"] + +[[hyperdrive]] +binding = "HYPERDRIVE" +id = "your-hyperdrive-id-here" +``` + +## 4. Develop the application + +Modify the `src/index.ts` file to use Hyperdrive with Prisma: + +```ts title="src/index.ts" +import { PrismaClient } from "@prisma/client/edge"; + +export interface Env { + HYPERDRIVE: Hyperdrive; +} + +export default { + async fetch(request, env, ctx): Promise { + const path = new URL(request.url).pathname; + if (path === "/favicon.ico") + return new Response("Resource not found", { + status: 404, + headers: { + "Content-Type": "text/plain", + }, + }); + + // Use Hyperdrive connection string with Prisma + const prisma = new PrismaClient({ + datasourceUrl: env.HYPERDRIVE.connectionString, + }); + + const user = await prisma.user.create({ + data: { + email: `Jon${Math.ceil(Math.random() * 1000)}@gmail.com`, + name: "Jon Doe", + }, + }); + + const userCount = await prisma.user.count(); + + return new Response(`\ +Created new user: ${user.name} (${user.email}). +Number of users in the database: ${userCount}. + `); + }, +} satisfies ExportedHandler; +``` + +:::note + +Hyperdrive allows you to use any standard PostgreSQL driver, not just Prisma ORM. You can also use `node-postgres` directly or `postgres.js`. The globally distributed nature of Hyperdrive provides the lowest possible latencies by performing connection pooling across Cloudflare's network. + +::: + +Run the development server: + +```sh +npm run dev +``` + +Visit [`https://localhost:8787`](https://localhost:8787) to see your app display the following output: + +```sh +Created new user: Jon Doe (Jon123@gmail.com). +Number of users in the database: 1 +``` + +Every time you refresh the page, a new user is created. The number displayed will increment by `1` with each refresh as it returns the total number of users in your database. + +## 5. Deploy the application to Cloudflare + +If you're using Hyperdrive, your Hyperdrive configuration is already linked in your `wrangler.toml` file, so no additional secrets are needed. Simply deploy your project: + +```sh +npm run deploy +``` + +The `wrangler` CLI will bundle and upload your application. + +If you are not already logged in, the `wrangler` CLI will open a browser window prompting you to log in to the [Cloudflare dashboard](https://dash.cloudflare.com/). + +:::note +If you belong to multiple accounts, select the account where you want to deploy the project. +::: + +Once the deployment completes, verify the deployment by visiting the live URL provided in the deployment output, such as `https://{PROJECT_NAME}.workers.dev`. If you encounter any issues, ensure the secrets were added correctly and check the deployment logs for errors. + + + + ## Next steps Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers! @@ -237,4 +500,4 @@ To enhance your application further: - Add [caching](https://www.prisma.io/docs/postgres/caching) to your queries. - Explore the [Prisma Postgres documentation](https://www.prisma.io/docs/postgres/getting-started). -To see how to build a real-time application with Cloudflare Workers and Prisma Postgres, read [this](https://www.prisma.io/docs/guides/prisma-postgres-realtime-on-cloudflare) guide. +To see how to build a real-time application with Cloudflare Workers and Prisma Postgres, read [this](https://www.prisma.io/docs/guides/prisma-postgres-realtime-on-cloudflare) guide. \ No newline at end of file