使用 Drizzle 和 Gel 快速入门

This guide assumes familiarity with:

Drizzle 原生支持使用 gel 客户端连接 Gel。

这是项目的基础文件结构。在 src 目录中,我们有 index.ts 文件,用于表的定义。在 drizzle 文件夹中则存放了从 Gel 生成的 Drizzle schema。

📦 <项目根目录>
 ├ 📂 drizzle
 ├ 📂 src
 │ └ 📜 index.ts
 ├ 📜 drizzle.config.ts
 ├ 📜 package.json
 └ 📜 tsconfig.json

第1步 - 安装并初始化 Gel 项目

npm
yarn
pnpm
bun
npx gel project init

第2步 - 定义基础 Gel schema

dbschema/default.esdl 文件中添加基础的 Gel schema

module default {
    type user {
        name: str;
        required email: str;
        age: int16;
    }
}

第3步 - 推送 Gel schema 到数据库

生成 Gel 迁移文件:

gel migration create

应用 Gel 迁移到数据库:

gel migration apply

现在你的文件结构应该是这样

📦 <项目根目录>
 ├ 📂 dbschema
 │ ├ 📂 migrations
 │ ├ 📜 default.esdl
 │ └ 📜 scoping.esdl
 ├ 📂 src
 │ └ 📜 index.ts
 ├ 📜 drizzle.config.ts
 ├ 📜 edgedb.toml
 ├ 📜 package.json
 └ 📜 tsconfig.json

第4步 - 安装所需包

npm
yarn
pnpm
bun
npm i drizzle-orm gel
npm i -D drizzle-kit tsx

第5步 - 配置 Drizzle 配置文件

Drizzle 配置文件Drizzle Kit 使用的配置文件,包含了数据库连接、迁移文件夹及 schema 文件的所有信息。

在项目根目录创建 drizzle.config.ts 文件,并添加如下内容:

drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'gel',
});

第6步 - 从 Gel 同步类型到 Drizzle schema

同步你的数据库 schema:

npm
yarn
pnpm
bun
npx drizzle-kit pull

这是示例生成的 schema.ts 文件:

drizzle/schema.ts
import { gelTable, uniqueIndex, uuid, smallint, text } from "drizzle-orm/gel-core"
import { sql } from "drizzle-orm"

export const users = gelTable("users", {
	id: uuid().default(sql`uuid_generate_v4()`).primaryKey().notNull(),
	age: smallint(),
	email: text().notNull(),
	name: text(),
}, (table) => [
	uniqueIndex("a8c6061c-f37f-11ef-9249-0d78f6c1807b;schemaconstr").using("btree", table.id.asc().nullsLast().op("uuid_ops")),
]);

第7步 - 连接 Drizzle ORM 到数据库

src 目录下创建 index.ts 文件并初始化连接:

src/index.ts
import { drizzle } from "drizzle-orm/gel";
import { createClient } from "gel";

const gelClient = createClient();
const db = drizzle({ client: gelClient });

第8步 - 查询数据库

src/index.ts
import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/gel";
import { createClient } from "gel";
import { users } from "../drizzle/schema";

const gelClient = createClient();
const db = drizzle({ client: gelClient });

async function main() {
  const user: typeof users.$inferInsert = {
    name: "John",
    age: 30,
    email: "john@example.com",
  };

  await db.insert(users).values(user);
  console.log("新用户已创建!");

  const usersResponse = await db.select().from(users);
  console.log("从数据库获取所有用户:", usersResponse);
  /*
  const users: {
    id: number;
    name: string;
    age: number;
    email: string;
  }[]
  */

  await db
    .update(users)
    .set({
      age: 31,
    })
    .where(eq(users.email, user.email));
  console.log("用户信息已更新!");

  await db.delete(users).where(eq(users.email, user.email));
  console.log("用户已删除!");
}

main();

第9步 - 运行 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

npm
yarn
pnpm
bun
npx tsx src/index.ts
tips

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