1 0
Read Time:3 Minute, 11 Second

Knex.js, often referred to as Knex, is a popular JavaScript library for building and interacting with relational databases in Node.js applications. It provides a query builder and an abstraction layer for database operations, making it easier to work with databases in a more structured and flexible manner.

Key features and functionalities of Knex.js include:

  1. Query Building: Knex allows you to construct database queries using a fluent and chainable API, which makes it easier to create complex SQL queries without writing raw SQL statements.
  2. Database Abstraction: Knex provides a database-agnostic layer, meaning you can use it with various relational database management systems (RDBMS) like PostgreSQL, MySQL, SQLite, and more. You can switch between databases by changing the Knex configuration without needing to rewrite your queries.
  3. Migrations: Knex includes a migration system that helps you manage database schema changes over time. You can create, modify, and roll back database schemas using migrations, which ensures that your database schema remains consistent across different environments.
  4. Connection Pooling: Knex manages database connections efficiently by using connection pooling, which helps improve the performance and scalability of your application.
  5. Promises and Async/Await: Knex supports Promises and async/await, making it suitable for modern JavaScript and Node.js development, allowing for more readable and maintainable code.
knex

Here’s a basic example of using Knex.js to perform a simple database query in a Node.js application:

Install Knex.js using

 npm install knex

Database Driver Installation: Knex itself is a query builder and does not include the database drivers. You’ll need to install the appropriate database driver separately. For example, if you’re using PostgreSQL, you would install the pg driver like this:

npm install pg

Knex init (This creates config file for knex named knexfile.js)

Database Configuration in knexfile.js:

Initialize Knex with your database configuration
module.exports = {
  development: {
    client: 'pg',
    connection: {
      host: 'localhost',
      user: 'your_database_user',
      password: 'your_database_password',
      database: 'your_database_name',
    },
    migrations: {
      directory: './migrations',
    },
    seeds: {
      directory: './seeds',
    },
  },
};

Initialize Knex:

In your Node.js application, you’ll need to initialize Knex using the configuration you’ve defined. You can do this by importing knex and passing your configuration to it.

const knex = require('knex');
const knexConfig = require('./knexfile');

const db = knex(knexConfig.development); // Use the appropriate environment (e.g., development, production)

Creating Migrations:

If you plan to use migrations with Knex, you can create migration files to manage your database schema. You can generate a new migration file using the Knex CLI:

npx knex migrate:make migration_name --env configuration

Build Query:

This will create a migration named 20230823122542_014_initial_schema.js or something.It will have 2 export functions where we can write our raw sql query:

exports.up = async (knex) => {
    await knex.raw('CREATE TABLE a (\
        id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,\
        .........
        updated_at TIMESTAMP DEFAULT current_timestamp,\
        created_at TIMESTAMP\
    );\
    CREATE TABLE b (\
        id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,\
        .........
        updated_at TIMESTAMP DEFAULT current_timestamp,\
        created_at TIMESTAMP\
    );');
};

exports.down = async (knex) => {
// Drop the "a" table
    await knex.schema.dropTableIfExists('a');

    // Drop the "b" table
    await knex.schema.dropTableIfExists('b');
};

Running Migrations:

After defining your migrations, you can run them to apply the schema changes to your database:

npx knex migrate:latest --env configuration


Migration rollback:


Since we haven’t added any data to our database yet, probably the best option in this case is the second one, just roll back the migration and start over. We have nothing to lose.

To run a migration rollback we simply issue this command at the console:
knex migrate:rollback


Specific Migration Running and Rollback:

$ knex migrate:down 001_migration_name.js
To run the specified migration that has not yet been run

$ knex migrate:up 001_migration_name.js
To list both completed and pending migrations:

About Post Author

Shubhankar Singh

👋 Shubhankar Kumar Singh 🚀 Full Stack Web Developer & Designer 🌐 JavaScript Enthusiast for Front-End & Back-End 🎨 Passionate about Beautiful UI/UX
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

2 thoughts on “KnexJS Query Builder

Leave a Reply

Your email address will not be published. Required fields are marked *