2

I have a Postgres database using Sequelize (node/express) as ORM. I have a table called students, in it there are columns: id and name.

In this students table, I have several registered students, but a detail: the last registered ID is 34550 and the first is 30000, they come from an import from a previous database, I need to continue counting from 34550, or that is, from the last registered student. However, when I register a student via API, the generated ID is below 30000. I know that in mysql the ID field being AUTO INCREMENT would solve it, however, as I understand it, postgres works in a different way.

How could I solve this problem?

The migration used to create the table is as follows:

    module.exports = {
    up: (queryInterface, Sequelize) => {
      return queryInterface.createTable('students', {
        id: {
          type: Sequelize.INTEGER,
          allowNull: false,
          autoIncrement: true,
          primaryKey: true,
        },
        name: {
          type: Sequelize.STRING,
          allowNull: false,
        },
      });
    },
  
    down: (queryInterface) => {
      return queryInterface.dropTable('students');
    },
  };

Table print:

enter image description here

1

2 Answers 2

1

Based on Frank comment, I was able to adjust using:

SELECT setval('public.students_id_seq', 34550, true);
Sign up to request clarification or add additional context in comments.

1 Comment

That sql may not work for all postgre versions. I found my ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH 111; variant here: stackoverflow.com/a/8750984/10099510
1

In my case (postgres:15.6) that query helped:

await sequelize.query(`ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH ${maxId};`);

Here is full migration code:

import {Migration, MigrationParams} from '../../../types/db.migrations';
import {SharedLogRecord} from '../../../types/db';
import fs from 'fs';

type SharedLogRecordFromSqlite = SharedLogRecord & {
  updatedAt: string;
  deletedAt: string;
};

export const up: Migration = async ({context: queryInterface}: MigrationParams) => {
  // 20_shared_logs.json
  const data: SharedLogRecordFromSqlite[] = JSON.parse(
      fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'),
  );

  let maxId: number = 0;
  data.forEach((record: SharedLogRecordFromSqlite) => {
    delete record.updatedAt;
    delete record.deletedAt;

    if (record.id > maxId) maxId = record.id;
  });
  maxId++;

  await queryInterface.bulkInsert('SharedLogs', data);
};

export const down: Migration = async () => {};

module.exports = {up, down};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.