knex
A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.
Top Related Projects
Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js
An SQL-friendly ORM for Node.js
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.
Quick Overview
Knex.js is a flexible SQL query builder for Node.js and browsers. It supports multiple database systems including PostgreSQL, MySQL, SQLite3, and Oracle. Knex.js provides a unified API for database operations, making it easier to work with different databases using a consistent syntax.
Pros
- Supports multiple database systems with a unified API
- Provides a powerful and intuitive query builder
- Offers migration and seeding tools for database schema management
- Includes transaction support and connection pooling
Cons
- Learning curve for developers new to query builders
- Performance overhead compared to raw SQL queries
- Limited support for advanced database-specific features
- Occasional breaking changes between major versions
Code Examples
- Basic SELECT query:
const users = await knex('users')
.select('id', 'name', 'email')
.where('active', true)
.orderBy('name');
- INSERT with returning clause:
const [newUser] = await knex('users')
.insert({ name: 'John Doe', email: 'john@example.com' })
.returning(['id', 'name']);
- Transaction example:
await knex.transaction(async (trx) => {
await trx('accounts').decrement('balance', 100);
await trx('transactions').insert({ amount: 100, type: 'withdrawal' });
});
Getting Started
- Install Knex.js and the database driver:
npm install knex
npm install pg # for PostgreSQL
- Create a database connection:
const knex = require('knex')({
client: 'pg',
connection: {
host: 'localhost',
user: 'username',
password: 'password',
database: 'myapp_db'
}
});
- Use Knex.js in your application:
async function getUsers() {
const users = await knex('users').select('*');
console.log(users);
}
getUsers();
Competitor Comparisons
Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
Pros of Sequelize
- More robust ORM features, including model definitions and associations
- Built-in data validation and type checking
- Supports multiple dialects (MySQL, PostgreSQL, SQLite, etc.) with minimal configuration changes
Cons of Sequelize
- Steeper learning curve due to more complex API and concepts
- Can be slower for simple queries compared to raw SQL or query builders
- Potential for overuse of ORM features, leading to less efficient database interactions
Code Comparison
Sequelize model definition:
const User = sequelize.define('User', {
username: DataTypes.STRING,
email: DataTypes.STRING
});
Knex schema definition:
knex.schema.createTable('users', table => {
table.string('username');
table.string('email');
});
Sequelize offers a more declarative approach to defining models, while Knex provides a lower-level API for schema creation. Sequelize's ORM features allow for easier data manipulation and querying, but Knex's query builder offers more flexibility and control over SQL generation.
Both libraries have their strengths, with Sequelize being better suited for complex applications with intricate data relationships, and Knex excelling in scenarios where raw SQL-like performance and fine-grained control are required.
ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
Pros of TypeORM
- Object-Relational Mapping (ORM) support, allowing developers to work with databases using TypeScript classes
- Built-in support for migrations and schema synchronization
- Extensive support for TypeScript decorators, enhancing code readability and maintainability
Cons of TypeORM
- Steeper learning curve due to its more complex architecture and features
- Potential performance overhead in certain scenarios compared to raw SQL queries
- Less flexibility for complex custom queries compared to Knex's query builder
Code Comparison
TypeORM entity definition:
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
}
Knex table creation:
knex.schema.createTable('users', table => {
table.increments('id');
table.string('name');
});
TypeORM offers a more declarative approach with decorators, while Knex provides a more imperative style for database operations. TypeORM is better suited for projects heavily relying on TypeScript and object-oriented paradigms, whereas Knex offers more flexibility and control over raw SQL queries. The choice between the two depends on project requirements, team expertise, and performance considerations.
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
Pros of Prisma
- Type-safe database access with auto-generated TypeScript types
- Intuitive and powerful query API with automatic joins and relations
- Built-in migration system for easy schema management
Cons of Prisma
- Steeper learning curve for developers familiar with raw SQL or query builders
- Less flexibility for complex custom queries compared to raw SQL
- Requires a schema file, which can be an additional step in setup
Code Comparison
Prisma query:
const users = await prisma.user.findMany({
where: { age: { gte: 18 } },
include: { posts: true }
})
Knex query:
const users = await knex('users')
.where('age', '>=', 18)
.select('*')
.withGraphFetched('posts')
Key Differences
- Prisma offers type safety and auto-completion, while Knex provides a more SQL-like syntax
- Prisma handles relations more seamlessly, whereas Knex requires explicit join operations
- Prisma generates a client based on your schema, while Knex is more flexible but requires manual setup
Both Prisma and Knex are powerful tools for database interactions, with Prisma focusing on type safety and ease of use, and Knex offering more flexibility and a closer-to-SQL experience. The choice between them often depends on project requirements and developer preferences.
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js
Pros of Bookshelf
- Higher-level ORM with model relationships and eager loading
- Built-in validation and serialization features
- Supports plugins for extended functionality
Cons of Bookshelf
- Steeper learning curve due to more complex API
- Less flexibility for raw SQL queries
- Smaller community and fewer resources compared to Knex
Code Comparison
Knex query:
knex('users')
.where('id', 1)
.update({ name: 'John Doe' });
Equivalent Bookshelf operation:
User.forge({ id: 1 })
.save({ name: 'John Doe' }, { patch: true });
Key Differences
Knex is a query builder that provides a flexible, low-level interface for database operations. It offers fine-grained control over SQL queries and supports multiple database systems.
Bookshelf is an ORM built on top of Knex, providing a higher-level abstraction for working with database models. It offers features like relationships, eager loading, and model validation, making it suitable for complex data structures and applications requiring a more structured approach to data management.
While Knex is more lightweight and versatile, Bookshelf provides a more robust set of tools for handling relational data in an object-oriented manner. The choice between the two depends on the project's complexity and the developer's preference for low-level control versus high-level abstractions.
An SQL-friendly ORM for Node.js
Pros of Objection.js
- Provides a full-featured ORM layer on top of Knex
- Supports advanced features like eager loading, graph inserts, and JSON schema validation
- Offers a more object-oriented approach to database interactions
Cons of Objection.js
- Steeper learning curve due to additional abstractions
- May introduce performance overhead for simple queries
- Less flexibility for raw SQL operations compared to Knex
Code Comparison
Objection.js:
const person = await Person.query()
.findById(1)
.withGraphFetched('pets');
Knex:
const person = await knex('persons')
.where('id', 1)
.first();
const pets = await knex('pets').where('owner_id', person.id);
Summary
Objection.js builds upon Knex, offering a more robust ORM experience with advanced features for complex data relationships. It's ideal for larger projects with intricate data models. Knex, being a query builder, provides more direct control over SQL operations and may be preferable for simpler applications or when raw performance is crucial. The choice between the two depends on project requirements, team expertise, and the complexity of database interactions needed.
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.
Pros of MikroORM
- Provides a full-featured ORM with entity management, identity map, and unit of work
- Supports TypeScript out of the box with strong typing and decorators
- Offers built-in caching mechanisms for improved performance
Cons of MikroORM
- Steeper learning curve due to more complex architecture and concepts
- May introduce overhead for simpler database operations
- Less flexibility for raw SQL queries compared to Knex
Code Comparison
MikroORM:
@Entity()
class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}
const user = em.create(User, { name: 'John' });
await em.persistAndFlush(user);
Knex:
await knex('users').insert({ name: 'John' });
const user = await knex('users').where({ name: 'John' }).first();
MikroORM provides a more object-oriented approach with entities and decorators, while Knex offers a simpler, SQL-like query builder. MikroORM's code is more verbose but provides stronger typing and abstraction. Knex's code is more concise and closer to raw SQL, offering greater flexibility for complex queries.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
knex.js
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:
- 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
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 {
// Create a table
await knex.schema
.createTable('users', (table) => {
table.increments('id');
table.string('user_name');
})
// ...and another
.createTable('accounts', (table) => {
table.increments('id');
table.string('account_name');
table.integer('user_id').unsigned().references('users.id');
});
// Then query the table...
const insertedRows = await knex('users').insert({ user_name: 'Tim' });
// ...and using the insert id, insert into the other table.
await knex('accounts').insert({
account_name: 'knex',
user_id: insertedRows[0],
});
// Query both of the rows.
const selectedRows = await knex('users')
.join('accounts', 'users.id', 'accounts.user_id')
.select('users.user_name as user', 'accounts.account_name as account');
// map over the results
const enrichedRows = selectedRows.map((row) => ({ ...row, active: true }));
// Finally, add a catch statement
} 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) {
// error handling
}
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:
/**
* @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();
Top Related Projects
Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js
An SQL-friendly ORM for Node.js
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, MS SQL Server, PostgreSQL and SQLite/libSQL databases.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot