Knex is a SQL query builder for Node.js, which provides a flexible and convenient way to interact with relational databases. Below is a cheat sheet with commonly used Knex commands and syntax:
Installation
npm install knex --save
Configuration
Initialize Knex:Create a knexfile.js
in the project root or use a JavaScript object in your configuration file.
npx knex init
Modify the generated knexfile.js
to include your database configuration.
Connecting to a Database
Specify Database Configuration:Modify the knexfile.js
to include your database configuration (e.g., development environment).
Create a Knex Instance:
const knex = require('knex')(config); // Use the configuration from knexfile.js
Migrations
Creating a Migration:
npx knex migrate:make migration_name
This will create a new migration file in the migrations
directory.
Running Migrations:
npx knex migrate:latest
Rollback Migrations:
npx knex migrate:rollback
Seeding
Creating a Seed:
npx knex seed:make seed_name
This will create a new seed file in the seeds
directory.
Running Seeds:
npx knex seed:run
Query Building
Select:
knex.select('column1', 'column2').from('table').where('column', 'value');
Insert:
knex('table').insert({ column1: 'value1', column2: 'value2' });
Update:
knex('table').where('column', 'value').update({ column1: 'new_value' });
Delete:
knex('table').where('column', 'value').del();
Raw Queries:
knex.raw('SELECT * FROM table WHERE column = ?', ['value']);
Transactions
Begin a Transaction:
const trx = await knex.transaction();
Commit a Transaction:
await trx.commit();
Rollback a Transaction:
await trx.rollback();
Raw SQL
Running Raw SQL Queries:
knex.raw('SELECT * FROM table WHERE column = ?', ['value']);
Closing Connection
Closing the Connection:
knex.destroy();
This cheat sheet provides a basic overview of common Knex commands and features.