Last active
July 4, 2020 13:06
-
-
Save brunocascio/faf049900b61d20661514be01d74a01f to your computer and use it in GitHub Desktop.
Reset all tables sequence values in postgres with knex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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