Node.js 用 SQL クエリビルダー - クエリ、スキーマ、マイグレーション、トランザクション。
Knex.js をインストールし、データベース接続を設定します
# knex とデータベースドライバをインストール
npm install knex --save
# データベースドライバ(いずれかを選択)
npm install pg # PostgreSQL
npm install mysql2 # MySQL
npm install sqlite3 # SQLite
npm install tedious # MSSQLconst knex = require('knex')({
client: 'mysql2',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test'
},
pool: { min: 0, max: 7 }
});// 接続文字列
const knex = require('knex')({
client: 'pg',
connection: process.env.DATABASE_URL,
searchPath: ['knex', 'public']
});
// SQLite インメモリ
const knex = require('knex')({
client: 'sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true
});Select, insert, update, and delete operations
// 全件取得
knex('users').select('*')
// SELECT * FROM users
// 特定のカラムを取得
knex('users').select('id', 'name', 'email')
// SELECT id, name, email FROM users
// エイリアス付きで取得
knex('users').select('id', 'name as full_name')
// SELECT id, name as full_name FROM users
// 最初の結果
knex('users').first('*')
// SELECT * FROM users LIMIT 1// 単一行を挿入
knex('users').insert({ name: 'John', email: 'john@example.com' })
// 複数行を挿入
knex('users').insert([
{ name: 'John', email: 'john@example.com' },
{ name: 'Jane', email: 'jane@example.com' }
])
// returning 付きで挿入 (PostgreSQL)
knex('users')
.insert({ name: 'John', email: 'john@example.com' })
.returning('id')// 全行を更新
knex('users').update({ status: 'active' })
// 特定の行を更新
knex('users')
.where('id', 1)
.update({ name: 'John Updated' })
// returning 付きで更新
knex('users')
.where('id', 1)
.update({ name: 'John' })
.returning('*')// 全行を削除
knex('users').del()
// 特定の行を削除
knex('users').where('id', 1).del()
// returning 付きで削除
knex('users')
.where('id', 1)
.del()
.returning('*')様々な条件でデータをフィルタリング
// シンプルな where
knex('users').where('id', 1)
knex('users').where({ id: 1, status: 'active' })
// 演算子付き where
knex('users').where('age', '>', 18)
knex('users').where('created_at', '<=', '2024-01-01')
// 複数条件(AND)
knex('users')
.where('status', 'active')
.where('age', '>', 18)
// OR 条件
knex('users')
.where('status', 'active')
.orWhere('role', 'admin')// IN 条件
knex('users').whereIn('id', [1, 2, 3])
// NOT IN 条件
knex('users').whereNotIn('status', ['banned', 'deleted'])
// NULL 条件
knex('users').whereNull('deleted_at')
// NOT NULL 条件
knex('users').whereNotNull('email')
// BETWEEN 条件
knex('users').whereBetween('age', [18, 65])
// NOT BETWEEN 条件
knex('users').whereNotBetween('age', [0, 18])// 複雑な入れ子条件
knex('users')
.where('status', 'active')
.where(function() {
this.where('role', 'admin')
.orWhere('role', 'moderator')
})
// WHERE status = 'active' AND (role = 'admin' OR role = 'moderator')
// EXISTS 条件
knex('users')
.whereExists(function() {
this.select('*')
.from('orders')
.whereRaw('orders.user_id = users.id')
})
// 生の WHERE 条件
knex('users').whereRaw('age > ?', [18])複数テーブルのデータを結合
// INNER JOIN
knex('users')
.join('orders', 'users.id', '=', 'orders.user_id')
.select('users.name', 'orders.total')
// LEFT JOIN
knex('users')
.leftJoin('orders', 'users.id', 'orders.user_id')
.select('users.name', 'orders.total')
// RIGHT JOIN
knex('users')
.rightJoin('orders', 'users.id', 'orders.user_id')
// FULL OUTER JOIN
knex('users')
.fullOuterJoin('orders', 'users.id', 'orders.user_id')// 複数条件で結合
knex('users')
.join('orders', function() {
this.on('users.id', '=', 'orders.user_id')
.andOn('orders.status', '=', knex.raw('?', ['completed']))
})
// OR 条件で結合
knex('users')
.join('orders', function() {
this.on('users.id', '=', 'orders.user_id')
.orOn('users.email', '=', 'orders.email')
})
// クロス結合
knex('users').crossJoin('roles')集計関数と GROUP BY 操作
// カウント
knex('users').count('id as total')
// 重複除外カウント
knex('users').countDistinct('email')
// 合計
knex('orders').sum('total as revenue')
// 平均
knex('orders').avg('total as average_order')
// 最小値と最大値
knex('orders').min('total as min_order')
knex('orders').max('total as max_order')// GROUP BY
knex('orders')
.select('user_id')
.count('id as order_count')
.groupBy('user_id')
// 複数カラムで GROUP BY
knex('orders')
.select('user_id', 'status')
.sum('total as revenue')
.groupBy('user_id', 'status')
// HAVING 句
knex('orders')
.select('user_id')
.count('id as order_count')
.groupBy('user_id')
.having('order_count', '>', 5)
// 生の HAVING
knex('orders')
.select('user_id')
.sum('total as revenue')
.groupBy('user_id')
.havingRaw('SUM(total) > ?', [1000])クエリ結果をソートおよびページング
// 昇順で並び替え
knex('users').orderBy('name')
knex('users').orderBy('name', 'asc')
// 降順で並び替え
knex('users').orderBy('created_at', 'desc')
// 複数カラムで並び替え
knex('users')
.orderBy('status', 'asc')
.orderBy('created_at', 'desc')
// 配列で並び替え
knex('users').orderBy([
{ column: 'status', order: 'asc' },
{ column: 'name', order: 'desc' }
])
// 生の orderBy
knex('users').orderByRaw('age DESC NULLS LAST')// 制限
knex('users').limit(10)
// オフセット
knex('users').offset(20)
// ページング
knex('users')
.limit(10)
.offset(20)
// 重複除外
knex('users').distinct('email')
// 複数カラムで重複除外
knex('users').distinct('email', 'status')データベーステーブルを定義し作成します
// テーブル作成
knex.schema.createTable('users', function(table) {
table.increments('id').primary();
table.string('name', 100).notNullable();
table.string('email', 255).unique().notNullable();
table.integer('age');
table.boolean('is_active').defaultTo(true);
table.timestamps(true, true);
});
// テーブルが存在しない場合に作成
knex.schema.createTableIfNotExists('users', function(table) {
table.increments('id');
table.string('email').unique();
});// 共通のカラム型
table.increments('id') // 自動インクリメント ID
table.integer('votes') // 整数
table.bigInteger('big_votes') // 大きな整数
table.text('description') // テキスト
table.string('name', 255) // 長さ付き文字列
table.float('amount') // 浮動小数点数
table.decimal('price', 8, 2) // 小数点 (8,2)
table.boolean('is_admin') // 真偽値
table.date('birth_date') // 日付
table.datetime('created_at') // 日時
table.time('alarm_time') // 時間
table.timestamp('updated_at') // タイムスタンプ
table.json('metadata') // JSON
table.jsonb('data') // JSONB(PostgreSQL)
table.uuid('id') // UUID
table.enum('status', ['active', 'inactive']) // 列挙型// カラム修飾子
table.string('email')
.notNullable() // NULL不可
.unique() // ユニーク
.defaultTo('default') // デフォルト値
.unsigned() // 符号なし(数値用)
.index() // インデックスを追加
.comment('Email address') // コメントを追加
// 外部キー
table.integer('user_id')
.unsigned()
.notNullable()
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('CASCADE');
// タイムスタンプヘルパー
table.timestamps(true, true) // created_at, updated_at
table.timestamp('created_at').defaultTo(knex.fn.now())既存のテーブル構造を変更する
// カラムを追加
knex.schema.table('users', function(table) {
table.string('phone', 20);
});
// 複数カラムを追加
knex.schema.table('users', function(table) {
table.string('phone', 20);
table.string('address', 255);
table.integer('zip_code');
});
// カラムを変更
knex.schema.alterTable('users', function(table) {
table.string('email', 500).alter();
});
// カラム名を変更
knex.schema.table('users', function(table) {
table.renameColumn('name', 'full_name');
});// カラムを削除
knex.schema.table('users', function(table) {
table.dropColumn('phone');
});
// 複数カラムを削除
knex.schema.table('users', function(table) {
table.dropColumns('phone', 'address');
});
// テーブルを削除
knex.schema.dropTable('users');
// テーブルが存在すれば削除
knex.schema.dropTableIfExists('users');
// テーブル名を変更
knex.schema.renameTable('users', 'customers');// テーブルが存在するか確認
knex.schema.hasTable('users')
.then(exists => {
if (!exists) {
return knex.schema.createTable('users', table => {
table.increments('id');
});
}
});
// カラムが存在するか確認
knex.schema.hasColumn('users', 'email')
.then(exists => {
if (!exists) {
return knex.schema.table('users', table => {
table.string('email');
});
}
});データベースインデックスとリレーションシップを作成・管理する
// インデックスを作成
knex.schema.table('users', function(table) {
table.index('email');
});
// 名前付きインデックスを作成
knex.schema.table('users', function(table) {
table.index('email', 'idx_users_email');
});
// 複合インデックス
knex.schema.table('users', function(table) {
table.index(['status', 'created_at'], 'idx_status_created');
});
// ユニークインデックス
knex.schema.table('users', function(table) {
table.unique('email');
});
// インデックスを削除
knex.schema.table('users', function(table) {
table.dropIndex('email');
table.dropIndex([], 'idx_users_email'); // 名前で
});// 外部キーを追加
knex.schema.table('orders', function(table) {
table.foreign('user_id')
.references('id')
.inTable('users');
});
// アクション付き外部キー
knex.schema.table('orders', function(table) {
table.foreign('user_id')
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('RESTRICT');
});
// 名前付き外部キー
knex.schema.table('orders', function(table) {
table.foreign('user_id', 'fk_orders_user')
.references('users.id');
});
// 外部キーを削除
knex.schema.table('orders', function(table) {
table.dropForeign('user_id');
table.dropForeign([], 'fk_orders_user'); // 名前で
});複数のクエリを原子的に実行する
// 基本的なトランザクション
knex.transaction(async (trx) => {
await trx('users').insert({ name: 'John' });
await trx('orders').insert({ user_id: 1, total: 100 });
})
.then(() => console.log('Transaction committed'))
.catch((err) => console.error('Transaction failed:', err));
// 戻り値付きトランザクション
const userId = await knex.transaction(async (trx) => {
const [id] = await trx('users')
.insert({ name: 'John' })
.returning('id');
await trx('profiles')
.insert({ user_id: id, bio: 'Hello' });
return id;
});// 手動トランザクション制御
const trx = await knex.transaction();
try {
await trx('users').insert({ name: 'John' });
await trx('orders').insert({ user_id: 1, total: 100 });
await trx.commit();
} catch (err) {
await trx.rollback();
throw err;
}
// セーブポイント付きトランザクション
knex.transaction(async (trx) => {
await trx('users').insert({ name: 'John' });
const savepoint = await trx.savepoint();
try {
await trx('orders').insert({ user_id: 1, total: 100 });
await savepoint.release();
} catch (err) {
await savepoint.rollback();
}
});必要に応じてロウSQLを実行する
// シンプルなロウクエリ
knex.raw('SELECT * FROM users WHERE id = ?', [1])
// 名前付きバインディングのロウクエリ
knex.raw('SELECT * FROM users WHERE id = :userId', {
userId: 1
})
// SELECTでのロウ使用
knex('users')
.select(knex.raw('COUNT(*) as total'))
.where('status', 'active')
// WHEREでのロウ使用
knex('users')
.whereRaw('age > ?', [18])
.orWhereRaw('status = ?', ['admin'])// ロウ更新
knex('users')
.update({
updated_at: knex.raw('NOW()'),
views: knex.raw('views + 1')
})
.where('id', 1)
// ロウ挿入
knex('users').insert({
name: 'John',
created_at: knex.raw('CURRENT_TIMESTAMP')
})
// 列参照に knex.ref を使用
knex('users')
.where('created_at', '>', knex.ref('updated_at'))データベーススキーマのバージョン管理
# マイグレーション作成
npx knex migrate:make create_users_table
# マイグレーション実行
npx knex migrate:latest
# 最後のバッチをロールバック
npx knex migrate:rollback
# すべてのマイグレーションをロールバック
npx knex migrate:rollback --all
# マイグレーションステータス確認
npx knex migrate:status
# 特定のマイグレーション実行
npx knex migrate:up 001_create_users.js// Migration file structure
exports.up = function(knex) {
return knex.schema.createTable('users', function(table) {
table.increments('id').primary();
table.string('name', 100).notNullable();
table.string('email', 255).unique().notNullable();
table.timestamp('created_at').defaultTo(knex.fn.now());
});
};
exports.down = function(knex) {
return knex.schema.dropTable('users');
};// 複数操作を含むマイグレーション
exports.up = async function(knex) {
// users テーブル作成
await knex.schema.createTable('users', table => {
table.increments('id');
table.string('email').unique();
});
// orders テーブル作成
await knex.schema.createTable('orders', table => {
table.increments('id');
table.integer('user_id').unsigned();
table.foreign('user_id').references('users.id');
});
// 初期データをシード
await knex('users').insert([
{ email: 'admin@example.com' }
]);
};
exports.down = async function(knex) {
await knex.schema.dropTable('orders');
await knex.schema.dropTable('users');
};テストデータでデータベースを投入する
# Create seed file
npx knex seed:make 01_users
# Run all seeds
npx knex seed:run
# Run specific seed
npx knex seed:run --specific=01_users.js// 基本シードファイル
exports.seed = async function(knex) {
// 既存エントリを削除
await knex('users').del();
// シードデータを挿入
await knex('users').insert([
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Smith', email: 'jane@example.com' },
{ name: 'Bob Johnson', email: 'bob@example.com' }
]);
};// リレーション付きシード
exports.seed = async function(knex) {
// 正しい順序でテーブルをクリア
await knex('orders').del();
await knex('users').del();
// ユーザーを挿入し ID を取得
const [userId1] = await knex('users')
.insert({ name: 'John', email: 'john@example.com' })
.returning('id');
const [userId2] = await knex('users')
.insert({ name: 'Jane', email: 'jane@example.com' })
.returning('id');
// 関連する注文を挿入
await knex('orders').insert([
{ user_id: userId1, total: 100.50 },
{ user_id: userId1, total: 75.25 },
{ user_id: userId2, total: 200.00 }
]);
};TypeScript による型安全クエリ
// Define table types
interface User {
id: number;
name: string;
email: string;
created_at: string;
updated_at: string;
}
interface UserInsert {
name: string;
email: string;
}
interface UserUpdate {
name?: string;
email?: string;
updated_at?: string;
}// Augment Knex types
import { Knex } from 'knex';
declare module 'knex/types/tables' {
interface Tables {
users: User;
users_composite: Knex.CompositeTableType<
User,
UserInsert,
UserUpdate
>;
}
}
// Type-safe queries
const users = await knex('users').select('*');
// users is typed as User[]
const newUser = await knex('users_composite')
.insert({ name: 'John', email: 'john@example.com' })
.returning('*');// 汎用クエリ型
const getUserById = async (id: number): Promise<User | undefined> => {
return knex<User>('users')
.where({ id })
.first();
};
const createUser = async (data: UserInsert): Promise<User> => {
const [user] = await knex<User>('users')
.insert(data)
.returning('*');
return user;
};
const updateUser = async (
id: number,
data: UserUpdate
): Promise<User | undefined> => {
const [user] = await knex<User>('users')
.where({ id })
.update(data)
.returning('*');
return user;
};高度な Knex.js 機能
// Upsert(挿入または更新)
knex('users')
.insert({ id: 1, name: 'John', email: 'john@example.com' })
.onConflict('id')
.merge()
// 特定カラムでの Upsert
knex('users')
.insert({ id: 1, name: 'John', email: 'john@example.com' })
.onConflict('email')
.merge(['name'])
// Insert ignore(MySQL)
knex('users')
.insert({ email: 'john@example.com' })
.onConflict('email')
.ignore()// WITH(共通テーブル式)
knex.with('active_users', (qb) => {
qb.select('*').from('users').where('status', 'active');
})
.select('*')
.from('active_users')
.where('age', '>', 18);
// 再帰 CTE
knex.withRecursive('tree', (qb) => {
qb.select('*').from('categories').where('parent_id', null)
.union((qb2) => {
qb2.select('c.*')
.from('categories as c')
.join('tree as t', 'c.parent_id', 't.id');
});
})
.select('*').from('tree');// サブクエリ
knex('users')
.whereIn('id', function() {
this.select('user_id').from('orders').where('total', '>', 100);
})
// SELECT 内のサブクエリ
knex('users')
.select('name')
.select(
knex('orders')
.count('*')
.where('orders.user_id', knex.raw('??', ['users.id']))
.as('order_count')
)
// FROM 内のサブクエリ
knex
.select('*')
.from(
knex('users')
.where('status', 'active')
.as('active_users')
)// ウィンドウ関数
knex('orders')
.select('*')
.select(
knex.raw('ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) as row_num')
)
// JSON 操作(PostgreSQL)
knex('users')
.select('name')
.select(knex.raw("metadata->>'age' as age"))
.where(knex.raw("metadata->>'city'"), 'New York')
// 配列操作(PostgreSQL)
knex('users')
.whereRaw('? = ANY(tags)', ['javascript'])データベース接続とプールを管理する
// 接続プールを設定
const knex = require('knex')({
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'user',
password: 'password',
database: 'myapp'
},
pool: {
min: 2,
max: 10,
acquireTimeoutMillis: 30000,
idleTimeoutMillis: 30000
}
});
// 接続プールを破棄
await knex.destroy();
// 再初期化
knex.initialize();// 接続 afterCreate フック
const knex = require('knex')({
client: 'pg',
connection: { /* ... */ },
pool: {
afterCreate: function(conn, done) {
conn.query('SET timezone="UTC";', function(err) {
done(err, conn);
});
}
}
});
// 動的接続
const knex = require('knex')({
client: 'mysql',
connection: async () => {
const token = await getAuthToken();
return {
host: 'localhost',
user: 'user',
password: token,
database: 'myapp'
};
}
});// クエリのデバッグ
const knex = require('knex')({
client: 'pg',
connection: { /* ... */ },
debug: true // すべてのクエリをログ出力
});
// 特定クエリのデバッグ
knex('users')
.select('*')
.debug()
.then(rows => console.log(rows));
// 実行せずに SQL を取得
const sql = knex('users')
.where('id', 1)
.toSQL();
console.log(sql.sql); // SQL 文
console.log(sql.bindings); // パラメータ