Raihan Gafur
Raihan Gafur

Reputation: 23

How to write setval() in TypeORM in NestJS?

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?

Upvotes: 2

Views: 168

Answers (1)

pzaenger
pzaenger

Reputation: 11994

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}"))`);

Upvotes: 1

Related Questions