|
| 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 | +` |
0 commit comments