A query builder for PostgreSQL, MySQL and SQLite3, designed to be flexible, portable, and fun to use.

Overview

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.

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:

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();
Comments
  • knex 0.16 doesn't support knexfiles written in TypeScript

    knex 0.16 doesn't support knexfiles written in TypeScript

    Environment

    Knex version: 0.16.3 Database + version: docker postgres:10.4 OS: Windows 10 Pro & Docker node:8.14.0

    Bug

    1. knex migrate:make --knexfile knexfile.ts
    2. Error message: Unexpected token import

    Works normally on 0.15.x

    opened by brunolm 86
  • how to configure to use the standard ES6 Promise?

    how to configure to use the standard ES6 Promise?

    when running with node v6, is there a way to configure to use the standard ES6 Promise only (get rid of bluebird dependency)?

    for example in promise-queue package, it defaults to use whatever is globally available Promise,

    https://www.npmjs.com/package/promise-queue

    or user can explicitly configure it by Queue.configure(require('vow').Promise);

    So can this package implement a similar strategy?

    discussion 
    opened by c0b 82
  • Reconnecting after database server disconnect/reconnect

    Reconnecting after database server disconnect/reconnect

    I searched through the issues to find if others are having trouble attempting to reconnect.

    It's been a very long time since these two: https://github.com/tgriesser/knex/issues/1341 https://github.com/tgriesser/knex/issues/936

    Most of the suggestions I have seen in the issues so far are relying on pool2 and include configuration for requestTimeout.

    I am on version 0.12.2 of knex, which no longer uses pool2. I also can no longer see implementation of ping in src/client.js.

    I'm running tests where I use docker to run these steps:

    1. Spin up postgres db in container.
    2. Start knex/connect to postgres.
    3. Run a test query, evaluate success.
    4. Stop postgres db in container.
    5. Run test query again, evaluate failure (with config: `{pool: {acquireTimeoutMillis: XXXX}, acquireConnectionTimeout: XXXX)
    6. Restart postgres db in container.
    7. Run test query again, evaluate success.

    Step 7 is failing in the same way step 5 does.

    I assumed knex would automatically attempt to reconnect. Is there a way I can cause a reconnection?

    If you'd like, I can post this question instead at one of the past conversations on reconnection. I thought it was worth having a new conversation since most of the other conversations include only answers from before switching to generic-pool.

    bug more information requested help wanted 
    opened by ty10r 74
  • Modifying columns

    Modifying columns

    I think it is a reasonable expectation that it would be possible to:

    • rename a column
    • change the data type
    • add or drop the null constraint
    • change the default

    And probably other things that I have not thought of.

    I would imagine the syntax for doing this would be something like

     knex.Schema.table('table_name', function (t) {
            t.string('my_column').renameTo('something_else');
            t.string('my_column').changeTo('text');
            t.string('my_column').nullable() < adds nullable if not already present
            t.string('my_column').notNullable() < removes nullable if present
            t.string('my_column').defaultTo('whatever') < adds or updates the default
      });
    

    Maybe there needs to be something extra in the chain, possibly at the knex.Schema.table level to indicate that this is a modify statement not an add.

    I realise that this is tricky to implement across various databases, especially in SQLite where you have to create a whole new table, but in a system which requires migrations, without these tools it is going to be necessary to use knex.raw and write all the migrations for each DB supported, which sort of defeats the point of having a nice ORM especially one which is about to support migrations.

    feature request 
    opened by ErisDS 61
  • Support for mssql

    Support for mssql

    Wondering if there are any plans to support MSSQL. Could take advantage of a MSSQL library like this one: "https://github.com/patriksimek/node-mssql".

    I'd be happy to work on a pull request for this, but I might need a few pointers on how to get started.

    feature request 
    opened by tybenz 53
  • TimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

    TimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

    Environment

    Knex version: 0.15.2 Database: sqlite3 OS: Ubuntu 18

    I'm getting lots of errors like TimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?

    Any ideas? All my code lives in this one file: https://github.com/umaar/wiki-globe/blob/master/index.js - that code powers this globe which I posted in a Hacker News comment and in turn led to the discovery of such error.

    An example query looks like this:

    await knex('edits').insert([{
    	field1: JSON.stringify(data),
    	field2: 'field2'
    }]);
    

    Does sqlite3 only allow a single connection to it because it's file-based? I'll try adding .transacting() calls to see if that makes a difference.

    I guess it comes down to: some technical limitation with sqlite3 (maybe lack of pooling?) or some badly written code DB/queries on my part! Any insight you have would be much appreciated, thanks!

    insightful 
    opened by umaar 47
  • Can't add new command when connection is in closed state

    Can't add new command when connection is in closed state

    This happened to me today when i upgrade to 0.14.0. Not sure when the bug was introduced.

    Also, i saw this along with the above message: This socket has been ended by the other party

    Previously working version seems to be 0.13.0

    node 8.9.1, knex 0.14.0, "mysql2": "1.4.2"

    bug 
    opened by tuananh 44
  • WIP: Replace MSSQL dialect with Tedious.js implementation

    WIP: Replace MSSQL dialect with Tedious.js implementation

    Tedious.JS MSSQL dialect driver

    Hello Knex,

    I have been working on deprecating the use of node-mssql in favour of tedious which is the underlying TDS stream driver for talking with Microsoft SQL server for about six months now. I wanted to take it into production before I made people aware of this patch to make sure it was worth submitting.

    Rationale

    I ran into major issues with every ORM or query library that uses node-mssql under the hood for MSSQL, which ultimately completely prevented me from running my system in production.

    In a nutshell, the problem is that node-mssql is in itself a high-level driver that contains its own mechanisms which Knex either doesn't need, or conflicts with. To summarize the problems with using this library for this dialect:

    • Timeout acquiring resource messages, killing the application,
    • Random, huge latency spikes between query and result, making performance unstable,
    • Connection timeouts on startup, and
    • Inability to recover from error conditions

    The SQL dialect experience with Microsoft SQL Server on node.js, and Knex in particular, is very poor because of this driver.

    Patch details

    This patchset contains a working implementation of tedious backed by a few months of my internal product running in production without issues. The patch discards the second-level connection pool provided by node-mssql and simply attaches Tedious connection objects to Knex's pooling mechanism like every other dialect.

    With my driver running in production there have been no resource timeouts, no connection issues, and Knex receives the results of the query as fast as Tedious.js can deserialize the token stream. This implementation has been the most stable my project has ever been on MSSQL.

    I don't use some of MSSQL's functions so I am unable to complete some of the driver, but it is good enough for me to roll into production right now.

    Thanks for looking! :+1:

    improvement MSSQL high priority 
    opened by tylerjwatson 43
  • Make TypeScript support better, using lessons from typed-knex

    Make TypeScript support better, using lessons from typed-knex

    Environment

    Knex version: Current

    Feature discussion / request

    The last couple of years I've been using Knex and TypeScript and I've created a library to make this easier: https://github.com/wwwouter/typed-knex Recently Knex has added some basic support for TypeScript and I would like to get rid of my own library.

    I iterated quite a lot and I think my experience could be useful for this project.

    So the purpose of this ticket is getting feedback whether I could help and getting some more insight into the TypeScript roadmap.

    opened by wwwouter 42
  • Knex cli should support es6 for configuration and migrations

    Knex cli should support es6 for configuration and migrations

    It would be nice if the knex cli would support es6 for configuration and migrations. Maybe this could be behind a flag or only when there is a .babelrc file in current working directory.

    feature request PR please 
    opened by olalonde 42
  • How to execute multiple queries in one run?

    How to execute multiple queries in one run?

    I'm facing a problem that I would like to execute multiple queries separated by ';' by a single exec, is that possible?

    My test code which is failing looks like:

          var query = '' +
            'UPDATE "records_raw" ' +
            'SET "title" = ? ' +
            'WHERE "id" = ?' +
            ';' +
            'UPDATE "records_raw" ' +
            'SET "title" = ? ' +
            'WHERE "id" = ?' +
            ';';
    
          var bindings = [
            "x", "1",
            "y", "2"
          ];
    
          knex.raw(query, bindings).exec(function(err, result) {
            assert.isNotError(err);
          });
    

    The error:

    Error(cannot insert multiple commands into a prepared statement, ...
    

    Is there a way to disable prepared statements for such queries?

    feature request 
    opened by kobalicek 40
  • Unknown file extension

    Unknown file extension ".ts" for /home/[user]/stock_analysis_app/knexfile.ts

    Environment

    Knex version: 2.3.0 Database + version: Postgres 12 OS: Ubuntu(WSL2)

    Bug

    1. Explain what kind of behaviour you are getting and how you think it should do

    I can't make migrations with typescript. yarn knex init -x ts then yarn knex migrate:make test_migration -x ts gives me an error. I've tried removing package_lock and node_modules, installing globally, installing ts-node, and recloning the whole repo.

    1. Error message
    Unknown file extension ".ts" for /home/zii/stock-analysis-app/knexfile.ts
    TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/[user]/stock-analysis-app/knexfile.ts
        at new NodeError (node:internal/errors:400:5)
        at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:74:9)
        at defaultGetFormat (node:internal/modules/esm/get_format:114:38)
        at defaultLoad (node:internal/modules/esm/load:81:20)
        at nextLoad (node:internal/modules/esm/loader:161:28)
        at ESMLoader.load (node:internal/modules/esm/loader:596:26)
        at ESMLoader.moduleProvider (node:internal/modules/esm/loader:448:22)
        at new ModuleJob (node:internal/modules/esm/module_job:64:26)
        at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:471:17)
        at ESMLoader.getModuleJob (node:internal/modules/esm/loader:425:34)
    
    1. Reduced test code, for example in https://npm.runkit.com/knex or if it needs real database connection to MySQL or PostgreSQL, then single file example which initializes needed data and demonstrates the problem.

    the repo with the problem, knexfile included I'm sorry, I don't think a minimal code representation would help.

    opened by gatlace 1
  • Seeds provides as plain SQL dumps

    Seeds provides as plain SQL dumps

    Environment

    Knex version: 2.3.0

    Feature discussion / request

    The most common way of update schema and seeds data is exchange between DBAs/DevOps with pure SQL text with DDL character (ALTER) queries or populating data (INSERT).

    Since that nature of exchange between environments is more important, is it possible to provide compatibility layer in knex to support simple SQL queries in external sources (i.e. files for example). This would be very convenient at the initial stages of jump in to the migration approach with knex.

    Could you help with explain (the documentation does not describe any way to use external files with SQL queries) how reach a simple way to using SQL files seeds instead implement it as js code?

    opened by vsedyshev-intermedia 0
  • Custom Naming Convention For Migration Files

    Custom Naming Convention For Migration Files

    Documentation: https://github.com/knex/documentation/pull/484

    Purpose: Provide the ability to have a custom naming convention for migration files.

    Reasoning: Some projects may want to use a different naming convention other than the default for what this library provides.

    opened by sgarbesi 1
  • Migrartion make raise an error

    Migrartion make raise an error

    Environment

    Knex version: 2.3.0 OS: Linux

    Bug

    1. Create knexfile.mjs with next content
    const config = {
        client: ...,
        connection: ...,
        migrations: {
            directory: './migrations'.
        },
        seeds: {
            directory: './seeds'.
        },
    };
    export default config;
    export const {client, connection, migrations, seeds} = config;
    
    1. Execute knex migrate:make migration_name raise an next error output:
    Using environment: development
    Using environment: development
    Using environment: development
    Failed to resolve config file, knex cannot determine where to generate migrations
    The "path" argument must be of type string. Received null
    TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received null
        at new NodeError (node:internal/errors:387:5)
        at validateString (node:internal/validators:162:11)
        at Object.resolve (node:path:1098:7)
        at /home/vsedyshev/Work/HPBX-11369/quality-center/server/node_modules/knex/lib/migrations/migrate/MigrationGenerator.js:77:19
        at Array.map (<anonymous>)
        at MigrationGenerator._absoluteConfigDirs (/home/vsedyshev/Work/HPBX-11369/quality-center/server/node_modules/knex/lib/migrations/migrate/MigrationGenerator.js:71:24)
        at MigrationGenerator._ensureFolder (/home/vsedyshev/Work/HPBX-11369/quality-center/server/node_modules/knex/lib/migrations/migrate/MigrationGenerator.js:28:23)
        at MigrationGenerator.make (/home/vsedyshev/Work/HPBX-11369/quality-center/server/node_modules/knex/lib/migrations/migrate/MigrationGenerator.js:20:16)
        at Migrator.make (/home/vsedyshev/Work/HPBX-11369/quality-center/server/node_modules/knex/lib/migrations/migrate/Migrator.js:315:27)
        at Command.<anonymous> (/usr/lib/node_modules/knex/bin/cli.js:231:12)
    

    Look like directory value in MigrationGenerator.js:77 is null. Could you please suggest me where is born?

    opened by vsedyshev-intermedia 2
  • Knex.js has a limited SQL injection vulnerability

    Knex.js has a limited SQL injection vulnerability

    Environment

    Knex version: MYSQL2 + 2.3.0: OS: Kubuntu

    Bug

    npm install --save knex gives warring knex * Severity: high Knex.js has a limited SQL injection vulnerability - https://github.com/advisories/GHSA-4jv9-3563-23j3 No fix available node_modules/knex

    Need to have clean install without warrning......

    opened by saunish-bytap 1
Releases(2.3.0)
  • 2.3.0(Sep 1, 2022)

    New features:

    • PostgreSQL: Explicit jsonb support for custom pg clients #5201
    • SQLite: Support returning with sqlite3 and better-sqlite3 #5285
    • MSSQL: Implement mapBinding mssql dialect option #5292

    Typings:

    • Update types for TS 4.8 #5279
    • Fix typo #5267
    • Fix WhereJsonObject withCompositeTableType #5306
    • Fix AnalyticFunction type #5304
    • Infer specific column value type in aggregations #5297
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Jul 18, 2022)

    New features:

    • Inline primary key creation for postgres flavours #5233
    • SQLite: Add warning for undefined connection file #5223
    • MSSQL: Add JSON parameter support for connection #5200

    Bug fixes:

    • PostgreSQL: add primaryKey option for uuid #5212

    Typings:

    • Add promisable and better types #5222
    • Update raw query bind parameter type #5208
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(May 26, 2022)

    2.1.0 - 26 May, 2022

    New features:

    • Improve bundling experience to safely import dialects while using static paths #5142
    • Implement extendable builders #5041
    • PostgreSQL: Refresh materialized view concurrently #5166

    Bug fixes:

    • Use correct paths in package.json browser field #5174
    • MariaDB: Fix 'NULL' returned instead of NULL on MariaDB 10.2.6+ #5181
    • MySQL: fix hasColumn Error (hasColumn ('a_id') is true, but hasColumn('a_Id') is false) #5148
    • MSSQL: Fix .hasTable result when using .withSchema #5176
    • Oracle: correctly INSERTS Buffer #4869

    Typings:

    • Update type definitions for pg connection #5139
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Apr 21, 2022)

    2.0.0 - 21 April, 2022

    Breaking changes

    • Restore sqlite3 package #5136

    Test / internal changes:

    • Migrate Husky from 4 to 7 #5137
    • Migrate Jake to 10.8.5 #5138
    Source code(tar.gz)
    Source code(zip)
  • 1.0.7(Apr 13, 2022)

    1.0.7 - 13 March, 2022

    Bug fixes:

    • CLI: Fix cli migrate:make SQLite dependency #5106

    1.0.6 - 12 March, 2022

    Bug fixes:

    • PostgreSQL: Wait for search path to be set before returning connection #5107
    • CLI: No client override during migrate:make #5109
    Source code(tar.gz)
    Source code(zip)
  • 1.0.5(Apr 4, 2022)

    New features:

    • Override knexfile options with CLI options #4047

    Bug fixes:

    • Stringify json value in update #5063
    • Fix isModuleType() for yarn #4447
    • Wrapped Unions Fixes #5072
    • SQLite: Fix @vscode-sqlite3 error message #5081
    • CLI: Fix completed migration listing #5060

    Typings:

    • Make default generic parameters of Knex match the generic parameter types of knex #5021
    • Update knex types for TS 4.7 #5095
    Source code(tar.gz)
    Source code(zip)
  • 1.0.4(Mar 13, 2022)

    1.0.4 - 13 March, 2022

    New features:

    • Add whereLike functions #5044

    Bug fixes:

    • Fix orWhereJsonPath clause #5022
    • Subquery in on clause missing parenthesis #5049
    • Rework Union Wrapping #5030
    • Oracle: Fix batch inserts with DEFAULT values with OracleDB #2592 #5037

    Typings:

    • Fix types for "returning" methods #5031
    • createTableLike callback should be optional #5055

    Documentation:

    • Website URL changed to https://knex.github.io/documentation/
    Source code(tar.gz)
    Source code(zip)
  • 1.0.3(Feb 10, 2022)

    1.0.3 - 11 February, 2022

    Bug fixes:

    • Fix error message for missing migration files #4937
    • Add withMaterialized and withNotMaterialized to method-constants #5009
    • PostgreSQL: Fix whereJsonPath queries #5011
    • PostgreSQL: Fix delete joins #5016
    • CockroachDB: Fix whereJsonPath queries #5011
    • MySQL: Create primary keys in same statement #5017

    Typings:

    • Fix type definition for getMigration in MigrationSource #4998
    • Fix argument type of alter method #4996

    Improvements:

    • Use async / await syntax in seeds as default #5005

    Documentation:

    • Add Firebird dialect to ECOSYSTEM.md #5003

    1.0.2 - 02 February, 2022

    New features:

    • Support of MATERIALIZED and NOT MATERIALIZED with WITH/CTE #4940
    • Add raw support in onConflict clause #4960
    • Alter nullable constraint when alterNullable is set to true #4730
    • Add alterType parameter for alter function #4967
    • Support string json in json values #4988
    • MySQL: add with clause #4508

    Bug fixes:

    • Fix error message for missing migration files #4937
    • Move deferrable to after on update/on delete #4976
    • Do not use sys.tables to find if a table exists #2328
    • PostgreSQL: Fix Order nulls #4989
    • MySQL: Fix collation when renaming column #2666
    • SQLite: Same boolean handling in better-sqlite3 as in sqlite3 #4982

    Typings:

    • WhereILike - fix typo #4941
    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Jan 16, 2022)

  • 1.0.0(Jan 16, 2022)

    Breaking changes

    • Dropped support for Node 10;
    • Replaced unsupported sqlite3 driver with @vscode/sqlite3;
    • Changed data structure from RETURNING operation to be consistent with SELECT;
    • Changed Migrator to return list of migrations as objects consistently.

    New features:

    • Support fromRaw #4781
    • Support zero precision in timestamp/datetime #4784
    • Support whereLike and whereILike #4779
    • Add JSDoc (TS flavor) to stub files #4809
    • Allow skip binding in limit and offset #4811
    • Support creating a new table in the database based on another table #4821
    • Accept Raw on onIn joins #4830
    • Implement support for custom seed sources #4842
    • Add binary uuid option #4836
    • ForUpdate array parameter #4882
    • Add camel case to timestamps method #4803
    • Advanced JSON support #4859
    • Add type to TypeScript knexfile #4909
    • Checks Constraints Support #4874
    • Support creating multiple PKs with increments #4903
    • Enable wrapIdentifier for SQLite .hasTable #4915
    • MSSQL: Add support for unique constraint #4887
    • SQLite: New dialect, using better-sqlite3 driver #4871
    • SQLite: Switch to @vscode/sqlite3 #4866
    • SQLite: Support createViewOrReplace #4856
    • SQLite: Support RETURNING statements for better-sqlite3 driver #4934
    • PostgreSQL: Support JOIN and USING syntax for Delete Statement #4800

    Bug fixes:

    • Fix overzealous warning on use of whereNot with "in" or "between" #4780
    • Fix Union all + first syntax error #4799
    • Make view columns optional in create view like #4829
    • Insert lock row fix during migration #4865
    • Fix for createViewOrReplace #4856
    • SQLite: Fix foreign key constraints when altering a table #4189
    • MySQL: Validate connection fix #4794
    • MySQL: Set comment size warning limit to 1024 #4867

    Typings:

    • Allow string indexType in index creation #4791
    • Add missing ints typings #4832
    • Returning method types #4881
    • Improve columnInfo type #4868
    Source code(tar.gz)
    Source code(zip)
  • 0.95.14(Nov 14, 2021)

    0.95.14 - 09 November, 2021

    Bug fixes:

    • MySQL: mysql2 dialect validate connection fix #4794

    0.95.13 - 02 November, 2021

    Bug fixes:

    • PostgreSQL: Support zero precision in timestamp/datetime #4784

    Typings:

    • Allow string indexType in index creation #4791
    Source code(tar.gz)
    Source code(zip)
  • 0.95.12(Oct 27, 2021)

    0.95.12 - 28 October, 2021

    New features:

    • New dialect: CockroachDB #4742
    • New dialect: pg-native #4327
    • CockroachDB: add support for upsert #4767
    • PostgreSQL: Support SELECT .. FOR NO KEY UPDATE / KEY SHARE row level locking clauses #4755
    • PostgreSQL: Add support for 'CASCADE' in PostgreSQL 'DROP SCHEMA' queries #4713
    • MySQL: Add storage engine index Type support to index() and unique() schema #4756
    • MSSQL: Support table.primary, table.unique variant with options object #4710
    • SQLite: Add setNullable support to SQLite #4684
    • Add geometry column building #4776
    • Add support for creating table copies #1373
    • Implement support for views and materialized views #1626
    • Implement partial index support #4768
    • Support for 'is null' in 'order by' #3667

    Bug fixes:

    • Fix support for Oracle connections passed via knex.connection() #4757
    • Avoid inserting multiple locks if a migration lock already exists #4694

    Typings:

    • Some TableBuilder methods return wrong types #4764
    • Update JoinRaw bindings type to accept arrays #4752
    • fix onDelete/onUpdate for ColumnBuilder #4656
    Source code(tar.gz)
    Source code(zip)
  • 0.95.11(Sep 3, 2021)

    0.95.11 - 03 September, 2021

    New features:

    • Add support for nullability modification via schema builder (table.setNullable() and table.dropNullable()) #4657
    • MySQL: Add support for mysql/mariadb-client JSON parameters in connectionURIs #4629
    • MSSQL: Support comments as MS_Description properties #4632

    Bug fixes:

    • Fix Analytic orderBy and partitionBy to follow the SQL documentation #4602
    • CLI: fix migrate:up for migrations disabling transactions #4550
    • SQLite: Fix adding a column with a foreign key constraint in SQLite #4649
    • MSSQL: columnInfo() support case-sensitive database collations #4633
    • MSSQL: Generate valid SQL for withRecursive() #4514
    • Oracle: withRecursive: omit invalid RECURSIVE keyword, include column list #4514

    Improvements:

    • Add .mjs migration and seed stubs #4631
    • SQLite: Clean up DDL handling and move all operations to the parser-based approach #4648
    Source code(tar.gz)
    Source code(zip)
  • 0.95.10(Aug 23, 2021)

    Improvements:

    • Use sys info function instead of connection db name #4623

    Typings:

    • Deferrable and withkeyName should not be in ColumnBuilder #4600
    • Add TypeScript support for deferrable, new Primary/Unique syntax #4589

    New features:

    • Oracle: support specifying schema for dropTable and dropSequence #4596
    • Oracle: support specifying schema for autoincrement #4594
    Source code(tar.gz)
    Source code(zip)
  • 0.95.8(Jul 25, 2021)

    New features:

    • Add deferrable support for constraint #4584
    • Implement delete with join #4568
    • Add DPI error codes for Oracle #4536

    Bug fixes:

    • Fixing PostgreSQL datetime and timestamp column created with wrong format #4578

    Typings:

    • Improve analytic types #4576
    • MSSQL: Add trustServerCertificate option #4500
    Source code(tar.gz)
    Source code(zip)
  • 0.95.5(May 11, 2021)

    New features:

    • SQLite: Add support for file open flags #4446
    • Add .cjs extension to Seeder.js to support Node ESM #4381 #4382

    Bug fixes:

    • Remove peerDependencies to avoid auto-install on npm 7 #4480

    Typings:

    • Fix typing for increments and bigIncrements #4406
    • Add typings for on JoinClause for onVal #4436
    • Adding Type Definition for isTransaction #4418
    • Export client class from knex namespace #4479
    Source code(tar.gz)
    Source code(zip)
  • 0.95.3(Mar 25, 2021)

    New features:

    • PostgreSQL: Add "same" as operator #4372
    • MSSQL: Improve an estimate of the max comment length #4362
    • Throw an error if negative offset is provided #4361

    Bug fixes:

    • Fix timeout method #4324
    • SQLite: prevent dropForeign from being silently ignored #4376

    Typings:

    • Allow config.client to be non-client instance #4367
    • Add dropForeign arg type for single column #4363
    • Update typings for TypePreservingAggregation and stream #4377
    Source code(tar.gz)
    Source code(zip)
  • 0.95.2(Mar 11, 2021)

    0.95.2 - 11 March, 2021

    New features:

    • Improve ESM import support #4350

    Bug fixes:

    • CLI: update ts.stub files to new TypeScript namespace #4344
    • CLI: fix TypeScript migration stub after 0.95.0 changes #4366

    Typings:

    • Move QueryBuilder and KnexTimeoutError into knex namespace #4358

    Test / internal changes:

    • Unify db test helpers #4356

    0.95.1 - 04 March, 2021

    Bug fixes:

    • CLI: fix knex init not finding default knexfile #4339
    Source code(tar.gz)
    Source code(zip)
  • 0.95.0(Mar 3, 2021)

    0.95.0 - 03 March, 2021

    Please upgrade to TypeScript 4.1 if using an older version! Check out the migration guide for other breaking changes.

    New features:

    • Add transaction isolation support #4185
    • Add analytic functions #4188
    • Change default to not trigger a promise rejection for transactions with a specified handler #4195
    • Make toSQL().toNative() work for Raw to match the API for QueryBuilder #4058
    • Allow 'match' operator #3569
    • Support optimizer hints #4243
    • Add parameter to prevent autoincrement columns from being primary keys #4266
    • Make "first" and "pluck" mutually exclusive #4280
    • Added merge strategy to allow selecting columns to upsert. #4252
    • Throw error if the array passed to insert is empty #4289
    • Events: introduce queryContext on query-error #4301
    • CLI: Use UTC timestamp for new migrations #4245
    • MSSQL: Replace MSSQL dialect with Tedious.js implementation #2857 #4281
    • MSSQL: Use "nvarchar(max)" for ".json()" #4278
    • MSSQL: Schema builder - add predictable constraint names for default values #4319
    • MSSQL: Schema builder - attempt to drop default constraints when changing default value on columns #4321
    • SQLite: Fallback to json for sqlite3 when using jsonb #4186
    • SQLite: Return complete list of DDL commands for creating foreign keys #4194
    • SQLite: Support dropping composite foreign keys #4202
    • SQLite: Recreate indices when altering a table #4277
    • SQLite: Add support for altering columns #4322

    Bug fixes:

    • Fix issue with .withSchema usage with joins on a subquery #4267
    • Fix issue with schema usage with FROM clause contain QueryBuilder, function or Raw #4268
    • CLI: Address raised security warnings by dropping liftoff #4122
    • CLI: Fix an issue with npm@7 and ESM when type was set to 'module' in package.json #4295
    • PostgreSQL: Add check to only create native enum once #3658
    • SQLite: Fix foreign key "on delete" when altering a table #4225
    • SQLite: Made the constraint detection case-insensitive #4330
    • MySQL: Keep auto increment after rename #4266
    • MSSQL: don't raise query-error twice #4314
    • MSSQL: Alter column must have its own query #4317

    Typings:

    • Add missing onConflict overrides #4182
    • Introduce the "infamous triplet" export #4181
    • Fix type definition of Transaction #4172
    • Add typedefinitions for havingNotIn #4265
    • Include 'name' property in MigratorConfig #4300
    • Improve join and conflict types #4318
    • Fix ArrayIfAlready type #4331

    Test / internal changes:

    • Drop global Knex.raw #4180
    • Stop using legacy url.parse API #3702
    • Various internal refactorings #4175 #4177 #4178 #4192
    • Refactor to classes #4190 #4191 #4193 #4210 #4253
    • Move transaction type tests to TSD #4208
    • Clean up destroy logic #4248
    • Colorize code snippets in readme files #4234
    • Add "Ecosystem" documentation for Knex plugins #4183
    • Documentation cleanup
    • SQLite: Use SQLite "rename column" instead of a DDL helper #4200
    • SQLite: Simplify reinsert logic when altering a table #4272
    Source code(tar.gz)
    Source code(zip)
  • 0.21.17(Feb 15, 2021)

    0.21.17 - 30 January, 2021

    Bug fixes:

    • SQLite: Fix SQLite foreign on delete when altering a table #4261

    New features:

    • Add support for optimizer hints (see https://github.com/knex/documentation/pull/306 for documentation) #4243

    0.21.16 - 17 January, 2021

    Bug fixes:

    • MSSQL: Avoid passing unsupported pool param. Fixes node-mssql 7+ support #4236
    Source code(tar.gz)
    Source code(zip)
  • 0.21.15(Dec 26, 2020)

  • 0.21.14(Dec 18, 2020)

  • 0.21.13(Dec 11, 2020)

  • 0.21.10(Oct 31, 2020)

Owner
knex
SQL for JavaScript
knex
A tiny wrapper around pg that makes PostgreSQL a lot of fun to use. Written in TypeScript.

A tiny wrapper around pg that makes PostgreSQL a lot of fun to use. Written in TypeScript.

Mojolicious 8 Nov 29, 2022
A fast, synchronized and dynamic query builder package.

@ssibrahimbas/query A fast, synchronized and dynamic query builder package. What is? In short, the query builder. You can write complex and parameteri

Sami Salih İbrahimbaş 7 Jun 13, 2022
ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used

null 30.1k Jan 3, 2023
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases.

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite datab

MikroORM 5.4k Dec 31, 2022
Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under Windows, Linux, Mac or as web application

DbGate 2k Dec 30, 2022
A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud.

Dittorm A Node.js ORM for MySQL, SQLite, PostgreSQL, MongoDB, GitHub and serverless service like Deta, InspireCloud, CloudBase, LeanCloud. Installatio

Waline 21 Dec 25, 2022
Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server & SQLite

Prisma Quickstart • Website • Docs • Examples • Blog • Slack • Twitter • Prisma 1 What is Prisma? Prisma is a next-generation ORM that consists of the

Prisma 28k Jan 2, 2023
Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

방신우 22 Dec 23, 2022
A Node.js library for retrieving data from a PostgreSQL database with an interesting query language included.

RefQL A Node.js library for retrieving data from a PostgreSQL database with an interesting query language included. Introduction RefQL is about retrie

Rafael Tureluren 7 Nov 2, 2022
sqlite3 in ur indexeddb

This is an absurd project. It implements a backend for sql.js (sqlite3 compiled for the web) that treats IndexedDB like a disk and stores data in bloc

James Long 3.6k Jan 4, 2023
sqlite3 in ur indexeddb

This is an absurd project. It implements a backend for sql.js (sqlite3 compiled for the web) that treats IndexedDB like a disk and stores data in bloc

James Long 3.6k Dec 30, 2022
Same as sqlite-tag but without the native sqlite3 module dependency

sqlite-tag-spawned Social Media Photo by Tomas Kirvėla on Unsplash The same sqlite-tag ease but without the native sqlite3 dependency, aiming to repla

Andrea Giammarchi 17 Nov 20, 2022
Burger builder project using React, Hooks and Context API.

Burger Builder In this project, I made a context-api project by creating hamburgers with 3 different materials. Project setup npm install Project star

Efecan Pınar 4 Jun 17, 2021
~900 byte minified CSV parser and builder. Smaller when compressed. Built in ESM only.

but-csv ~900 byte minified CSV parser and builder. Smaller when compressed. Built in ESM only. Doesn't care about headers, keyed rows, anything but st

Sam Thorogood 16 Nov 13, 2022
Execute one command (or mount one Node.js middleware) and get an instant high-performance GraphQL API for your PostgreSQL database!

PostGraphile Instant lightning-fast GraphQL API backed primarily by your PostgreSQL database. Highly customisable and extensible thanks to incredibly

Graphile 11.7k Jan 4, 2023
A PostgreSQL client with strict types, detailed logging and assertions.

Slonik A battle-tested PostgreSQL client with strict types, detailed logging and assertions. (The above GIF shows Slonik producing query logs. Slonik

Gajus Kuizinas 3.6k Jan 3, 2023
An adapter-based ORM for Node.js with support for mysql, mongo, postgres, mssql (SQL Server), and more

Waterline is a next-generation storage and retrieval engine, and the default ORM used in the Sails framework. It provides a uniform API for accessing

Balderdash 5.4k Jan 4, 2023
NodeJS PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.

Node Postgres Extras NodeJS port of Heroku PG Extras with several additions and improvements. The goal of this project is to provide powerful insights

Paweł Urbanek 68 Nov 14, 2022