LoginSignup
6
1

More than 3 years have passed since last update.

Bot開発(Node.js)のDBアクセスライブラリは knex がオススメ!

Posted at

Bot開発でNode.jsを使うことが多く、DBアクセスがある要件で pg などで素のクエリを書いていて辛いなーと感じている時に、 knex に出会ったので紹介します。

公式ドキュメント http://knexjs.org/
GitHub https://github.com/knex/knex

使い方

インストール

$ npm install --save knex pg

knex初期設定

$ knex init

すると、以下のファイルが自動生成されます。

knexfile.js
// Update with your config settings.

module.exports = {

  development: {
    client: 'postgresql',
    connection: {
      database: 'linebot-dev',
      user:     'zyyx-kubo',
      password: ''
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory:'./db/migrations',
      tableName: 'knex_migrations'
    }
  },

  staging: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory:'./db/migrations',
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      directory:'./db/migrations',
      tableName: 'knex_migrations'
    }
  }

};

マイグレーションファイルの作成

$ knex migrate:make create_user
Using environment: development
Created Migration: ./db/migrations/20190214205707_create_user.js

マイグレーション

実行

$ knex migrate:latest

ロールバック

$ knex migrate:rollback

シード

ファイル作成

$ knex seed:make test_users
Using environment: development
Created seed file: ./db/seeds/test_users.js

実行

$ knex seed:run

Herokuでの実行

$ heroku run knex migrate:latest --app app-name
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1