Drizzle과 Gel 시작하기

This guide assumes familiarity with:

Drizzle은 gel 클라이언트를 통해 Gel 연결을 기본적으로 지원합니다.

이것은 프로젝트의 기본 파일 구조입니다. src 디렉토리에는 index.ts에 테이블 정의가 있습니다. drizzle 폴더에는 Gel에서 Drizzle 스키마로 생성된 파일이 있습니다

📦 <project root>
 ├ 📂 drizzle
 ├ 📂 src
 │ └ 📜 index.ts
 ├ 📜 drizzle.config.ts
 ├ 📜 package.json
 └ 📜 tsconfig.json

Step 1 - Gel 프로젝트 설치 및 초기화

npm
yarn
pnpm
bun
npx gel project init

Step 2 - 기본 Gel 스키마 정의

dbschema/default.esdl 파일에 기본 Gel 스키마를 추가합니다

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

Step 3 - Gel 스키마를 데이터베이스에 푸시

Gel 마이그레이션 파일 생성:

gel migration create

Gel 마이그레이션을 데이터베이스에 적용

gel migration apply

이제 다음과 같은 파일 구조를 갖게 됩니다

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

Step 4 - 필수 패키지 설치

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

Step 5 - Drizzle 설정 파일 설정

Drizzle config - Drizzle Kit에서 사용하는 설정 파일로, 데이터베이스 연결, 마이그레이션 폴더 및 스키마 파일에 대한 모든 정보를 포함합니다.

프로젝트 루트에 drizzle.config.ts 파일을 생성하고 다음 내용을 추가합니다:

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

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

Step 6 - Gel 타입을 Drizzle 스키마로 풀

데이터베이스 스키마를 풀합니다:

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")),
]);

Step 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 });

Step 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("New user created!");

  const usersResponse = await db.select().from(users);
  console.log("Getting all users from the database: ", 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("User info updated!");

  await db.delete(users).where(eq(users.email, user.email));
  console.log("User deleted!");
}

main();

Step 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