[Fixed] create/drop database task for gulp/knex


I have an Express.js web applications which uses Knex.js as the SQL query builder and migrations engine.
While Knex.js has methods for creating, dropping, and altering tables, it doesn’t have methods for creating/dropping the database itself.

I was wondering if there is an extension for Knex.js or even a gulp task that allows you to create/drop a database. I couldn’t find any.
I’m using a PostgreSQL database.


I’m not sure about PostgreSQL, but I hit the same problem with MySQL. I discovered you can use knex to connect without selecting a database, create the database with raw SQL, then re-connect selecting the new database.

Here is a stand-alone script that creates a new database with a single-column table:

var conn = {
  host: '',
  user: 'user',
  password: 'pass',
  charset: 'utf8',

// connect without database selected
var knex = require('knex')({ client: 'mysql', connection: conn });

knex.raw('CREATE DATABASE my_database').then(function () {

  // connect with database selected
  conn.database = 'my_database';
  knex = require('knex')({ client: 'mysql', connection: conn });

    .createTable('my_table', function (table) {
    .then(function () {

This works (well enough for me for now) but I’m interested to hear of other solutions.

Leave a Reply

(*) Required, Your email will not be published