Socket
Socket
Sign inDemoInstall

knex

Package Overview
Dependencies
307
Maintainers
4
Versions
252
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    knex

A batteries-included SQL query & schema builder for Postgres, MySQL and SQLite3 and the Browser


Version published
Weekly downloads
1.8M
increased by4.03%
Maintainers
4
Install size
5.18 MB
Created
Weekly downloads
 

Package description

What is knex?

Knex.js is a SQL query builder for JavaScript, which works with multiple database systems like PostgreSQL, MySQL, SQLite3, and Oracle. It allows for building and executing SQL queries in a readable and programmatic way, handling connections and transactions, and seeding and migrating databases for development purposes.

What are knex's main functionalities?

Query Building

Builds a SQL query to select all columns from the 'users' table where the 'id' is 1.

knex.select('*').from('users').where('id', 1)

Schema Building

Creates a new table called 'users' with an auto-incrementing 'id' column, a 'name' column of string type, and timestamp columns for 'created_at' and 'updated_at'.

knex.schema.createTable('users', function(table) { table.increments('id'); table.string('name'); table.timestamps(); })

Transaction Support

Performs a transaction to insert multiple records into the 'books' table. If any part of the transaction fails, all changes are rolled back.

knex.transaction(function(trx) { const books = [{title: 'Canterbury Tales'}, {title: 'Macbeth'}]; return trx.insert(books).into('books'); })

Raw Queries

Executes a raw SQL query, selecting all columns from the 'users' table where the 'id' is 1, with parameter binding.

knex.raw('SELECT * FROM users WHERE id = ?', [1])

Seeding

Defines a seed file that first clears the 'users' table and then inserts new records into it.

exports.seed = function(knex) { return knex('users').del().then(function() { return knex('users').insert([{name: 'Alice'}, {name: 'Bob'}]); }); }

Migrations

Defines a migration file with an 'up' method to create a new 'users' table and a 'down' method to drop the 'users' table.

exports.up = function(knex) { return knex.schema.createTable('users', function(table) { table.increments(); table.string('name'); table.timestamps(); }); }; exports.down = function(knex) { return knex.schema.dropTable('users'); };

Other packages similar to knex

Readme

Source

knex.js

npm version npm downloads Coverage Status Dependencies Status Gitter chat Language Grade: JavaScript

A SQL query builder that is flexible, portable, and fun to use!

A batteries-included, multi-dialect (MSSQL, MySQL, PostgreSQL, SQLite3, Oracle (including Oracle Wallet Authentication)) query builder for Node.js, featuring:

Node.js versions 10+ are supported.

Read the full documentation to get started!
Or check out our Recipes wiki to search for solutions to some specific problems
If upgrading from older version, see Upgrading instructions

For support and questions, join the #bookshelf channel on freenode IRC

For an Object Relational Mapper, see:

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:

const knex = require('knex')({
  client: 'sqlite3',
  connection: {
    filename: './data.db',
  },
});

// Create a table
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...
  .then(() =>
    knex('users').insert({ user_name: 'Tim' })
  )

  // ...and using the insert id, insert into the other table.
  .then(rows => 
    knex('accounts').insert({ account_name: 'knex', user_id: rows[0] })
  )

  // Query both of the rows.
  .then(() => 
    knex('users')
      .join('accounts', 'users.id', 'accounts.user_id')
      .select('users.user_name as user', 'accounts.account_name as account')
  )

  // map over the results
  .then(rows =>
    rows.map(row => {
      console.log(row)
    })
  )

  // Finally, add a .catch handler for the promise chain
  .catch(e => {
    console.error(e);
  });

Keywords

FAQs

Last updated on 07 Aug 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc