Skip to content

Commit a244fa6

Browse files
committed
add drivers and orms to hyperdrive docs
1 parent a637925 commit a244fa6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+772
-213
lines changed

src/content/docs/hyperdrive/configuration/connect-to-private-database.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ Validate that you can connect to your database from Workers and make queries.
199199

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

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

204204
Now, deploy your Worker:
205205

src/content/docs/hyperdrive/examples/connect-to-mysql/index.mdx

+3-63
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,7 @@ npx wrangler hyperdrive create my-first-hyperdrive --connection-string="mysql://
3232

3333
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:
3434

35-
<WranglerConfig>
36-
37-
```toml
38-
# required for database drivers to function
39-
compatibility_flags = ["nodejs_compat"]
40-
compatibility_date = "2024-09-23"
41-
42-
[[hyperdrive]]
43-
binding = "HYPERDRIVE"
44-
id = "<your-hyperdrive-id-here>"
45-
```
46-
47-
</WranglerConfig>
35+
<Render file="hyperdrive-node-compatibility-requirement" product="hyperdrive" />
4836

4937
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.
5038

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

10694
### `mysql`
10795

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

110-
```sh
111-
npm install mysql
112-
```
113-
114-
**Ensure you have `compatibility_flags` and `compatibility_date` set in your [Wrangler configuration file](/workers/wrangler/configuration/)** as shown below:
115-
116-
<Render file="nodejs-compat-wrangler-toml" product="workers" />
117-
118-
Create a new connection and pass the Hyperdrive parameters:
119-
120-
```ts
121-
import { createConnection } from "mysql";
122-
123-
export interface Env {
124-
HYPERDRIVE: Hyperdrive;
125-
}
126-
127-
export default {
128-
async fetch(request, env, ctx): Promise<Response> {
129-
const result = await new Promise<any>((resolve) => {
130-
const connection = createConnection({
131-
host: env.HYPERDRIVE.host,
132-
user: env.HYPERDRIVE.user,
133-
password: env.HYPERDRIVE.password,
134-
database: env.HYPERDRIVE.database,
135-
port: env.HYPERDRIVE.port,
136-
});
137-
138-
connection.connect((error: { message: string }) => {
139-
if (error) {
140-
throw new Error(error.message);
141-
}
142-
143-
connection.query("SHOW tables;", [], (error, rows, fields) => {
144-
connection.end();
145-
146-
resolve({ fields, rows });
147-
});
148-
});
149-
});
150-
151-
return new Response(JSON.stringify(result), {
152-
headers: {
153-
"Content-Type": "application/json",
154-
},
155-
});
156-
},
157-
} satisfies ExportedHandler<Env>;
158-
```
98+
<Render file="use-mysql-to-make-query" product="hyperdrive" />
15999

160100
## Identify connections from Hyperdrive
161101

src/content/docs/hyperdrive/examples/connect-to-mysql/aws-rds-aurora.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-mysql/mysql-database-providers/aws-rds-aurora.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,4 @@ With a database user, password, database endpoint (hostname and port), and datab
9797
## 3. Create a database configuration
9898

9999
<Render file="create-hyperdrive-config-mysql" />
100+
<Render file="create-hyperdrive-config-mysql-next-steps" />

