Drizzle ORMは軽量で型安全なTypeScript ORMです。本記事では、Drizzle ORMを使用してOceanBaseデータベースのMySQLモードに接続する方法を紹介します。
前提条件
- Node.js 16.0.0以降のバージョンがインストール済みであること。
- npmまたはyarnパッケージマネージャーがインストールされていること。
- OceanBaseデータベースがデプロイ済みで、MySQLテナントが作成されていること。
手順
- Node.jsとnpmのバージョンを確認する
- 必要な依存関係をインストールする
- OceanBaseデータベース接続情報を取得する
- プロジェクトを作成して設定する
- サンプルプログラムを実行する
ステップ1:Node.jsとnpmのバージョンを確認する
ターミナルを開き、以下のコマンドを実行してNode.jsとnpmのバージョンを確認します:
node -v
npm -v
ステップ2:必要な依存関係をインストールする
mkdir drizzle-oceanbase-demo
cd drizzle-oceanbase-demo
npm init -y
npm install drizzle-orm mysql2
npm install -D typescript @types/node ts-node
npx tsc --init
ステップ2:データベース接続を設定する
プロジェクトのルートディレクトリに.envファイルを作成し、データベース接続情報を入力します:
DB_HOST=your_host
DB_PORT=2881
DB_USER=your_username
DB_PASSWORD=your_password
DB_NAME=your_database
ステップ3:OceanBaseデータベース接続情報を取得する
OceanBaseデータベースのデプロイ担当者または管理者から、該当するデータベース接続情報を取得します。
mysql -h$host -P$port -u$user_name -p$password -D$database_name
パラメータ説明:
$host:OceanBaseデータベースへの接続IPアドレスを提供する$port:OceanBaseデータベースへの接続ポートを提供する$database_name:アクセス対象のデータベース名$user_name:テナントの接続アカウントを提供する$password:アカウントのパスワードを提供する
ステップ3:データテーブルモデルを定義する
src/db/schema.tsを作成します:
import { mysqlTable, int, varchar, timestamp, index } from 'drizzle-orm/mysql-core';
export const users = mysqlTable('users', {
id: int('id').primaryKey().autoincrement(),
username: varchar('username', { length: 255 }).notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
passwordHash: varchar('password_hash', { length: 255 }).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().onUpdateNow().notNull(),
}, (table) => ({
// emailフィールドのインデックスを追加する
emailIdx: index('email_idx').on(table.email),
}));
OceanBaseデータベースでテーブルを作成します:
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL
);
ステップ4:データベース接続の作成
src/db/index.ts を作成します:
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
import * as schema from './schema';
import * as dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const poolConnection = mysql.createPool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || '2881'),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
timezone: '+08:00',
// Add these options for better compatibility
multipleStatements: true,
supportBigNumbers: true,
bigNumberStrings: true
});
console.log('Connecting to database at:', {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
database: process.env.DB_NAME
});
export const db = drizzle(poolConnection, {
schema,
mode: 'default'
});
ステップ5:CRUD操作の例
src/index.ts を作成します:
import { db } from './db';
import { users } from './db/schema';
import { eq } from 'drizzle-orm';
async function main() {
try {
// Test the connection first
await db.select().from(users).limit(1);
console.log('Successfully connected to the database');
// Create user
const insertResult = await db.insert(users).values({
username: 'testuser',
email: 'test@example.com',
passwordHash: 'hashed_password',
});
console.log('Insert result:', insertResult);
// Get the inserted user
const [newUser] = await db.select().from(users).where(eq(users.email, 'test@example.com'));
console.log('Created user:', newUser);
// Query user
const [user] = await db.select().from(users).where(eq(users.id, newUser.id));
console.log('Retrieved user:', user);
// Update user
const updateResult = await db.update(users)
.set({ email: 'new.email@example.com' })
.where(eq(users.id, newUser.id));
console.log('Update result:', updateResult);
// Get the updated user
const [updatedUser] = await db.select().from(users).where(eq(users.id, newUser.id));
console.log('Updated user:', updatedUser);
// Delete user
const deleteResult = await db.delete(users)
.where(eq(users.id, newUser.id));
console.log('Delete result:', deleteResult);
// Verify deletion
const [deletedUser] = await db.select().from(users).where(eq(users.id, newUser.id));
console.log('User after deletion:', deletedUser || 'User not found');
} catch (error) {
console.error('Database error:', error);
}
}
main().catch(console.error);
実行例
npx ts-node src/index.ts