Skip to content

Instantly share code, notes, and snippets.

@brunocascio
Last active July 4, 2020 13:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunocascio/faf049900b61d20661514be01d74a01f to your computer and use it in GitHub Desktop.
Save brunocascio/faf049900b61d20661514be01d74a01f to your computer and use it in GitHub Desktop.
Reset all tables sequence values in postgres with knex
return await knex.transaction(async t => {
try {
// Retrieve table names (excluding migrations_lock)
const tables = (await knex
.raw(`
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'
`)
.transacting(t)
)
.rows
.map(r => r.table_name)
.filter(tableName => tableName !== 'migrations_lock');
// reset serial sequence values
await Promise.all(tables.map(async tableName => await knex
.raw(`
SELECT
setval(pg_get_serial_sequence('${tableName}', 'id'),
coalesce(max(id), 0) + 1, false)
FROM ${tableName};
`)
.transacting(t)
));
return Promise.resolve(await t.commit());
} catch (error) {
Promise.reject(await t.rollback(error));
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment