2

I have a Datamapper model, say XYZ. Now, There are multiple threads which, at times, read a row using this model and attempt to update the same row - only one should should succeed, depending on a property of XYZ, say abc

class XYZ
include DataMapper::Resource
property :id # primary key
property :abc
end

Now:

obj = XYZ.get(some_id)
obj.update(abc: 10) # Assume abc column value was 5 earlier

This may happen in several threads, and may happen simultaneously. Also, the new value for column abc is different in each thread. Once, when a thread updates abc, others should not. Essentially what I am trying to do is to run this query via datamapper:

UPDATE `xyz` SET `abc` = 20 WHERE `id` = <some id> AND `abc` = 5

the model.update function does not allows to update an attribute and put a condition of that attribute simultaneously. I know I can run an SQL query directly; but is there any other way?

constantine1
  • 397
  • 1
  • 2
  • 12

1 Answers1

0

I would do something like this:

XYZ.all( :id => some_id, :abc => 5 ).update( :abc => 20 )
Neil Slater
  • 25,116
  • 5
  • 71
  • 90
  • That would result in two db queries - one `select`, and then `update`. The problem I am trying to solve is of concurrency - where all threads read the same data at the same time and then almost immediately try to update it (yeah, I know it should be a race condition, but it is happening). What I want to have the condition in SQL query itself, so that concurrency problem would get resolved in all cases. – constantine1 Sep 06 '13 at 07:56
  • ah, my bad, I've got used to Sequel, where there would be one query for this kind of construct. This may also be possible in DataMapper, will have a think – Neil Slater Sep 06 '13 at 08:00
  • Not an answer, but I just found this useful to confirm what DataMapper was doing: http://stackoverflow.com/questions/1619028/automatic-logging-of-datamapper-queries – Neil Slater Sep 06 '13 at 08:13
  • Yeah, I can see all the DM queries (using Padrino framework logger with DM). I went through DM code and finally cave in - put native SQL query :( Thanks for the answers though.... – constantine1 Sep 06 '13 at 09:15