What is knex?
Knex.js is a SQL query builder for JavaScript, which works with multiple database systems like PostgreSQL, MySQL, SQLite3, and Oracle. It allows for building and executing SQL queries in a readable and programmatic way, handling connections and transactions, and seeding and migrating databases for development purposes.
What are knex's main functionalities?
Query Building
Builds a SQL query to select all columns from the 'users' table where the 'id' is 1.
knex.select('*').from('users').where('id', 1)
Schema Building
Creates a new table called 'users' with an auto-incrementing 'id' column, a 'name' column of string type, and timestamp columns for 'created_at' and 'updated_at'.
knex.schema.createTable('users', function(table) { table.increments('id'); table.string('name'); table.timestamps(); })
Transaction Support
Performs a transaction to insert multiple records into the 'books' table. If any part of the transaction fails, all changes are rolled back.
knex.transaction(function(trx) { const books = [{title: 'Canterbury Tales'}, {title: 'Macbeth'}]; return trx.insert(books).into('books'); })
Raw Queries
Executes a raw SQL query, selecting all columns from the 'users' table where the 'id' is 1, with parameter binding.
knex.raw('SELECT * FROM users WHERE id = ?', [1])
Seeding
Defines a seed file that first clears the 'users' table and then inserts new records into it.
exports.seed = function(knex) { return knex('users').del().then(function() { return knex('users').insert([{name: 'Alice'}, {name: 'Bob'}]); }); }
Migrations
Defines a migration file with an 'up' method to create a new 'users' table and a 'down' method to drop the 'users' table.
exports.up = function(knex) { return knex.schema.createTable('users', function(table) { table.increments(); table.string('name'); table.timestamps(); }); }; exports.down = function(knex) { return knex.schema.dropTable('users'); };
Other packages similar to knex
sequelize
Sequelize is an ORM (Object-Relational Mapping) library for Node.js. It provides a higher-level abstraction for database interactions and supports multiple dialects. Unlike Knex, which is primarily a query builder, Sequelize allows for defining models and relationships directly in JavaScript.
typeorm
TypeORM is an ORM for TypeScript and JavaScript (ES7, ES6, ES5). It supports the Data Mapper and Active Record patterns and works with SQL databases. It provides more advanced ORM features compared to Knex, such as automatic migration generation and support for decorators.
bookshelf
Bookshelf.js is a JavaScript ORM for Node.js, built on the Knex SQL query builder. It features a simple and intuitive API and supports relations, eager and lazy loading, model events, and plugins. It's more ORM-focused than Knex but uses Knex under the hood for query building.
A SQL query builder that is flexible, portable, and fun to use!
A batteries-included, multi-dialect (MSSQL, MySQL, PostgreSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for
Node.js, featuring:
Node.js versions 10+ 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 {
await knex.schema
.createTable('users', table => {
table.increments('id');
table.string('user_name');
})
.createTable('accounts', table => {
table.increments('id');
table.string('account_name');
table
.integer('user_id')
.unsigned()
.references('users.id');
})
const insertedRows = await knex('users').insert({ user_name: 'Tim' })
await knex('accounts').insert({ account_name: 'knex', user_id: insertedRows[0] })
const selectedRows = await knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account')
const enrichedRows = selectedRows.map(row => ({ ...row, active: true }))
} 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) {
}
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:
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();