I have this method for managing sequences. i has to manipulate the set of sequences (e.g. the points on a polyline) and increment any above the point you want to insert at.
sequenceManage:function(record,offset){
var self=this;
var o=record.$modelOptions.Options;
var tableName=record.$modelOptions.name.plural;
var query = "UPDATE "+tableName+
" SET "+o.sequenceName+" = "+o.sequenceName+"+"+offset+
" WHERE "+o.sequenceName +" >= "+record[o.sequenceName]+
" AND "+o.sequenceName+" IS NOT NULL ";
_.each(o.sequenceIndexes,function(seqIndex){
query+=" AND "+seqIndex+"="+record[seqIndex];
});
return this.sequelize.query(query);
},
which I call from an afterCreate hook thus
model.hook("afterCreate",function(record, options) {
var self=this;
return this.sequenceMax(record)
.then(function(maxSequence){
if (!record.sequence)
record.sequence=maxSequence;
record.sequence=Math.min(record.sequence,maxSequence);
return self.sequenceManage(record,1)
});
});
all was good, until I started using findOrCreate which of course kicks off a transaction between the find and the create locking that table. which is all good, except for the lockers own hook callbacks.
Any hints on how I unravel this, other than of course going
find(...).then(function(m){if(!m)return this.create(...);})
i want the transaction, i guess I could do that myself as i know the entry point, though that’s obviously limited/crappy.
How do you get findOrCreate not to get hung up when running hooks that manipulate the target table.