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 ?
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')
}
};
nextVal() does?Currently there is no way in sequelize to do so, kindly refer
I was able to do something similar as posted by @sebin and chaining the promise to my model.create(), like so:
this.sequelize
.query("SELECT max(cust_no) + 1 as 'custNo' from employees.customers", {
type: this.sequelize.Sequelize.QueryTypes.SELECT
})
.then(results => {
return results[0];
})
.then(nextPk => {
const values = Object.assign({}, newCustomer, nextPk);
return customersModel.create(values);
})
.then(newRecord => {
console.log('newRecord:', newRecord);
});
In the above case I use max +1 but the solution applies to your sequence all the same.
This works perfectly with MSSQL / MariaDB
Sequelize.literal in the "defaultValue" was the key. I'm new to Sequelize, and luckily it lets me redefine the "id" field, which normally doesn't have to be specified in the model. Happy day for me.
module.exports = (sequelize, Sequelize) => {
const People = sequelize.define("people", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
defaultValue: sequelize.Sequelize.literal("NEXT VALUE FOR dbo.BAS_IDGEN_SEQ")
},...