How to write setval() in TypeORM in NestJS?

Viewed 75

I am using TypeORM and PostgreSQL in NestJS and I am facing a problem called error: duplicate key value violates unique constraint "message_pkey". I have searched and found out it's a common problem in PostgreSQL, but to solve this problem, I have to write this query:

SELECT setval('TABLENAME_id_seq', (SELECT MAX(id) FROM "TABLENAME"));
// Change TABLENAME with your table

But I can't find how to write this in TypeORM or query builder in NestJS?

1 Answers

Maybe a raw SQL query is a possible solution:

import { getManager } from 'typeorm';

const table = 'tablename';
await getManager().query(`SELECT setval('${table}_id_seq', (SELECT MAX(id) FROM "${table}"))`);
Related