Skip to content

[Hyperdrive] add drivers and orms docs #22125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: production
Choose a base branch
from
Open
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
18 changes: 17 additions & 1 deletion public/__redirects
Original file line number Diff line number Diff line change
Expand Up @@ -1709,7 +1709,23 @@
/hyperdrive/examples/timescale/ /hyperdrive/examples/connect-to-postgres/timescale/ 301
/hyperdrive/examples/xata/ /hyperdrive/examples/connect-to-postgres/xata/ 301
/hyperdrive/examples/fly/ /hyperdrive/examples/connect-to-postgres/fly/ 301

/hyperdrive/examples/aws-rds-aurora/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/aws-rds-aurora/ 301
/hyperdrive/examples/azure/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/azure/ 301
/hyperdrive/examples/cockroachdb/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/cockroachdb/ 301
/hyperdrive/examples/digital-ocean/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/digital-ocean/ 301
/hyperdrive/examples/google-cloud-sql/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/google-cloud-sql/ 301
/hyperdrive/examples/materialize/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/materialize/ 301
/hyperdrive/examples/neon/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/neon/ 301
/hyperdrive/examples/nile/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/nile/ 301
/hyperdrive/examples/pgedge/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/pgedge/ 301
/hyperdrive/examples/supabase/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/supabase/ 301
/hyperdrive/examples/timescale/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/timescale/ 301
/hyperdrive/examples/xata/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/xata/ 301
/hyperdrive/examples/fly/ /hyperdrive/examples/connect-to-postgres/postgres-database-providers/fly/ 301
/hyperdrive/examples/connect-to-mysql/planetscale/ /hyperdrive/examples/connect-to-mysql/mysql-database-providers/planetscale/ 301
/hyperdrive/examples/connect-to-mysql/azure/ /hyperdrive/examples/connect-to-mysql/mysql-database-providers/azure/ 301
/hyperdrive/examples/connect-to-mysql/google-cloud-sql/ /hyperdrive/examples/connect-to-mysql/mysql-database-providers/google-cloud-sql/ 301
/hyperdrive/examples/connect-to-mysql/aws-rds-aurora/ /hyperdrive/examples/connect-to-mysql/mysql-database-providers/aws-rds-aurora/ 301

/hyperdrive/reference/supported-databases/ /hyperdrive/reference/supported-databases-and-features/ 301
/hyperdrive/configuration/connect-to-postgres/ /hyperdrive/examples/connect-to-postgres/ 301
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ Validate that you can connect to your database from Workers and make queries.

Use Postgres.js to send a test query to validate that the connection has been successful.

<Render file="use-postgresjs-to-make-query" product="hyperdrive" />
<Render file="use-postgres-js-to-make-query" product="hyperdrive" />

Now, deploy your Worker:

Expand Down
66 changes: 3 additions & 63 deletions src/content/docs/hyperdrive/examples/connect-to-mysql/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,7 @@ npx wrangler hyperdrive create my-first-hyperdrive --connection-string="mysql://

The command above will output the ID of your Hyperdrive, which you will need to set in the [Wrangler configuration file](/workers/wrangler/configuration/) for your Workers project:

<WranglerConfig>

```toml
# required for database drivers to function
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"
```

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

