Sequelize は、Promise をベースとした Node.js の ORM ツールであり、Postgres、MySQL、SQLite、SQL Server など、さまざまなデータベースをサポートしています。本記事では、Sequelize を使用して OceanBase データベースの MySQL モードに接続する方法について説明します。
前提条件
- Node.js 14.0.0以降のバージョンがインストール済みであること。
- npmまたはyarnパッケージマネージャーがインストールされていること。
- OceanBaseデータベースがデプロイ済みで、MySQLテナントが作成されていること。
- ネットワーク接続が正常であることを確認してください。
手順
- Node.jsとnpmのバージョンを確認する
- 必要な依存関係をインストールする
- OceanBaseデータベースの接続情報を取得する
- プロジェクトを作成して設定する
- サンプルプログラムを実行する
ステップ1:Node.jsとnpmのバージョンを確認する
ターミナルを開き、以下のコマンドを実行してNode.jsとnpmのバージョンを確認します:
node -v
npm -v
ステップ2:必要な依存関係をインストールする
プロジェクトディレクトリを作成し、初期化します:
mkdir sequelize-oceanbase-demo cd sequelize-oceanbase-demo npm init -ySequelizeとMySQL2ドライバーをインストールします:
npm install sequelize mysql2 # TypeScriptを使用する場合 npm install -D typescript @types/node @types/sequelize # TypeScript設定を初期化する npx tsc --init
ステップ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:アカウントのパスワード
ステップ4:プロジェクトの作成と設定
プロジェクト構造の作成:
sequelize-oceanbase-demo/ ├── src/ │ ├── models/ │ │ └── index.js │ └── index.js ├── .env └── package.jsonデータベース接続の設定:
プロジェクトのルートディレクトリに
.envファイルを作成します:DB_HOST=your_host DB_PORT=2881 DB_USER=your_username DB_PASSWORD=your_password DB_NAME=your_databaseデータベース接続の作成:
src/models/index.jsファイルを作成します:require('dotenv').config(); const { Sequelize } = require('sequelize'); const sequelize = new Sequelize( process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, { host: process.env.DB_HOST, dialect: 'mysql', port: process.env.DB_PORT, logging: console.log, // SQLクエリログを表示 pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } } ); module.exports = sequelize;接続のテスト:
src/index.jsファイルを作成します:const sequelize = require('./models/index'); async function testConnection() { try { await sequelize.authenticate(); console.log('接続成功'); } catch (error) { console.error('接続失敗:', error); } } testConnection();
ステップ5:サンプルプログラムの実行
モデルの定義:
const { DataTypes } = require('sequelize'); const User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false }, email: { type: DataTypes.STRING, validate: { isEmail: true } } }, { tableName: 'users' });
全体の例
以下は、Sequelizeを使用してCRUD操作を実行する方法を示す完全な例です。
const { Sequelize, DataTypes } = require('sequelize');
// 1. 接続の作成
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'oceanbase-host',
port: 2881,
dialect: 'mysql'
});
// 2. モデルの定義
const User = sequelize.define('User', {
username: DataTypes.STRING,
email: DataTypes.STRING
});
// 3. モデルのデータベースへの同期
async function syncDatabase() {
try {
await sequelize.sync();
console.log('データベース同期に成功しました');
} catch (error) {
console.error('データベース同期に失敗しました:', error);
}
}
// 4. CRUD操作
async function crudOperations() {
// 作成
const user = await User.create({
username: 'testuser',
email: 'test@example.com'
});
// クエリ
const users = await User.findAll();
console.log(users);
// 更新
await User.update(
{ email: 'new@example.com' },
{ where: { id: 1 } }
);
// 削除
await User.destroy({
where: { id: 1 }
});
}
// 実行
syncDatabase().then(() => crudOperations());
// トランザクションを使用する例
async function createWithTransaction() {
const t = await sequelize.transaction();
try {
const user = await User.create({
username: 'transaction_user',
email: 'transaction@example.com'
}, { transaction: t });
await t.commit();
return user;
} catch (error) {
await t.rollback();
throw error;
}
}
syncDatabase().then(() => createWithTransaction());