findOrCreate, transactions and hooks

549 views
Skip to first unread message

Mark Lester

unread,
May 14, 2016, 9:43:40 AM5/14/16
to Sequelize
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.

Mark Lester

unread,
May 15, 2016, 5:19:23 AM5/15/16
to Sequelize
so I made a transaction to pass to findOrCreate, and fixed up any missing passing of options, and we are almost good.
I also installed this global namespace stuff but not sure I got that working.

But now I have  strangeness in that only certain fields are being saved in one of these tables, but thats doubtless me.
In short, I am good.

Mark Lester

unread,
May 15, 2016, 2:12:25 PM5/15/16
to Sequelize
I got it working in the end, I need to go
 {transaction:options.transaction}

a lot. if I just throw options about you end up with weird errors as field lists are already set up. hence my saves saving some commonly named fields, and not other stuff.
but all in all, thank you for findOrCreate.

Reply all
Reply to author
Forward
0 new messages