Skip to content

Gel(前身為 EdgeDB)是一個底層由 Postgres 驅動的圖關系數據庫。它提供聲明式模式語言、遷移系統和面向對象查詢語言,此外還支持原始 SQL 查詢。它在數據庫層解決了對象關系映射問題,消除了在你的應用代碼中使用 ORM 庫的需求。


首先,如果你還沒有安裝,請 安裝 Gel

sh
curl https://www.geldata.com/sh --proto "=https" -sSf1 | sh
sh
irm https://www.geldata.com/ps1 | iex
sh
brew install geldata/tap/gel-cli

使用 bun init 創建一個新項目。

sh
mkdir my-edgedb-app
cd my-edgedb-app
bun init -y

我們將使用 Gel CLI 為我們的項目初始化一個 Gel 實例。這會在項目根目錄創建一個 gel.toml 文件。

sh
gel project init
txt
No `gel.toml` found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above
Do you want to initialize a new project? [Y/n]
> Y
Specify the name of Gel instance to use with this project [default: my_gel_app]:
> my_gel_app
Checking Gel versions...
Specify the version of Gel to use with this project [default: x.y]:
> x.y
┌─────────────────────┬──────────────────────────────────────────────────────────────────┐
│ Project directory   │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app         │
│ Project config      │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│
│ Schema dir (empty)  │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│
│ Installation method │ portable package                                                 │
│ Version             │ x.y+6d5921b                                                      │
│ Instance name       │ my_gel_app                                                       │
└─────────────────────┴──────────────────────────────────────────────────────────────────┘
Version x.y+6d5921b is already downloaded
Initializing Gel instance...
Applying migrations...
Everything is up to date. Revision initial
Project initialized.
To connect to my_gel_app, run `gel`

要查看數據庫是否正在運行,讓我們打開一個 REPL 並運行一個簡單的查詢。

sh
gel
gel> select 1 + 1;
txt
2

然後運行 \quit 退出 REPL。

sh
gel> \quit

項目初始化後,我們可以定義一個模式。gel project init 命令已經創建了一個 dbschema/default.esdl 文件來包含我們的模式。

txt
dbschema
├── default.esdl
└── migrations

打開該文件並粘貼以下內容。

ts
module default {
  type Movie {
    required title: str;
    releaseYear: int64;
  }
};

然後生成並應用初始遷移。

sh
gel migration create
txt
Created /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema/migrations/00001.edgeql, id: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq
sh
gel migrate
txt
Applied m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq (00001.edgeql)

應用模式後,讓我們使用 Gel 的 JavaScript 客戶端庫執行一些查詢。我們將安裝客戶端庫和 Gel 的代碼生成 CLI,並創建一個 seed.ts 文件。

sh
bun add gel
bun add -D @gel/generate
touch seed.ts

將以下代碼粘貼到 seed.ts 中。

客戶端會自動連接到數據庫。我們使用 .execute() 方法插入幾部電影。我們將使用 EdgeQL 的 for 表達式將這個批量插入轉換為單個優化查詢。

ts
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(`Seeding complete.`);
process.exit();

然後使用 Bun 運行此文件。

sh
bun run seed.ts
txt
Seeding complete.

Gel 為 TypeScript 實現了許多代碼生成工具。為了以類型安全的方式查詢我們新播種的數據庫,我們將使用 @gel/generate 來代碼生成 EdgeQL 查詢構建器。

sh
bunx @gel/generate edgeql-js
txt
Generating query builder...
Detected tsconfig.json, generating TypeScript files.
   To override this, use the --target flag.
   Run `npx @edgedb/generate --help` for full options.
Introspecting database schema...
Writing files to ./dbschema/edgeql-js
Generation complete! 🤘
Checking the generated query builder into version control
is not recommended. Would you like to update .gitignore to ignore
the query builder directory? The following line will be added:

   dbschema/edgeql-js

[y/n] (leave blank for "y")
> y

index.ts 中,我們可以從 ./dbschema/edgeql-js 導入生成的查詢構建器並編寫一個簡單的 select 查詢。

ts
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 }[]

使用 Bun 運行文件,我們可以看到我們插入的電影列表。

sh
bun run index.ts
txt
[
  {
    title: "The Matrix",
    releaseYear: 1999
  }, {
    title: "The Matrix Reloaded",
    releaseYear: 2003
  }, {
    title: "The Matrix Revolutions",
    releaseYear: 2003
  }
]

有關完整文檔,請參閱 Gel 文檔

Bun學習網由www.bunjs.com.cn整理維護