Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding auto incrementing integer with a starting value in Sequelize

After some research I don't seem to be able to find a great approach doing following:

I wan't to add a new column, to an existing table, that should be an auto incrementing integer, starting with the value of 1000.

My migration file is for now simple and obvious:

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return Promise.all([
      queryInterface.addColumn(
        'Orders',
        'orderRef',
        {
          autoIncrement: true,
          type: Sequelize.INTEGER
        }
      )
    ])
  },

  down: {...
  }
};

So this adds the column to the table unproblematic. But I don't seem to be able to find a great approach to set the value to start at 1000 and increment from there.

I know I could run a query like ALTER TABLE Orders AUTO_INCREMENT = 1000; but I would very much appreciate to keep it in Sequelize.

I'm using a PostgreSQL database and Sequelize version 4.38.1.

Does anyone know a nice way around this issue?

like image 796
crellee Avatar asked Jan 02 '19 11:01

crellee


People also ask

Can you set auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Does Sequelize automatically add an ID?

Sequelize will assume your table has a id primary key property by default.

Can auto increment not primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.


1 Answers

It is already present in Sequelize. There is an option called initialAutoIncrement. This sets the initial AUTO_INCREMENT value for the table in MySQL.

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    'User',
    {
      id: {
        type: DataTypes.BIGINT(20),
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: DataTypes.STRING(500),
        allowNull: false,
      },
    },
    {
      initialAutoIncrement: 1000,
    }
  );

  return User;
};
like image 115
Robinson De La Cruz Avatar answered Sep 21 '22 23:09

Robinson De La Cruz