knex.js
![Coverage Status](https://camo.githubusercontent.com/31a3305cd4b08ab656e04df0ca9ce2b70d07021a1ed388b19245567e51772ea9/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f7467726965737365722f6b6e65782f62616467652e7376673f6272616e63683d6d6173746572)
A SQL query builder that is flexible, portable, and fun to use!
A batteries-included, multi-dialect (MSSQL, MySQL, PostgreSQL, SQLite3, WebSQL, Oracle) query builder for Node.js and the Browser, featuring:
- transactions
- connection pooling
- streaming queries
- both a promise and callback API
- a thorough test suite
- the ability to run in the Browser
Read the full documentation to get started!
For support and questions, join the #bookshelf channel on freenode IRC
For an Object Relational Mapper, see: http://bookshelfjs.org
To see the SQL that Knex will generate for a given query, see: Knex Query Lab
Examples
We have several examples on the website. Here is the first one to get you started:
var knex = require('knex')({
dialect: 'sqlite3',
connection: {
filename: './data.db'
}
});
// Create a table
knex.schema.createTable('users', function(table) {
table.increments('id');
table.string('user_name');
})
// ...and another
.createTable('accounts', function(table) {
table.increments('id');
table.string('account_name');
table.integer('user_id').unsigned().references('users.id');
})
// Then query the table...
.then(function() {
return knex.insert({user_name: 'Tim'}).into('users');
})
// ...and using the insert id, insert into the other table.
.then(function(rows) {
return knex.table('accounts').insert({account_name: 'knex', user_id: rows[0]});
})
// Query both of the rows.
.then(function() {
return knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account');
})
// .map over the results
.map(function(row) {
console.log(row);
})
// Finally, add a .catch handler for the promise chain
.catch(function(e) {
console.error(e);
});