This will allow Hyperdrive to generate a dynamic connection string within your Worker that you can pass to your existing database driver. Refer to [Driver examples](#driver-examples) to learn how to set up a database driver with Hyperdrive.

Expand Down Expand Up @@ -105,57 +93,9 @@ The following Workers code shows you how to use [mysql2](https://github.com/sido

### `mysql`

Install the `mysql` driver:
The following Workers code shows you how to use [mysql](https://github.com/mysqljs/mysql) with Hyperdrive.

```sh
npm install mysql
```

**Ensure you have `compatibility_flags` and `compatibility_date` set in your [Wrangler configuration file](/workers/wrangler/configuration/)** as shown below:

<Render file="nodejs-compat-wrangler-toml" product="workers" />

Create a new connection and pass the Hyperdrive parameters:

```ts
import { createConnection } from "mysql";

export interface Env {
HYPERDRIVE: Hyperdrive;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const result = await new Promise<any>((resolve) => {
const connection = createConnection({
host: env.HYPERDRIVE.host,
user: env.HYPERDRIVE.user,
password: env.HYPERDRIVE.password,
database: env.HYPERDRIVE.database,
port: env.HYPERDRIVE.port,
});

connection.connect((error: { message: string }) => {
if (error) {
throw new Error(error.message);
}

connection.query("SHOW tables;", [], (error, rows, fields) => {
connection.end();

resolve({ fields, rows });
});
});
});

return new Response(JSON.stringify(result), {
headers: {
"Content-Type": "application/json",
},
});
},
} satisfies ExportedHandler<Env>;
```
<Render file="use-mysql-to-make-query" product="hyperdrive" />

## Identify connections from Hyperdrive

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,4 @@ With a database user, password, database endpoint (hostname and port), and datab
## 3. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@ To connect to a private Azure Database for MySQL instance, refer to [Connect to
## 2. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ With the username, password, public IP address and (optional) database name (def
## 2. Create a database configuration

<Render file="create-hyperdrive-config-mysql" />
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
type: overview
pcx_content_type: navigation
title: Database Providers
hideChildren: false
sidebar:
order: 5
group:
hideIndex: true
---

import { DirectoryListing } from "~/components";

<DirectoryListing />
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ With the host, database name, username and password, you can now create a Hyperd
## 2. Create a database configuration

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

:::note

When connecting to a Planetscale 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 database instead of the [Planetscale serverless driver](https://planetscale.com/docs/tutorials/planetscale-serverless-driver). 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-mysql-next-steps" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
---
pcx_content_type: example
title: Drizzle ORM
sidebar:
order: 3
meta:
title: Using Drizzle ORM with Hyperdrive for MySQL
---

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

[Drizzle ORM](https://orm.drizzle.team/) is a lightweight TypeScript ORM with a focus on type safety. This example demonstrates how to use Drizzle ORM with MySQL via Cloudflare Hyperdrive in a Workers application.

## Prerequisites

- A Cloudflare account with Workers access
- A MySQL database
- A [Hyperdrive configuration to your MySQL database](/hyperdrive/get-started/#3-connect-hyperdrive-to-a-database)

## 1. Install Drizzle

Install the Drizzle ORM and its dependencies such as the [mysql2](https://github.com/sidorares/node-mysql2) driver:

```sh
# mysql2 v3.13.0 or later is required
npm i drizzle-orm mysql2 dotenv
npm i -D drizzle-kit tsx @types/node
```

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

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

## 2. Configure Drizzle

### 2.1. Define a schema

With Drizzle ORM, we define the schema in TypeScript rather than writing raw SQL.

<Steps>
1. Create a folder `/db/` in `/src/`.
2. Create a `schema.ts` file.
3. In `schema.ts`, define a `users` table as shown below.

```ts title="src/db/schema.ts"
// src/schema.ts
import { mysqlTable, int, varchar, timestamp } from "drizzle-orm/mysql-core";

export const users = mysqlTable("users", {
id: int("id").primaryKey().autoincrement(),
name: varchar("name", { length: 255 }).notNull(),
email: varchar("email", { length: 255 }).notNull().unique(),
createdAt: timestamp("created_at").defaultNow(),
});
```
</Steps>

### 2.2. Connect Drizzle ORM to the database with Hyperdrive

Use your the credentials of your Hyperdrive configuration for your database when using the Drizzle ORM.

Populate your `index.ts` file as shown below.

```ts title="src/index.ts"
// src/index.ts

import { drizzle } from "drizzle-orm/mysql2";
import { createConnection } from "mysql2";
import { users } from "./db/schema";

export interface Env {
HYPERDRIVE: Hyperdrive;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a connection using the mysql2 driver with the Hyperdrive credentials (only accessible from your Worker).
const connection = await createConnection({
host: env.HYPERDRIVE.host,
user: env.HYPERDRIVE.user,
password: env.HYPERDRIVE.password,
database: env.HYPERDRIVE.database,
port: env.HYPERDRIVE.port,

// Required to enable mysql2 compatibility for Workers
disableEval: true,
});

// Create the Drizzle client with the mysql2 driver connection
const db = drizzle(connection);

// Sample query to get all users
const allUsers = await db.select().from(users);

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

If your database is empty, continue to step [2.3. Configure Drizzle-Kit for migration](/hyperdrive/examples/connect-to-mysql/mysql-drivers-and-libraries/drizzle-orm/#23-configure-drizzle-kit-for-migrations-optional).

### 2.3. Configure Drizzle-Kit for migrations (optional)

You can generate and run SQL migrations on your database based on your schema using Drizzle Kit CLI. Refer to [Drizzle ORM docs](https://orm.drizzle.team/docs/get-started/mysql-new) for additional guidance.

<Steps>
1. Create a `.env` file in the root folder of your project, and add your database connection string. The Drizzle Kit CLI will use this connection string to create and apply the migrations.

```toml title=".env"
# .env
# Replace with your direct database connection string
DATABASE_URL='mysql://user:[email protected]/database-name'
```

2. Create a `drizzle.config.ts` file in the root folder of your project to configure Drizzle Kit and add the following content:

```ts title="drizzle.config.ts"
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'mysql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
```

3. Generate the migration file for your database according to your schema files and apply the migrations to your database.

```bash
npx drizzle-kit generate
```
```bash output
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/junlee/tutorials/jun-hyperdrive-drizzle-mysql/drizzle.config.ts'
Reading schema files:
/Users/junlee/tutorials/jun-hyperdrive-drizzle-mysql/src/db/schema.ts

1 tables
users 4 columns 0 indexes 0 fks

[✓] Your SQL migration file ➜ drizzle/0000_daffy_rhodey.sql 🚀
```
```bash
npx drizzle-kit migrate
```
```bash output
No config path provided, using default 'drizzle.config.ts'
Reading config file '/Users/junlee/tutorials/jun-hyperdrive-drizzle-mysql/drizzle.config.ts'
```
</Steps>

## 3. 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
@@ -0,0 +1,12 @@
---
pcx_content_type: navigation
title: Libraries and Drivers
sidebar:
order: 8
group:
hideIndex: true
---

import { DirectoryListing } from "~/components";

<DirectoryListing />
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
pcx_content_type: example
title: mysql
sidebar:
order: 2
meta:
title: Using mysql driver with Hyperdrive
---

import { Render } from "~/components";

The [mysql](https://github.com/mysqljs/mysql) package is a MySQL driver for Node.js.
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.

<Render file="use-mysql-to-make-query" product="hyperdrive" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
pcx_content_type: example
title: mysql2
sidebar:
order: 1
---

import { Render } from "~/components";

The [mysql2](https://github.com/sidorares/node-mysql2) package is a modern MySQL driver for Node.js with better performance and built-in Promise support.
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.

<Render file="use-mysql2-to-make-query" product="hyperdrive" />
Loading
Loading