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 ?
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.
Currently there is no way in sequelize to do so, kindly refer
https://github.com/sequelize/sequelize/issues/3555
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
});
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')
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With