> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 Bun 中使用 Gel

Gel（前身为 EdgeDB）是一款由 Postgres 支持的图关系数据库。它提供声明式模式语言、迁移系统和面向对象的查询语言，同时还支持原生 SQL 查询。它在数据库层面解决了对象关系映射问题，免去了在应用代码中使用 ORM 库的必要。

***

首先，如果你还没有安装，[请安装 Gel](https://docs.geldata.com/learn/installation)。

<CodeGroup>
  ```sh Linux/macOS terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
  curl https://www.geldata.com/sh --proto "=https" -sSf1 | sh
  ```

  ```sh Windows terminal icon="windows" theme={"theme":{"light":"github-light","dark":"dracula"}}
  irm https://www.geldata.com/ps1 | iex
  ```

  ```sh Homebrew terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
  brew install geldata/tap/gel-cli
  ```
</CodeGroup>

***

使用 `bun init` 创建一个新的项目。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
mkdir my-edgedb-app
cd my-edgedb-app
bun init -y
```

***

我们将使用 Gel CLI 来为项目初始化一个 Gel 实例。这将在项目根目录创建一个 `gel.toml` 文件。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
gel project init
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
在 `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` 或其上级目录未找到 `gel.toml`
是否要初始化一个新项目？[Y/n]
> Y
请为此项目指定要使用的 Gel 实例名称 [默认: my_gel_app]:
> my_gel_app
正在检查 Gel 版本...
请为此项目指定要使用的 Gel 版本 [默认: x.y]:
> x.y
┌─────────────────────┬──────────────────────────────────────────────────────────────────┐
│ 项目目录           │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app         │
│ 项目配置           │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│
│ 模式目录（空）     │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│
│ 安装方式           │ 便携包                                                         │
│ 版本               │ x.y+6d5921b                                                    │
│ 实例名称           │ my_gel_app                                                     │
└─────────────────────┴──────────────────────────────────────────────────────────────────┘
版本 x.y+6d5921b 已下载
正在初始化 Gel 实例...
正在应用迁移...
所有内容均为最新。版本 initial
项目已初始化。
连接到 my_gel_app，请运行 `gel`
```

***

为了确认数据库是否正在运行，我们打开一个 REPL 并运行查询。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
gel
gel> select 1 + 1;
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
2
```

然后运行 `\quit` 退出 REPL。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
gel> \quit
```

***

项目初始化完成后，我们可以定义一个模式。`gel project init` 命令已创建了一个 `dbschema/default.esdl` 文件用于保存我们的模式定义。

```txt File Tree icon="folder-tree" theme={"theme":{"light":"github-light","dark":"dracula"}}
dbschema
├── default.esdl
└── migrations
```

***

打开该文件，粘贴以下内容。

```ts default.esdl icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
module default {
  type Movie {
    required title: str;
    releaseYear: int64;
  }
};
```

***

然后生成并应用一个初始迁移。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
gel migration create
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
已创建 /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema/migrations/00001.edgeql，ID: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq
```

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
gel migrate
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
已应用 m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq (00001.edgeql)
```

***

应用模式后，我们通过 Gel 的 JavaScript 客户端库执行一些查询。安装客户端库和 Gel 的代码生成 CLI，创建一个 `seed.ts` 文件。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun add gel
bun add -D @gel/generate
touch seed.ts
```

***

将以下代码粘贴到 `seed.ts`。

客户端会自动连接数据库。我们使用 `.execute()` 方法插入几部电影。这里使用 EdgeQL 的 `for` 表达式将多个插入操作合并为一个优化查询。

```ts seed.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { createClient } from "gel";

const client = createClient();

const INSERT_MOVIE = `
  with movies := <array<tuple<title: str, year: int64>>>$movies
  for movie in array_unpack(movies) union (
    insert Movie {
      title := movie.title,
      releaseYear := movie.year,
    }
  )
`;

const movies = [
  { title: "The Matrix", year: 1999 },
  { title: "The Matrix Reloaded", year: 2003 },
  { title: "The Matrix Revolutions", year: 2003 },
];

await client.execute(INSERT_MOVIE, { movies });

console.log(`种子数据插入完成。`);
process.exit();
```

***

然后使用 Bun 运行此文件。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run seed.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
种子数据插入完成。
```

***

Gel 为 TypeScript 提供了多种代码生成工具。为了类型安全地查询我们的新数据库，使用 `@gel/generate` 生成 EdgeQL 查询构建器。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bunx @gel/generate edgeql-js
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
正在生成查询构建器...
检测到 tsconfig.json，正在生成 TypeScript 文件。
   如需覆盖此行为，请使用 --target 标志。
   运行 `npx @edgedb/generate --help` 获取完整选项。
正在检查数据库模式...
正在写入文件到 ./dbschema/edgeql-js
生成完成！🤘
不建议将生成的查询构建器纳入版本控制。
是否要将查询构建器目录添加到 .gitignore？将添加以下内容：

   dbschema/edgeql-js

[y/n]（留空为"y"）
> y
```

***

在 `index.ts` 中，我们可以从 `./dbschema/edgeql-js` 导入生成的查询构建器，并编写一个 select 查询。

```ts index.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { createClient } from "gel";
import e from "./dbschema/edgeql-js";

const client = createClient();

const query = e.select(e.Movie, () => ({
  title: true,
  releaseYear: true,
}));

const results = await query.run(client);
console.log(results);

results; // { title: string, releaseYear: number | null }[]
```

***

运行该文件，可以看到我们插入的电影列表。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun run index.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
[
  {
    title: "The Matrix",
    releaseYear: 1999
  }, {
    title: "The Matrix Reloaded",
    releaseYear: 2003
  }, {
    title: "The Matrix Revolutions",
    releaseYear: 2003
  }
]
```

***

更多完整文档，请参考 [Gel 文档](https://docs.geldata.com/)。
