knex.js

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and...

README

npm version npm downloads
undefined Coverage Status Dependencies Status Gitter chat Language Grade: JavaScript

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:

- both a promise and callback API

Node.js versions 12+ are supported.

Take a look at the full documentation to get started!
Browse the list of plugins and tools built for knex
Check out our recipes wiki to search for solutions to some specific problems
In case of upgrading from an older version, see migration guide

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:

- https://github.com/Vincit/objection.js
- https://github.com/mikro-orm/mikro-orm
- https://bookshelfjs.org

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:

  1. ``` js
  2. const knex = require('knex')({
  3.   client: 'sqlite3',
  4.   connection: {
  5.     filename: './data.db',
  6.   },
  7. });

  8. try {

  9.   // Create a table
  10.   await knex.schema
  11.     .createTable('users', table => {
  12.       table.increments('id');
  13.       table.string('user_name');
  14.     })
  15.     // ...and another
  16.     .createTable('accounts', table => {
  17.       table.increments('id');
  18.       table.string('account_name');
  19.       table
  20.         .integer('user_id')
  21.         .unsigned()
  22.         .references('users.id');
  23.     })

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

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

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

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

  34.   // Finally, add a catch statement
  35. } catch(e) {
  36.   console.error(e);
  37. };
  38. ```

TypeScript example

  1. ```ts
  2. import { Knex, knex } from 'knex'

  3. interface User {
  4.   id: number;
  5.   age: number;
  6.   name: string;
  7.   active: boolean;
  8.   departmentId: number;
  9. }

  10. const config: Knex.Config = {
  11.   client: 'sqlite3',
  12.   connection: {
  13.     filename: './data.db',
  14.   },
  15. };

  16. const knexInstance = knex(config);

  17. try {
  18.   const users = await knex<User>('users').select('id', 'age');
  19. } catch (err) {
  20.   // error handling
  21. }
  22. ```

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:
  1. ``` js
  2. import { knex } from 'knex/knex.mjs'
  3. ```

You can also just do the default import:
  1. ``` js
  2. import knex from 'knex'
  3. ```

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:
  1. ``` js
  2. /**
  3. * @type {Knex}
  4. */
  5. const database = knex({
  6.     client: 'mysql',
  7.     connection: {
  8.       host : '127.0.0.1',
  9.       user : 'your_database_user',
  10.       password : 'your_database_password',
  11.       database : 'myapp_test'
  12.     }
  13.   });
  14. database.migrate.latest();
  15. ```