你可以查看 我们的教程 中关于如何从 CloudFlare 获取环境变量的信息。
开始使用 Drizzle 和 D1
Basic file structure
This is the basic file structure of the project. In the src/db
directory, we have table definition in schema.ts
. In drizzle
folder there are sql migration file and snapshots.
📦 <project root>
├ 📂 drizzle
├ 📂 src
│ ├ 📂 db
│ │ └ 📜 schema.ts
│ └ 📜 index.ts
├ 📜 .env
├ 📜 drizzle.config.ts
├ 📜 package.json
└ 📜 tsconfig.json
步骤 1 - 安装所需软件包
npm i drizzle-orm dotenv
npm i -D drizzle-kit tsx
步骤 2 - 设置 wrangler.toml
你需要一个用于 D1 数据库的 wrangler.toml
文件,其内容如下:
name = "YOUR PROJECT NAME"
main = "src/index.ts"
compatibility_date = "2022-11-07"
node_compat = true
[[ d1_databases ]]
binding = "DB"
database_name = "YOUR DB NAME"
database_id = "YOUR DB ID"
migrations_dir = "drizzle"
步骤 3 - 将 Drizzle ORM 连接到数据库
import { drizzle } from 'drizzle-orm/d1';
export interface Env {
<BINDING_NAME>: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
const db = drizzle(env.<BINDING_NAME>);
},
};
步骤 4 - 创建表
Create a schema.ts
file in the src/db
directory and declare your table:
import { int, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const usersTable = sqliteTable("users_table", {
id: int().primaryKey({ autoIncrement: true }),
name: text().notNull(),
age: int().notNull(),
email: text().notNull().unique(),
});
步骤 5 - 设置 Drizzle 配置文件
Drizzle 配置 - Drizzle 套件 使用的配置文件,包含有关数据库连接、迁移文件夹和模式文件的所有信息。
在项目根目录中创建一个 drizzle.config.ts
文件并添加以下内容:
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'sqlite',
driver: 'd1-http',
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
token: process.env.CLOUDFLARE_D1_TOKEN!,
},
});
步骤 6 - 应用更改到数据库
You can directly apply changes to your database using the drizzle-kit push
command. This is a convenient method for quickly testing new schema designs or modifications in a local development environment, allowing for rapid iterations without the need to manage migration files:
npx drizzle-kit push
Read more about the push command in documentation.
Alternatively, you can generate migrations using the drizzle-kit generate
command and then apply them using the drizzle-kit migrate
command:
Generate migrations:
npx drizzle-kit generate
Apply migrations:
npx drizzle-kit migrate
Read more about migration process in documentation.
步骤 7 - 种子和查询数据库
import { drizzle } from 'drizzle-orm/d1';
export interface Env {
<BINDING_NAME>: D1Database;
}
export default {
async fetch(request: Request, env: Env) {
const db = drizzle(env.<BINDING_NAME>);
const result = await db.select().from(users).all()
return Response.json(result);
},
};
步骤 8 - 运行 index.ts 文件
To run any TypeScript files, you have several options, but let’s stick with one: using tsx
You’ve already installed tsx
, so we can run our queries now
Run index.ts
script
npx tsx src/index.ts
We suggest using bun
to run TypeScript files. With bun
, such scripts can be executed without issues or additional
settings, regardless of whether your project is configured with CommonJS (CJS), ECMAScript Modules (ESM), or any other module format.
To run a script with bun
, use the following command:
bun src/index.ts
If you don’t have bun installed, check the Bun installation docs