knex vs sequelize vs pg-promise vs bookshelf
Node.js ORMライブラリ
knexsequelizepg-promisebookshelf類似パッケージ:
Node.js ORMライブラリ

Node.js ORM(Object-Relational Mapping)ライブラリは、データベースとアプリケーション間のデータのやり取りを簡素化するツールです。これらのライブラリは、データベースのテーブルをJavaScriptオブジェクトにマッピングし、SQLクエリをプログラム的に生成する機能を提供します。これにより、開発者はSQLを直接書くことなく、データベース操作を行うことができ、コードの可読性と保守性が向上します。Sequelizeは、Promiseベースのフル機能ORMで、複数のデータベース(PostgreSQL、MySQL、SQLiteなど)をサポートし、スキーマ定義、マイグレーション、バリデーションなどの機能を提供します。Knexは、SQLビルダーであり、ORMではありませんが、クエリビルディング、マイグレーション、トランザクション管理を提供し、柔軟性とパフォーマンスに優れています。Bookshelfは、Knexの上に構築されたORMで、リレーショナルデータベースのためのシンプルで直感的なAPIを提供し、関連性のあるデータの扱いを容易にします。pg-promiseは、PostgreSQL専用のライブラリで、プロミスベースのインターフェースを提供し、クエリの実行、トランザクション管理、カスタム型のサポートなど、高度な機能を備えています。

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
knex2,661,00820,169874 kB7022年前MIT
sequelize2,147,69030,3112.91 MB1,0039ヶ月前MIT
pg-promise561,8213,547417 kB12ヶ月前MIT
bookshelf81,0676,365-2376年前MIT
機能比較: knex vs sequelize vs pg-promise vs bookshelf

データベースサポート

  • knex:

    Knexも複数のデータベース(PostgreSQL、MySQL、SQLiteなど)をサポートしており、データベース間の移植性が高いです。

  • sequelize:

    Sequelizeは、PostgreSQL、MySQL、SQLite、MariaDBなど、複数のリレーショナルデータベースをサポートしています。

  • pg-promise:

    pg-promiseは、PostgreSQL専用のライブラリで、PostgreSQLの機能をフルに活用できます。

  • bookshelf:

    Bookshelfは、Knexをベースにしているため、Knexがサポートするすべてのデータベースをサポートしています。

クエリビルディング

  • knex:

    Knexは、強力なクエリビルダーを提供し、複雑なSQLクエリを簡単に構築できます。

  • sequelize:

    Sequelizeは、ORM機能を提供しながら、プログラム的にクエリを構築することもできます。

  • pg-promise:

    pg-promiseは、クエリを文字列として直接実行することができ、動的なクエリビルディングもサポートしています。

  • bookshelf:

    Bookshelfは、Knexのクエリビルダーを利用しており、リレーションシップを考慮したクエリを簡単に作成できます。

トランザクション管理

  • knex:

    Knexもトランザクション管理機能を提供しており、トランザクションを簡単に開始、コミット、ロールバックできます。

  • sequelize:

    Sequelizeは、トランザクション管理をサポートしており、複数の操作を一つのトランザクションとして実行できます。

  • pg-promise:

    pg-promiseは、高度なトランザクション管理機能を提供しており、ネストされたトランザクションや、トランザクション内でのクエリの自動ロールバックなどが可能です。

  • bookshelf:

    Bookshelfは、Knexのトランザクション機能を利用しており、トランザクションを簡単に扱うことができます。

リレーションシップのサポート

  • knex:

    Knexはリレーションシップを直接サポートしていませんが、クエリビルダーを使用して手動でリレーションシップを扱うことができます。

  • sequelize:

    Sequelizeは、1対1、1対多、多対多など、複雑なリレーションシップをサポートしています。

  • pg-promise:

    pg-promiseはリレーションシップを直接サポートしていませんが、クエリを手動で作成してリレーショナルデータを扱うことができます。

  • bookshelf:

    Bookshelfは、リレーションシップの定義が簡単で、リレーショナルデータを扱うのに適しています。

