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.
npm install knex-cleanerVerified import paths — ran on the pinned version, not inferred.
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.
Pass `{ restartIdentity: true }` in the options object to `knexCleaner.clean(knex, options)`.Choose the `mode` based on your database schema and performance needs. If you encounter foreign key errors with `truncate`, switch to `mode: 'delete'`. Be aware that `delete` will not reset identity counters on its own (use `restartIdentity: true` for Postgres).
Ensure you are using `knex-cleaner` with a Knex.js version it was last actively maintained with, or thoroughly test its behavior with newer Knex versions. Consider alternative libraries if encountering compatibility issues.
Ensure you are calling the `clean` method: `knexCleaner.clean(knex, options)`. If using ESM, `import knexCleaner from 'knex-cleaner';` then `knexCleaner.clean(...)`.
For SQLite, consider manually resetting the sequence or using a different cleaning strategy. For PostgreSQL, ensure `restartIdentity: true` is set in the options when `mode: 'delete'` is used. For databases where `TRUNCATE` resets IDs, use `mode: 'truncate'` if feasible.
Switch the `mode` option to `'delete'`. While slower, `DELETE` statements typically handle foreign key constraints more gracefully. Alternatively, temporarily disable foreign key checks if your database supports it and you understand the implications (not recommended for production). Or, ensure your `ignoreTables` list includes tables with critical parent data.