Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Postgresql Sequence Nextval in SequelizeJS

How can i define sequence nextval() in sequelizeJS Model.

Is there any predefined function available for nextval() in sequelizeJS ?,

Is there any possiblity to write sequence nextval() custom function inside sequelize define model ?

like image 365
Kalaiselvan M Avatar asked Feb 28 '17 06:02

Kalaiselvan M


People also ask

Can we create sequence in PostgreSQL?

CREATE SEQUENCE creates a new sequence number generator. This involves creating and initializing a new special single-row table with the name name . The generator will be owned by the user issuing the command. If a schema name is given then the sequence is created in the specified schema.


3 Answers

Currently there is no way in sequelize to do so, kindly refer

https://github.com/sequelize/sequelize/issues/3555

like image 159
Keval Gohil Avatar answered Oct 23 '22 22:10

Keval Gohil


No predefined function for that. But you can make use of raw query and get nextval like

sequelize.query("SELECT nextval('sequence')", { 
 type: collection.Sequelize.QueryTypes.SELECT 
});
like image 27
sebin Avatar answered Oct 23 '22 20:10

sebin


In case there is someone at this point who wants to do this as well, the best way to do it I guess is using Sequelize.literal:

// on your model

const model = sequelize.define("model", {
  ...attributes,
  customSequence: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: sequelize.Sequelize.literal("nextval('custom_sequence')")
  },
})

// after create a migration for your new column

module.exports = {
  up: async (queryInterface, sequelize) => {
    await queryInterface.sequelize.query("CREATE SEQUENCE custom_sequence start 1020 increment 20",)

    await queryInterface.addColumn('table', 'customSequence', {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: sequelize.Sequelize.literal("nextval('custom_sequence')")
    })
  },

  down: async (queryInterface, sequelize) => {
    await queryInterface.sequelize.query('DROP SEQUENCE custom_sequence')
    await queryInterface.removeColumn('table', 'customSequence')
  }
};
like image 1
Elias Rodelo Avatar answered Oct 23 '22 22:10

Elias Rodelo