There's a sequelize function that allows to increment a value by a number, that number can be negative to decrement, I would like to make sure that that column is always positive or 0, so I added a validator to my model:
module.exports = function (sequelize, DataTypes) {
var ProductVariant = sequelize.define('ProductVariant', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
ProductId: {
type: DataTypes.STRING(45),
field: 'product_id',
allowNull: false,
primaryKey: true,
references: {
model: 'product',
key: 'id'
}
},
image: {
type: DataTypes.INTEGER(11),
allowNull: true
},
price: {
type: DataTypes.DECIMAL(6, 2),
allowNull: false
},
qty_stock: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0
},
createdAt: {
type: 'TIMESTAMP',
allowNull: true,
field: 'creation_date'
},
updatedAt: {
type: 'TIMESTAMP',
field: 'last_updated',
allowNull: true
},
},
{
tableName: 'variants',
hooks: {
beforeValidate: function(variant, options) {
if (variant.qty_assigned < 0) {
throw new Error('Not valid');
}
}
}
});
ProductVariant.associate = function (models) {
ProductVariant.belongsTo(models.Product)
},
{
indexes:
[{
unique: true,
fields: ['product_id']
}]
}
return ProductVariant;
};
But when I do:
await ProductVariant.increment({ qty_assigned: -100 }, {
where: { id: { [Op.eq]: variantId } },
transaction: t
});
I works and updates the value without checking validation. I also tried with:
qty_stock: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: 0,
validate: {
min: 0
}
}
Is it possible that is has to do with the fact that increment is done in database? can I do something to add a validation?
Validation is done against an instance (in your app) and not against the DB.
The increment API is special as it updates the value directly in the database and not on the instance
From https://sequelize.org/master/class/lib/model.js~Model.html#static-method-increment (emphasis mine)
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a SET column = column + X WHERE foo = 'bar' query. To get the correct value after an increment into the Instance you should do a reload.
If you want to increment and get validation done, you can:
use a transaction (or optimistic locking) and update manually increment the value of the instance (use sequelize validation)
add a check in the DB (mysql8+: https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html).
Related
i am new to sequelize, i have a user table , address table and address type table as given below.
A user can have 2 a different address , permanent and current address, and the type of address (permanent or current ) is specified in the table address type.
I have tried to access the data from mapping table (address_type) in the resolver based on schema and set hasMany relation from user -> address table , but graphql shows association not found error.
How can we get the relation properly in order to get the mapping address type name.
type User{
id:Int
name:String
}
type Address {
id: ID!
user_id:Int
city: String
addr_type:AddressType
}
type AddressType{
id : Int
name:String (permanent|current)
}
table definition
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.INTEGER, allowNull: false,
},
}, {
tableName: 'user',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
addr_type: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
city: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address_types', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address_type',
timestamps: false
});
};
relationship
db.user.hasMany(db.address,{foreignKey: 'user_id'});
db.address.belongsTo(db.user,{foreignKey: 'user_id'});
db.address.belongsTo(db.address_types,{foreignKey: 'addr_type'});
resolver code
userts: async (obj, args, context, info ) => User.findAll( {
where: { user_status: 1 },
,
raw: true,
nest: true,
} ).then(userts => {
const response = userts.map(usert => {
return{
// i have 15 fields for a user, if i can access the schema of the corresponsing resolver i can dynamically build the response out put
id: usert.id,
firstName: usert.firstName,
lastName: usert.lastName,
middleName: usert.middleName,
}
})
return response;
}),
You should turn off the option raw in order to get associated objects and use the include option to indicate what associated models you wish to load.
User.findAll( {
where: { user_status: 1 },
include: [{
model: Address,
include: AddressType
}],
raw: false,
nest: true,
}
I'm using sequelize 4.32 and I was trying to write a self-association in one of the tables, I'm not sure if there is something else that I need to do to solve this relation, my goal is to get all the records in my table and include all the records associated with each one
this is the error that I'm getting in the console:
You have used the alias adjucent_stands in two separate associations. Aliased associations must have unique aliases
below you'll find my model:
module.exports = (sequelize, DataTypes) => {
const stands = sequelize.define('stands', {
id: {
type: DataTypes.INTEGER,
unique: true,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
field: 'name',
unique: {
args: true,
msg: 'Name already exists ',
},
},
location: {
type: DataTypes.JSON,
field: 'location',
},
remote: {
type: DataTypes.BOOLEAN,
field: 'remote',
defaultValue: false,
},
created_at: {
type: DataTypes.DATE(3),
defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),
},
updated_at: {
type: DataTypes.DATE(3),
defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),
},
}, { freezeTableName: true, timestamps: true, underscored: true });
stands.associate = (models) => {
stands.hasMany(stands, { as: 'adjucent_stands' });
};
return stands;
};
Specification for my conference instance method:
getParticipants() : Promise -> Participant array
Conference model:
return sequelize.define('conference', {
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
maxParticipants: {
type: Sequelize.INTEGER,
allowNull: false
},
fileShareSession: {
type: Sequelize.STRING,
defaultValue: null,
allowNull: true
},
startDate: {
type: Sequelize.DATE,
defaultValue: null,
allowNull: true
},
endDate: {
type: Sequelize.DATE,
defaultValue: null,
allowNull: true
},
state: {
type: Sequelize.ENUM(
ConferenceState.new,
ConferenceState.starting,
..
),
defaultValue: ConferenceState.new,
required: true,
allowNull: false
}
Participant model:
return sequelize.define('participant', {
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
displayName: {
type: Sequelize.STRING,
defaultValue: null,
allowNull: true
},
mediaResourceId: {
type: Sequelize.STRING,
defaultValue: null,
allowNull: true
},
screenSharingId: {
type: Sequelize.STRING,
defaultValue: null,
allowNull: true
},
mediaType: {
type: Sequelize.ENUM(
MediaType.AUDIO_VIDEO),
defaultValue: MediaType.AUDIO_VIDEO,
allowNull: false
},
state: {
type: Sequelize.ENUM(
ParticipantState.new,
ParticipantState.joining,
..
),
defaultValue: ParticipantState.new,
required: true,
allowNull: false
}
Question:
So can I do a participant.findAll in my conferencing instance model or not? When yes, do I get an Array back with a findAll?
I would have done it like that:
// getParticipants() : Promise -> Participant array
getParticipants() {
return new Promise((resolve, reject) => {
var Participant = sequelize.models.participant;
Participant.findAll({
where: {
id: id
}
}).then(function(participant) {
if (_.isObject(participant)) {
resolve(participant);
} else {
throw new ResourceNotFound(conference.name, {id: id});
}
}).catch(function(err) {
reject(err);
});
});
},
LAZY loading is implemented by sequelize when you make relationships between tables. You could make a relationship as follows:
var Conference = sequelize.define('conference', { ... });
var Participant = sequelize.define('participant', { ... });
Conference.belongsToMany(Participant, { through: 'ConferenceParticipants'});
Participant.belongsToMany(Conference, { through: 'ConferenceParticipants'});
Then you can implement EAGER loading when you query your database like:
// Obtain the participant list included in the original object (EAGER)
var conference =
Conference.findOne({
attributes: ['field1', 'field2', ...],
where: {title: 'Conference A'},
includes: [{
attributes: ['field1', 'field2', ...],
model: Participant,
through: { model: 'ConferenceParticipants'} // You have to name the join table
}]
})
.then(function(conference) {
// Here you will have the conference with the list of participants
});
If you want to use LAZY loading, sequelize implement it for you, you just need to call below methods:
// Obtain the participant LAZY
conference.getParticipants().then(function(participants) {
// participants is an array of participant
})
// You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method.
conference.getParticipants({ where: 'id > 10' }).then(function(participants) {
// participants with an id greater than 10 :)
})
// You can also only retrieve certain fields of a associated object.
conference.getParticipants({attributes: ['title']}).then(function(participants) {
// retrieve participants with the attributes "title" and "id"
})
You can get a reference to sequelize relationship implementation in next document.
I use Sequelize to communicate with my postgres database. I want to use the upsert functionality, but with custom where clause. For example I have this model for volunteers location
module.exports = function (sequelize, DataTypes) {
var volunteer_location = sequelize.define('volunteer_location', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
deviceId: {
allowNull: false,
type: Sequelize.STRING
},
latitude: {
allowNull: false,
type: Sequelize.DECIMAL(18, 14)
},
longitude: {
allowNull: false,
type: Sequelize.DECIMAL(18, 14)
},
city: {
allowNull: false,
type: Sequelize.STRING(90)
},
state: {
type: Sequelize.STRING(90)
},
postalCode: {
type: Sequelize.STRING(16)
},
country: {
allowNull: false,
type: Sequelize.STRING(70)
}
}, {
instanceMethods: {
insertOrUpdate: function (requestBody, res) {
volunteer_location.upsert(requestBody).then(function () {
res.sendStatus(200);
});
}
}
});
return volunteer_location;
};
In the insertOrUpdate method I try to use the upsert by giving a json like
location = {
deviceId: req.body.deviceId,
latitude: req.body.latitude,
longitude: req.body.longitude,
city: req.body.city,
state: req.body.state,
postalCode: req.body.postalCode,
country: req.body.country,
volunteer: req.decoded.id
};
where volunteer is a foreign key from table users.
Now the executing says:
CREATE OR REPLACE FUNCTION pg_temp.sequelize_upsert() RETURNS integer
AS $func$ BEGIN INSERT INTO "volunteer_locations" some values RETURN
1; EXCEPTION WHEN unique_violation THEN UPDATE "volunteer_locations"
SET some values WHERE (("id" IS NULL AND "volunteer" = 1));
RETURN 2; END; $func$ LANGUAGE plpgsql; SELECT * FROM
pg_temp.sequelize_upsert();
id and volunteer is a set of primary keys. I want to change the WHERE clause on the UPDATE by checking only the volunteer value, because I don't know the value of the id.
Is this possible? Or I have to use
findOne(...).then(function () {
//update
});
EDIT
I set volunteer with the attribute unique: true and it replaced the where clause with WHERE (("id" IS NULL AND "volunteer" = 1) OR "volunteer" = 1);, which means that the update works. But I don't know if this is very efficient. If anyone knows a better solution please let me know.
i don't know if this is possible, there are 2 models which are associated through relation, and models are defined this way:
sequelize.define('account_has_plan', {
account_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'account',
key: 'id'
}
},
plan_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'plan',
key: 'id'
}
},
type_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
references: {
model: 'type',
key: 'id'
}
},
create_at: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: 'CURRENT_TIMESTAMP'
},
update_at: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: 'CURRENT_TIMESTAMP'
}
}, {
tableName: 'account_has_plan',
underscored: true,
freezeTableName: true,
timestamps: false
});
sequelize.define('type', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
element: {
type: DataTypes.ENUM('Meal','Workout','Status'),
allowNull: false
}
}, {
tableName: 'type',
freezeTableName: true,
timestamps: false
});
the code on which calls the models and execute the query to DB is this:
var model = $.loadModel("account_has_plan");
var type = $.loadModel("type");
model.belongsTo(type);
var query = {
where: {
account_id: $.params.accountId
},
limit: $.query.limit || 12,
offset: $.query.offset || 0,
attributes:["account_id"],
include: [{
model: type
}]
};
model.findAll(query)
.then(function(data){
$.data = data;
$.json();
})
.catch(function(err){
console.log(err);
errorHandler.throwStatus(500, $);
});
this way the data from the server responds like this:
{
"account_id": 1,
"type": {
"id": 2,
"name": "Arms",
"element": "Workout"
}
}
there is actually no problem with this data, but i am forced to follow a pattern from docs i was provided with, which the difference there is that type is actually a string value rather than object value as presented in the example, so in the end the data structure i try to get has to be like this:
{
"account_id": 1,
"type": "Arms"
}
i have actually how idea on how to achieve this, i know i have little practice with sequelize, maybe this has to be defined through a model method or using through in the reference (which i have tried but returns error)
but the point is.. i need to know if it can be possible before i have to report a change on the REST documentation which is big
First of all, since what you'll be getting through a sequelize query are instances, you need to convert it to "plain" object. You could do that by using a module called sequelize-values.
Then you should be able to manually map the value to the one you're looking for.
model.findAll(query)
.then(function(data){
return data.map(function(d){
var rawValue = d.getValues();
rawValue.type = rawValue.type.name;
return rawValue;
});
})
.then(function(data){
$.data = data;
$.json();
})
.catch(function(err){
console.log(err);
errorHandler.throwStatus(500, $);
});