src/content/docs/hyperdrive/examples/connect-to-mysql/azure.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-mysql/mysql-database-providers/azure.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ To connect to a private Azure Database for MySQL instance, refer to [Connect to
3838
## 2. Create a database configuration
3939

4040
<Render file="create-hyperdrive-config-mysql" />
41+
<Render file="create-hyperdrive-config-mysql-next-steps" />

src/content/docs/hyperdrive/examples/connect-to-mysql/google-cloud-sql.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-mysql/mysql-database-providers/google-cloud-sql.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,4 @@ With the username, password, public IP address and (optional) database name (def
4141
## 2. Create a database configuration
4242

4343
<Render file="create-hyperdrive-config-mysql" />
44+
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
type: overview
3+
pcx_content_type: navigation
4+
title: Database Providers
5+
hideChildren: false
6+
sidebar:
7+
order: 5
8+
group:
9+
hideIndex: true
10+
---
11+
12+
import { DirectoryListing } from "~/components";
13+
14+
<DirectoryListing />

src/content/docs/hyperdrive/examples/connect-to-mysql/planetscale.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-mysql/mysql-database-providers/planetscale.mdx

+10
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,13 @@ With the host, database name, username and password, you can now create a Hyperd
2727
## 2. Create a database configuration
2828

2929
<Render file="create-hyperdrive-config-mysql" />
30+
31+
:::note
32+
33+
When connection 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/)
34+
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
35+
will perform global connection pooling and fast query routing by connecting directly to your database.
36+
37+
:::
38+
39+
<Render file="create-hyperdrive-config-mysql-next-steps" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
---
2+
pcx_content_type: example
3+
title: Drizzle ORM
4+
sidebar:
5+
order: 3
6+
meta:
7+
title: Using Drizzle ORM with Hyperdrive for MySQL
8+
---
9+
10+
import { Render } from "~/components";
11+
12+
[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.
13+
14+
## Prerequisites
15+
16+
- A Cloudflare account with Workers access
17+
- A MySQL database
18+
- A [Hyperdrive configuration to your MySQL database](/hyperdrive/get-started/#3-connect-hyperdrive-to-a-database)
19+
20+
## Installation
21+
22+
Install the Drizzle ORM and its dependencies such as the [mysql2](https://github.com/sidorares/node-mysql2) driver:
23+
24+
```sh
25+
# mysql2 v3.13.0 or later is required
26+
npm i drizzle-orm mysql2 dotenv
27+
npm i -D drizzle-kit tsx @types/node
28+
```
29+
30+
Add the required Node.js compatibility flags and Hyperdrive binding to your `wrangler.jsonc` file:
31+
32+
<Render file="hyperdrive-node-compatibility-requirement" />
33+
34+
## Configure Drizzle
35+
36+
### Define a schema
37+
38+
With Drizzle ORM, we define the schema in TypeScript rather than writing raw SQL. Here's how to define a users table:
39+
40+
```ts
41+
// src/schema.ts
42+
import { mysqlTable, int, varchar, timestamp } from "drizzle-orm/mysql-core";
43+
44+
export const users = mysqlTable("users", {
45+
id: int("id").primaryKey().autoincrement(),
46+
name: varchar("name", { length: 255 }).notNull(),
47+
email: varchar("email", { length: 255 }).notNull().unique(),
48+
createdAt: timestamp("created_at").defaultNow(),
49+
});
50+
```
51+
52+
### Connect Drizzle ORM to the database with Hyperdrive
53+
54+
Use your the credentials of your Hyperdrive configuration for your database when using the
55+
Drizzle ORM within your Worker project as such:
56+
57+
```ts
58+
// src/db/schema.ts
59+
60+
import { drizzle } from "drizzle-orm/mysql2";
61+
import { createConnection } from "mysql2";
62+
import { users } from "./db/schema";
63+
64+
export default {
65+
async fetch(request, env, ctx): Promise<Response> {
66+
// Create a connection using the mysql2 driver with the Hyperdrive credentials (only accessible from your Worker).
67+
const connection = await createConnection({
68+
host: env.HYPERDRIVE.host,
69+
user: env.HYPERDRIVE.user,
70+
password: env.HYPERDRIVE.password,
71+
database: env.HYPERDRIVE.database,
72+
port: env.HYPERDRIVE.port,
73+
74+
// Required to enable mysql2 compatibility for Workers
75+
disableEval: true,
76+
});
77+
78+
// Create the Drizzle client with the mysql2 driver connection
79+
const db = drizzle(connection);
80+
81+
// Sample query to get all users
82+
const allUsers = await db.select().from(users);
83+
84+
return Response.json(allUsers);
85+
},
86+
} satisfies ExportedHandler<Env>;
87+
```
88+
89+
### Configure Drizzle-Kit for migrations (optional)
90+
91+
You can generate and run SQL migrations on your database based on your schema
92+
using Drizzle Kit CLI. Refer to [Drizzle ORM docs](https://orm.drizzle.team/docs/get-started/mysql-new) for additional guidance.
93+
94+
1. Create a `.env` file and add your database connection string. The Drizzle Kit CLI will use
95+
this connection string to create and apply the migrations.
96+
97+
```toml
98+
# Replace with your direct database connection string
99+
DATABASE_URL='mysql://user:[email protected]/database-name'
100+
```
101+
102+
2. Create a `drizzle.config.ts` file in the root of your project to configure Drizzle Kit
103+
and add the following content:
104+
105+
```ts
106+
import 'dotenv/config';
107+
import { defineConfig } from 'drizzle-kit';
108+
export default defineConfig({
109+
out: './drizzle',
110+
schema: './src/db/schema.ts',
111+
dialect: 'mysql',
112+
dbCredentials: {
113+
url: process.env.DATABASE_URL!,
114+
},
115+
});
116+
```
117+
118+
3. Generate the migration file for your database according to your schema files and apply the migrations to your database.
119+
`bash
120+
npx drizzle-kit generate
121+
npx drizzle-kit migrate
122+
`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
pcx_content_type: navigation
3+
title: Libraries and Drivers
4+
sidebar:
5+
order: 8
6+
group:
7+
hideIndex: true
8+
---
9+
10+
import { DirectoryListing } from "~/components";
11+
12+
<DirectoryListing />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
pcx_content_type: example
3+
title: mysql
4+
sidebar:
5+
order: 2
6+
meta:
7+
title: Using mysql driver with Hyperdrive
8+
---
9+
10+
import { Render } from "~/components";
11+
12+
The [mysql](https://github.com/mysqljs/mysql) package is a MySQL driver for Node.js.
13+
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.
14+
15+
<Render file="use-mysql-to-make-query" product="hyperdrive" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
pcx_content_type: example
3+
title: mysql2
4+
sidebar:
5+
order: 1
6+
---
7+
8+
import { Render } from "~/components";
9+
10+
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.
11+
This example demonstrates how to use it with Cloudflare Workers and Hyperdrive.
12+
13+
<Render file="use-mysql2-to-make-query" product="hyperdrive" />

src/content/docs/hyperdrive/examples/connect-to-postgres/index.mdx

+3-59
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,7 @@ npx wrangler hyperdrive create my-first-hyperdrive --connection-string="postgres
3232

3333
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:
3434

35-
<WranglerConfig>
36-
37-
```toml
38-
# required for database drivers to function
39-
compatibility_flags = ["nodejs_compat"]
40-
compatibility_date = "2024-09-23"
41-
42-
[[hyperdrive]]
43-
binding = "HYPERDRIVE"
44-
id = "<your-hyperdrive-id-here>"
45-
```
46-
47-
</WranglerConfig>
35+
<Render file="hyperdrive-node-compatibility-requirement" product="hyperdrive" />
4836

4937
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.
5038

@@ -84,57 +72,13 @@ The following examples show you how to:
8472

8573
The following Workers code shows you how to use [Postgres.js](https://github.com/porsager/postgres) with Hyperdrive.
8674

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

8977
### node-postgres / pg
9078

9179
Install the `node-postgres` driver:
9280

93-
```sh
94-
npm install pg
95-
```
96-
97-
**Ensure you have `compatibility_flags` and `compatibility_date` set in your [Wrangler configuration file](/workers/wrangler/configuration/)** as shown below:
98-
99-
<Render file="nodejs-compat-wrangler-toml" product="workers" />
100-
101-
Create a new `Client` instance and pass the Hyperdrive parameters:
102-
103-
```ts
104-
import { Client } from "pg";
105-
106-
export interface Env {
107-
// If you set another name in the Wrangler configuration file as the value for 'binding',
108-
// replace "HYPERDRIVE" with the variable name you defined.
109-
HYPERDRIVE: Hyperdrive;
110-
}
111-
112-
export default {
113-
async fetch(request, env, ctx): Promise<Response> {
114-
const client = new Client({
115-
connectionString: env.HYPERDRIVE.connectionString,
116-
});
117-
118-
try {
119-
// Connect to your database
120-
await client.connect();
121-
122-
// A very simple test query
123-
const result = await client.query({ text: "SELECT * FROM pg_tables" });
124-
125-
// Clean up the client, ensuring we don't kill the worker before that is
126-
// completed.
127-
ctx.waitUntil(client.end());
128-
129-
// Return result rows as JSON
130-
return Response.json({ result: result });
131-
} catch (e) {
132-
console.log(e);
133-
return Response.json({ error: e.message }, { status: 500 });
134-
}
135-
},
136-
} satisfies ExportedHandler<Env>;
137-
```
81+
<Render file="use-node-postgres-to-make-query" product="hyperdrive" />
13882

13983
## Identify connections from Hyperdrive
14084

src/content/docs/hyperdrive/examples/connect-to-postgres/aws-rds-aurora.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/aws-rds-aurora.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,4 @@ With a database user, password, database endpoint (hostname and port) and databa
9191
## 3. Create a database configuration
9292

9393
<Render file="create-hyperdrive-config" />
94+
<Render file="create-hyperdrive-config-next-steps" />

src/content/docs/hyperdrive/examples/connect-to-postgres/azure.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/azure.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ To connect to a private Azure Database for PostgreSQL instance, refer to [Connec
3838
## 2. Create a database configuration
3939

4040
<Render file="create-hyperdrive-config" />
41+
<Render file="create-hyperdrive-config-next-steps" />

src/content/docs/hyperdrive/examples/connect-to-postgres/cockroachdb.mdx renamed to src/content/docs/hyperdrive/examples/connect-to-postgres/postgres-database-providers/cockroachdb.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,4 @@ By default, the CockroachDB cloud enables connections from the public Internet (
4141
## 2. Create a database configuration
4242

4343
<Render file="create-hyperdrive-config" />
44+
<Render file="create-hyperdrive-config-next-steps" />

0 commit comments

Comments
 (0)