Skip to content

Instantly share code, notes, and snippets.

@GarryOne
Last active November 24, 2022 13:46
Show Gist options
  • Save GarryOne/eabdb5704887c2d1cafd3cb1ebc7fb5e to your computer and use it in GitHub Desktop.
Save GarryOne/eabdb5704887c2d1cafd3cb1ebc7fb5e to your computer and use it in GitHub Desktop.
Node Postgres Fix Table IDENTITY seq / autoincrement / nextval
const pg = require('pg');
const { Client } = pg;
const updateTables = async () => {
const client = new Client({
connectionString:
'postgresql://cysiamadmin@rav-ravhe7-db:JraWQiOiJ4Um@rav-ravhe7-db.postgres.database.azure.com:5432/postgres?schema=public',
ssl: {
rejectUnauthorized: false,
},
});
await client.connect();
console.log('Connected');
const execQuery = async (queryStr, params = []) => {
return new Promise((resolve, reject) => {
client.query(queryStr, params, (error, results) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
});
};
const tablesRes = await execQuery(`
SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public';
`);
const tables = tablesRes.rows.map((row) => row.table_name);
await Promise.all(
tables.map(async (tableName) => {
let lastId;
try {
const res = await execQuery(
`SELECT id from "${tableName}" ORDER BY id DESC LIMIT 1`,
);
lastId = res.rows[0].id;
} catch (e) {
console.log(`[Failed] on ${tableName}`);
}
if (lastId) {
const nextId = lastId + 1;
const queryStr = `ALTER SEQUENCE "${tableName}_id_seq" RESTART WITH ${nextId}`;
try {
await execQuery(queryStr);
} catch (e) {
console.log(`[Failed] on ${tableName}`);
}
console.log(tableName, queryStr);
}
}),
);
process.exit();
};
updateTables();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment