Drizzle로 데이터베이스 연결하기

Drizzle ORM은 데이터베이스 드라이버를 통해 데이터베이스에서 SQL 쿼리를 실행합니다.

index.ts
schema.ts
import { drizzle } from "drizzle-orm/node-postgres"
import { users } from "./schema"

const db = drizzle(process.env.DATABASE_URL);
const usersCount = await db.$count(users);
                        ┌──────────────────────┐
                        │   db.$count(users)   │ <--- drizzle query
                        └──────────────────────┘     
                            │               ʌ
select count(*) from users -│               │
                            │               │- [{ count: 0 }]
                            v               │
                         ┌─────────────────────┐
                         │    node-postgres    │ <--- database driver
                         └─────────────────────┘
                            │               ʌ
01101000 01100101 01111001 -│               │
                            │               │- 01110011 01110101 01110000
                            v               │
                         ┌────────────────────┐
                         │      Database      │ 
                         └────────────────────┘

내부적으로 Drizzle은 node-postgres 드라이버 인스턴스를 생성하며, 필요한 경우 db.$client를 통해 접근할 수 있습니다

import { drizzle } from "drizzle-orm/node-postgres"

const db = drizzle(process.env.DATABASE_URL);
const pool = db.$client;
// above is equivalent to
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});
const db = drizzle({ client: pool });

Drizzle은 설계상 모든 엣지(edge) 또는 서버리스 런타임과 기본적으로 호환됩니다. 서버리스 데이터베이스에 접근해야 할 때 언제든지 지원합니다

Neon HTTP
Neon with websockets
Vercel Postgres
PlanetScale HTTP
Cloudflare d1
import { drizzle } from "drizzle-orm/neon-http";

const db = drizzle(process.env.DATABASE_URL);

물론, Bun SQLiteExpo SQLite와 같은 런타임별 드라이버도 지원합니다:

import { drizzle } from "drizzle-orm/bun-sqlite"

const db = drizzle(); // <--- will create an in-memory db
const db = drizzle("./sqlite.db");
import { drizzle } from "drizzle-orm/expo-sqlite";
import { openDatabaseSync } from "expo-sqlite";

const expo = openDatabaseSync("db.db");
const db = drizzle(expo);

데이터베이스 연결 URL

데이터베이스 연결 URL 개념에 익숙하지 않은 경우를 위한 설명입니다

postgresql://alex:AbC123dEf@ep-cool-darkness-123456.us-east-2.aws.neon.tech/dbname
             └──┘ └───────┘ └─────────────────────────────────────────────┘ └────┘
              ʌ    ʌ          ʌ                                              ʌ
        role -│    │          │- hostname                                    │- database

                   │- password

다음 단계

드라이버별 문서를 자유롭게 확인해보세요