Ease of Use: Code Examples

  • knex:

    Knexを使用した簡単なクエリビルディングの例

    const knex = require('knex')({ client: 'pg', connection: { host: 'localhost', user: 'username', password: 'password', database: 'mydb' } });
    
    (async () => {
      const users = await knex('users').select('*'); // データの取得
      console.log(users);
    })();
    
  • sequelize:

    Sequelizeを使用した簡単なデータベース操作の例

    const { Sequelize, DataTypes } = require('sequelize');
    const sequelize = new Sequelize('database', 'username', 'password', { dialect: 'postgres' });
    
    const User = sequelize.define('User', { name: DataTypes.STRING, email: DataTypes.STRING });
    
    (async () => {
      await sequelize.sync(); // テーブルの作成
      const user = await User.create({ name: 'Alice', email: 'alice@example.com' }); // データの挿入
      console.log(user.toJSON());
    })();
    
  • pg-promise:

    pg-promiseを使用したPostgreSQLへのクエリ例

    const pgp = require('pg-promise')();
    const db = pgp('postgres://username:password@localhost:5432/mydb');
    
    (async () => {
      const users = await db.any('SELECT * FROM users'); // データの取得
      console.log(users);
    })();
    
  • bookshelf:

    Bookshelfを使用したリレーショナルデータの操作例

    const knex = require('knex')({ client: 'pg', connection: { host: 'localhost', user: 'username', password: 'password', database: 'mydb' } });
    const bookshelf = require('bookshelf')(knex);
    
    const User = bookshelf.model('User', { tableName: 'users' });
    const Post = bookshelf.model('Post', { tableName: 'posts', user_id: 'user_id' });
    
    User.hasMany(Post); // 1対多のリレーションシップ
    
    (async () => {
      const user = await User.where({ id: 1 }).fetch({ withRelated: ['posts'] }); // リレーショナルデータの取得
      console.log(user.toJSON());
    })();
    
選び方: knex vs sequelize vs pg-promise vs bookshelf
  • knex:

    Knexは、ORMではなくSQLビルダーですが、柔軟なクエリビルディングとマイグレーション機能が必要な場合に選択します。特に、複雑なクエリをプログラム的に構築したり、データベースの抽象化を最小限に抑えたい場合に適しています。

  • sequelize:

    Sequelizeを選択するのは、フル機能のORMが必要で、複数のデータベースをサポートし、スキーマ定義やマイグレーションなどの高度な機能を利用したい場合です。特に、リレーショナルデータベースとの統合が必要な大規模なアプリケーションに適しています。

  • pg-promise:

    pg-promiseは、PostgreSQL専用のライブラリで、高度なクエリ機能やトランザクション管理が必要な場合に選択します。特に、PostgreSQLの特性を活かした開発や、カスタムクエリを多く使用するアプリケーションに適しています。

  • bookshelf:

    Bookshelfは、Knexの上に構築されたORMで、シンプルなAPIとリレーショナルデータの扱いやすさを提供します。リレーションシップを簡単に定義できるため、中小規模のプロジェクトや、シンプルなORM機能が必要な場合に適しています。

knex のREADME

knex.js

npm version npm downloads Coverage Status Dependencies Status Gitter chat

A SQL query builder that is flexible, portable, and fun to use!

A batteries-included, multi-dialect (PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node.js, featuring:

Node.js versions 12+ are supported.

You can report bugs and discuss features on the GitHub issues page or send tweets to @kibertoad.

For support and questions, join our Gitter channel.

For knex-based Object Relational Mapper, see:

To see the SQL that Knex will generate for a given query, you can use Knex Query Lab

Examples

We have several examples on the website. Here is the first one to get you started:

const knex = require('knex')({
  client: 'sqlite3',
  connection: {
    filename: './data.db',
  },
});

try {
  // Create a table
  await knex.schema
    .createTable('users', (table) => {
      table.increments('id');
      table.string('user_name');
    })
    // ...and another
    .createTable('accounts', (table) => {
      table.increments('id');
      table.string('account_name');
      table.integer('user_id').unsigned().references('users.id');
    });

  // Then query the table...
  const insertedRows = await knex('users').insert({ user_name: 'Tim' });

  // ...and using the insert id, insert into the other table.
  await knex('accounts').insert({
    account_name: 'knex',
    user_id: insertedRows[0],
  });

  // Query both of the rows.
  const selectedRows = await knex('users')
    .join('accounts', 'users.id', 'accounts.user_id')
    .select('users.user_name as user', 'accounts.account_name as account');

  // map over the results
  const enrichedRows = selectedRows.map((row) => ({ ...row, active: true }));

  // Finally, add a catch statement
} catch (e) {
  console.error(e);
}

TypeScript example

import { Knex, knex } from 'knex';

interface User {
  id: number;
  age: number;
  name: string;
  active: boolean;
  departmentId: number;
}

const config: Knex.Config = {
  client: 'sqlite3',
  connection: {
    filename: './data.db',
  },
};

const knexInstance = knex(config);

try {
  const users = await knex<User>('users').select('id', 'age');
} catch (err) {
  // error handling
}

Usage as ESM module

If you are launching your Node application with --experimental-modules, knex.mjs should be picked up automatically and named ESM import should work out-of-the-box. Otherwise, if you want to use named imports, you'll have to import knex like this:

import { knex } from 'knex/knex.mjs';

You can also just do the default import:

import knex from 'knex';

If you are not using TypeScript and would like the IntelliSense of your IDE to work correctly, it is recommended to set the type explicitly:

/**
 * @type {Knex}
 */
const database = knex({
  client: 'mysql',
  connection: {
    host: '127.0.0.1',
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test',
  },
});
database.migrate.latest();