Gel (구 EdgeDB) 은 Postgres 위에서 작동하는 그래프 - 관계형 데이터베이스입니다. 선언적 스키마 언어, 마이그레이션 시스템 및 객체 지향 쿼리 언어를 제공하며 원시 SQL 쿼리도 지원합니다. 이는 애플리케이션 코드에서 ORM 라이브러리의 필요성을 없애고 데이터베이스 계층에서 객체 - 관계형 매핑 문제를 해결합니다.
먼저 아직 설치하지 않았다면 Gel 을 설치 하세요.
curl https://www.geldata.com/sh --proto "=https" -sSf1 | shirm https://www.geldata.com/ps1 | iexbrew install geldata/tap/gel-clibun init 을 사용하여 새 프로젝트를 만듭니다.
mkdir my-gel-app
cd my-gel-app
bun init -yGel CLI 를 사용하여 프로젝트에 대한 Gel 인스턴스를 초기화합니다. 이는 프로젝트 루트에 gel.toml 파일을 생성합니다.
gel project initNo `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 을 열고 간단한 쿼리를 실행하세요.
gel
gel> select 1 + 1;2그런 다음 \quit 을 실행하여 REPL 을 종료합니다.
gel> \quit프로젝트가 초기화되었으니 이제 스키마를 정의할 수 있습니다. gel project init 명령은 이미 스키마를 포함할 dbschema/default.esdl 파일을 생성했습니다.
dbschema
├── default.esdl
└── migrations해당 파일을 열고 다음 내용을 붙여넣으세요.
module default {
type Movie {
required title: str;
releaseYear: int64;
}
};그런 다음 초기 마이그레이션을 생성하고 적용합니다.
gel migration createCreated /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema/migrations/00001.edgeql, id: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrqgel migrateApplied m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq (00001.edgeql)스키마가 적용되었으니 Gel 의 JavaScript 클라이언트 라이브러리를 사용하여 일부 쿼리를 실행해 보겠습니다. 클라이언트 라이브러리와 Gel 의 codegen CLI 를 설치하고 seed.ts 파일을 생성합니다.
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(`Seeding complete.`);
process.exit();그런 다음 Bun 으로 이 파일을 실행합니다.
bun run seed.tsSeeding complete.Gel 은 TypeScript 를 위한 여러 코드 생성 도구를 구현합니다. 새로 시딩된 데이터베이스를 타입 안전하게 쿼리하기 위해 @gel/generate 를 사용하여 EdgeQL 쿼리 빌더를 생성합니다.
bunx @gel/generate edgeql-jsGenerating 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")
> yindex.ts 에서 ./dbschema/edgeql-js 에서 생성된 쿼리 빌더를 import 하고 간단한 select 쿼리를 작성할 수 있습니다.
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 으로 파일을 실행하면 삽입한 영화 목록을 볼 수 있습니다.
bun run index.ts[
{
title: "The Matrix",
releaseYear: 1999
}, {
title: "The Matrix Reloaded",
releaseYear: 2003
}, {
title: "The Matrix Revolutions",
releaseYear: 2003
}
]전체 문서는 Gel 문서 를 참조하세요.