Knex.js Database Cleaner

1.3.1 · maintenance · verified Wed Apr 22

knex-cleaner is a helper library designed to programmatically clear database tables for Knex.js-based applications, primarily used in testing environments. It provides functionalities to truncate or delete all tables (or a specified subset) within a given Knex database instance. It supports PostgreSQL, MySQL, and SQLite3 databases. The current stable version is 1.3.1, with its last release in 2020, primarily focusing on dependency updates and minor feature enhancements like handling schemas other than 'public' for PostgreSQL. Its key differentiation lies in its direct integration with Knex instances, offering granular control over the cleaning process, including the ability to ignore specific tables and reset identity counters for PostgreSQL. This makes it a suitable tool for ensuring a clean and consistent database state before or after running integration tests, abstracting away manual SQL commands for table clearing. While it can be used with Bookshelf.js, it operates directly on the underlying Knex instance.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Knex.js with an SQLite database, populate it with data, and then use `knex-cleaner` to clear all user-defined tables, ignoring Knex's internal migration tables. It shows both 'delete' mode and verification of empty tables.

import knexCleaner from 'knex-cleaner';
import knex from 'knex'; // Assume knex is installed

const dbConfig = {
  client: 'sqlite3',
  connection: {
    filename: './mydb_test.sqlite'
  },
  useNullAsDefault: true
};

const myKnexInstance = knex(dbConfig);

async function setupDatabase() {
  // For SQLite, create a dummy table to ensure the database file exists
  await myKnexInstance.schema.hasTable('users').then(exists => {
    if (!exists) {
      return myKnexInstance.schema.createTable('users', table => {
        table.increments('id');
        table.string('name');
        table.string('email');
      });
    }
  });
  await myKnexInstance.schema.hasTable('products').then(exists => {
    if (!exists) {
      return myKnexInstance.schema.createTable('products', table => {
        table.increments('id');
        table.string('name');
        table.decimal('price', 8, 2);
      });
    }
  });

  // Insert some data
  await myKnexInstance('users').insert([{ name: 'Alice', email: 'alice@example.com' }]);
  await myKnexInstance('products').insert([{ name: 'Widget', price: 19.99 }]);
  console.log('Database initialized and populated.');
}

async function cleanAndVerify() {
  await setupDatabase();

  console.log('Tables before clean:', await myKnexInstance.raw("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';"));

  const options = {
    mode: 'delete', // Or 'truncate' for faster clearing on supported DBs
    restartIdentity: true, // Useful for PostgreSQL
    ignoreTables: ['knex_migrations', 'knex_migrations_lock'] // Ignore Knex migration tables
  };

  try {
    await knexCleaner.clean(myKnexInstance, options);
    console.log('Database tables successfully cleaned!');
    console.log('Users table count after clean:', (await myKnexInstance('users').count('id as count'))[0].count);
    console.log('Products table count after clean:', (await myKnexInstance('products').count('id as count'))[0].count);
  } catch (error) {
    console.error('Error cleaning database:', error);
  } finally {
    await myKnexInstance.destroy();
  }
}

cleanAndVerify();

view raw JSON →