在 Bun 中使用 Gel
Gel(前身為 EdgeDB)是一個建置於 Postgres 之上的圖關係型資料庫。它提供宣告式模式語言、遷移系統和麵向物件的查詢語言。它也支援原始 SQL 查詢。它在資料庫層解決了物件關係對映問題,因此你的應用程式碼無需使用 ORM 庫。
首先,如果你還沒有安裝,請安裝 Gel。
Linux/macOS
curl https://www.geldata.com/sh --proto "=https" -sSf1 | sh
Windows
irm https://www.geldata.com/ps1 | iex
Homebrew
brew install geldata/tap/gel-cli
使用 bun init 建立一個新的專案。
terminal
mkdir my-gel-app
cd my-gel-app
bun init -y
使用 Gel CLI 為專案初始化一個 Gel 例項。gel project init 命令會在專案根目錄中建立一個 gel.toml 檔案。
terminal
gel project init
Text
No `gel.toml` (or `edgedb.toml`) found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above
Initializing new project...
Checking Gel versions...
┌─────────────────────┬──────────────────────────────────────────────────────────────────┐
│ 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 │
│ Branch │ main │
└─────────────────────┴──────────────────────────────────────────────────────────────────┘
Version x.y+6d5921b is already downloaded
Initializing Gel instance 'my_gel_app'...
Applying migrations...
Everything is up to date. Revision initial
Writing gel.local.toml for configuration
Project initialized.
To connect to my_gel_app, run `gel`
要檢查資料庫是否正在執行,請開啟 REPL 並執行一個查詢。
terminal
gel
my_gel_app:main> select 1 + 1;
Text
{2}
然後執行 \quit 退出 REPL。
terminal
my_gel_app:main> \quit
接下來,定義一個模式。gel project init 命令已經建立了一個 dbschema/default.gel 檔案來儲存它。
File
dbschema
├── default.gel
├── extensions.gel
├── futures.gel
└── migrations
開啟該檔案,貼上以下內容。
default.gel
module default {
type Movie {
required title: str;
releaseYear: int64;
}
};
然後生成並應用一個初始遷移。
terminal
gel migration create
Text
Created dbschema/migrations/00001-m1uwekr.edgeql, id: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq
terminal
gel migrate
Text
Applying m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq (00001-m1uwekr.edgeql)
... parsed
... applied
應用模式後,使用 Gel 的 JavaScript 客戶端庫查詢資料庫。安裝客戶端庫和 Gel 的程式碼生成 CLI,然後建立一個 seed.ts 檔案。
terminal
bun add gel
bun add -D @gel/generate
touch seed.ts
將以下程式碼貼上到 seed.ts。
客戶端會自動連線到資料庫。該指令碼使用 .execute() 方法插入幾部電影,並使用 EdgeQL 的 for 表示式將批次插入轉換為單個查詢。
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 執行此檔案。
terminal
bun run seed.ts
Text
種子資料插入完成。
Gel 為 TypeScript 提供了多個程式碼生成工具。要針對已填充種子資料的資料庫編寫型別安全的查詢,請使用 @gel/generate 生成 EdgeQL 查詢建置器。
terminal
bunx @gel/generate edgeql-js
Text
Generating query builder...
Detected tsconfig.json, generating TypeScript files.
To override this, use the --target flag.
Run `npx @gel/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](留空為"y")
> y
在 index.ts 中,從 ./dbschema/edgeql-js 匯入生成的查詢建置器,並編寫一個選擇查詢。
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 執行該檔案,檢視剛才插入的電影。
terminal
bun run index.ts
Text
[
{
title: "The Matrix",
releaseYear: 1999,
}, {
title: "The Matrix Reloaded",
releaseYear: 2003,
}, {
title: "The Matrix Revolutions",
releaseYear: 2003,
}
]
請參閱 Gel 文件。