Skip to content

Neon は、コンピューティングとストレージを分離し、オートスケーリング、ブランチング、無制限ストレージなどの機能を提供する、完全に管理されたサーバーレス Postgres です。Neon は、@neondatabase/serverless ドライバーを直接使用するか、Drizzle のような ORM を介して Bun から直接使用できます。

Drizzle ORM は、SQL 風の「クエリビルダー」API と ORM 風の Queries API の両方をサポートしています。プロジェクトディレクトリを作成し、bun init を使用してディレクトリを初期化し、Drizzle と Neon serverless ドライバー をインストールして始めましょう。

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 サーバーレスドライバーを使用して Neon データベースに接続し、Drizzle データベースインスタンスでラップします。

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

// Bun は自動的に DATABASE_URL を .env.local から読み込みます
// 詳細については 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);

次に index.ts を Bun で実行します。

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

これにより、新しい drizzle ディレクトリが作成され、.sql マイグレーションファイルと meta ディレクトリが含まれます。

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

次にファイルを実行します。挿入した 3 人の著者が表示されます。

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 サーバーレスドライバーの SQL-over-HTTP 機能を使用しました。Neon のサーバーレスドライバーは、セッション、インタラクティブなトランザクション、node-postgres 互換性を有効にする Client および Pool コンストラクターも公開しています。完全な概要については、Neon のドキュメント を参照してください。

Drizzle ORM の使用に関する詳細なドキュメントについては、Drizzle ウェブサイト を参照してください。

Bun by www.bunjs.com.cn 編集