Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Created January 22, 2018 15:03
Show Gist options
  • Save n1ru4l/dcc420accd7673a68514773332b890c0 to your computer and use it in GitHub Desktop.
Save n1ru4l/dcc420accd7673a68514773332b890c0 to your computer and use it in GitHub Desktop.
Knex Reset Postgresql Database
import knex from 'knex'
import knexConfig from 'SUMWHERE'
const prepareDatabase = async () => {
const migrationTables = [`knex_migrations`, `knex_migrations_lock`]
const knexInstance = knex(knexConfig)
const closeConnection = pify(knexInstance.destroy)
const tableNames = await knexInstance(`pg_tables`)
.select(`tablename`)
.where(`schemaname`, `public`)
.then(tables => tables.map(r => r.tablename))
.then(tables => tables.filter(name => !migrationTables.includes(name)))
if (tableNames.length) {
await knexInstance.raw(
`TRUNCATE TABLE ${tableNames.join(',')} RESTART IDENTITY`
)
}
return { knex: knexInstance, close: closeConnection }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment