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), Clickhouse) query builder for Node.js, featuring:
- transactions
- connection pooling
- streaming queries
- both a promise and callback API
- a thorough test suite
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
We have several examples on the website. Here is the first one to get you started:
const knex = require('knex')({
client: 'clickhouse',
connection: {
connection: "http://user:[email protected]:8123/dbname",
// connection: {
// "database": "dbname",
// "host": "127.0.0.1",
// "port": 8123,
// "user": "user name",
// "password": "password"
// }
},
});
try {
const insertedRows = await knex('candlestick')
.insert([
{
pair: "btc/usdt",
open: 50000,
close: 50010,
openTime: '2022-07-19 19:39:50',
closeTime: '2022-07-19 19:39:51'
},
]);
const selectedRows = await knex("candlestick")
.select("pair")
// notice: use value wrapper
.where("open", ">", knex.client.val("1", "Decimal32(8)"))
.limit(10);
// Finally, add a catch statement
} catch(e) {
console.error(e);
};
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
}
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();