Skip to content

Neon 은 컴퓨팅과 스토리지를 분리하여 자동 확장, 브랜칭 및 무제한 스토리지와 같은 기능을 제공하는 완전 관리형 서버리스 Postgres 입니다. Neon 은 @neondatabase/serverless 드라이버를直接使用하거나 Drizzle 과 같은 ORM 을 통해 Bun 에서直接使用할 수 있습니다.

Drizzle ORM 은 SQL 유사 "쿼리 빌더" API 와 ORM 유사 쿼리 API 를 모두 지원합니다. 프로젝트 디렉터리를 생성하고 bun init 으로 디렉터리를 초기화한 다음 Drizzle 과 Neon serverless driver 를 설치하여 시작하세요.

sh
mkdir bun-drizzle-neon
cd bun-drizzle-neon
bun init -y
bun add drizzle-orm @neondatabase/serverless
bun add -D drizzle-kit

.env.local 파일을 생성하고 Neon Postgres 연결 문자열 을 추가하세요.

ini
DATABASE_URL=postgresql://usertitle:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require

Neon serverless driver 를 사용하여 Neon 데이터베이스에 연결하고 Drizzle 데이터베이스 인스턴스로 래핑합니다.

ts
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";

// Bun 은 자동으로 .env.local 에서 DATABASE_URL 을 로드합니다.
// 자세한 내용은 https://bun.com/docs/runtime/environment-variables 를 참조하세요.
const sql = neon(process.env.DATABASE_URL!);

export const db = drizzle(sql);

데이터베이스를 실제로 확인하려면 index.ts 에 다음 라인을 추가하세요.

ts
import { db } from "./db";
import { sql } from "drizzle-orm";

const query = sql`select 'hello world' as text`;
const result = await db.execute(query);
console.log(result.rows);

그런 다음 Bun 으로 index.ts 를 실행하세요.

sh
bun run index.ts
txt
[
  {
    text: "hello world",
  }
]

Drizzle ORM 기본형을 사용하여 데이터베이스에 대한 스키마를 정의할 수 있습니다. schema.ts 파일을 생성하고 다음 코드를 추가하세요.

ts
import { pgTable, integer, serial, text, timestamp } from "drizzle-orm/pg-core";

export const authors = pgTable("authors", {
  id: serial("id").primaryKey(),
  title: text("name").notNull(),
  bio: text("bio"),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

그런 다음 drizzle-kit CLI 를 사용하여 초기 SQL 마이그레이션을 생성합니다.

sh
bunx drizzle-kit generate --dialect postgresql --schema ./schema.ts --out ./drizzle

이렇게 하면 .sql 마이그레이션 파일과 meta 디렉터리를 포함한 새 drizzle 디렉터리가 생성됩니다.

txt
drizzle
├── 0000_aspiring_post.sql
└── meta
    ├── 0000_snapshot.json
    └── _journal.json

간단한 migrate.ts 스크립트로 이 마이그레이션을 실행할 수 있습니다. 이 스크립트는 Neon 데이터베이스에 새 연결을 생성하고 drizzle 디렉터리의 모든 실행되지 않은 마이그레이션을 실행합니다.

ts
import { db } from "./db";
import { migrate } from "drizzle-orm/neon-http/migrator";

const main = async () => {
  try {
    await migrate(db, { migrationsFolder: "drizzle" });
    console.log("Migration completed");
  } catch (error) {
    console.error("Error during migration:", error);
    process.exit(1);
  }
};

main();

이 스크립트를 bun 으로 실행하여 마이그레이션을 실행할 수 있습니다.

sh
bun run migrate.ts
txt
Migration completed

이제 데이터베이스에 일부 데이터를 추가할 수 있습니다. 다음 내용을 포함하는 seed.ts 파일을 생성하세요.

ts
import { db } from "./db";
import * as schema from "./schema";

async function seed() {
  await db.insert(schema.authors).values([
    {
      title: "J.R.R. Tolkien",
      bio: "The creator of Middle-earth and author of The Lord of the Rings.",
    },
    {
      title: "George R.R. Martin",
      bio: "The author of the epic fantasy series A Song of Ice and Fire.",
    },
    {
      title: "J.K. Rowling",
      bio: "The creator of the Harry Potter series.",
    },
  ]);
}

async function main() {
  try {
    await seed();
    console.log("Seeding completed");
  } catch (error) {
    console.error("Error during seeding:", error);
    process.exit(1);
  }
};

main();

그런 다음 이 파일을 실행하세요.

sh
bun run seed.ts
txt
Seeding completed

이제 스키마와 샘플 데이터를 갖춘 데이터베이스가 있습니다. Drizzle 을 사용하여 쿼리할 수 있습니다. index.ts 의 내용을 다음으로 대체하세요.

ts
import * as schema from "./schema";
import { db } from "./db";

const result = await db.select().from(schema.authors);
console.log(result);

그런 다음 파일을 실행하세요. 삽입한 세 명의 저자가 표시되어야 합니다.

sh
bun run index.ts
txt
[
  {
    id: 1,
    title: "J.R.R. Tolkien",
    bio: "The creator of Middle-earth and author of The Lord of the Rings.",
    createdAt: 2024-05-11T10:28:46.029Z,
  }, {
    id: 2,
    title: "George R.R. Martin",
    bio: "The author of the epic fantasy series A Song of Ice and Fire.",
    createdAt: 2024-05-11T10:28:46.029Z,
  }, {
    id: 3,
    title: "J.K. Rowling",
    bio: "The creator of the Harry Potter series.",
    createdAt: 2024-05-11T10:28:46.029Z,
  }
]

이 예제는 Neon serverless driver 의 SQL-over-HTTP 기능을 사용했습니다. Neon 의 serverless driver 는 세션, 대화형 트랜잭션 및 node-postgres 호환성을 활성화하기 위해 ClientPool 생성자도 노출합니다. 완전한 개요는 Neon 의 문서 를 참조하세요.

Drizzle ORM 사용에 대한 자세한 문서는 Drizzle 웹사이트 를 참조하세요.

Bun by www.bunjs.com.cn 편집