Mario
Mario

Reputation: 4988

How to increment serial id after having received id values manually?

I am in the process of migrating data from mysql to postgres. To this end I have exported mysql tables to .json files which I then process using node-postgres so that the data conforms to the new model defined in postgres. In this process when I make an insert to postgres of every table I include the id.

Here an example

const query = {
    text: `INSERT INTO public.table ( id, name ) VALUES ( $1, $2 )`,
    values: [id, name],
};

try {
    await connection.query(query);
} catch (error) {
    console.error(error.message);
}

All good up to here. The scenario I have now is that in the context of the new application when creating a record the id value is not increased. I read about it and understand it is the case described in this post

The backend of the application is implemented in typeorm. My question is how in the context of typeorm I can execute the directives ALTER SEQUENCE or setval() suggested in the previous answer

I will appreciate some guidance if I am misinterpreting the solution of the problem

I attach an example of the definition of one of the entities and table

@Entity()
export class SomeName {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

In database context id is declared as serial

Upvotes: 0

Views: 1502

Answers (1)

Mario
Mario

Reputation: 4988

I got to solve this problem following this answer https://stackoverflow.com/a/3698777/615274

Basically

First check

select max(id) from public.user; -- 35

select nextval('user_id_seq'); -- 5

The solution

SELECT setval('user_id_seq', max(id)) FROM user;

I need to do this on every table sequence

If I have missed something relevant, I appreciate comments

Upvotes: 1

Related Questions