Skip to content

Commit 25862b3

Browse files
authored
[ruby/sinatra-sequel] Use batch update for postgres (#9127)
1 parent 4398d2c commit 25862b3

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

frameworks/Ruby/sinatra-sequel/boot.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,21 @@ def connect(dbtype)
6262
# Define ORM models
6363
class World < Sequel::Model(:World)
6464
def_column_alias(:randomnumber, :randomNumber) if DB.database_type == :mysql
65+
66+
def self.batch_update(worlds)
67+
if DB.database_type == :mysql
68+
worlds.map(&:save_changes)
69+
else
70+
ids = []
71+
sql = String.new("UPDATE world SET randomnumber = CASE id ")
72+
worlds.each do |world|
73+
sql << "when #{world.id} then #{world.randomnumber} "
74+
ids << world.id
75+
end
76+
sql << "ELSE randomnumber END WHERE id IN ( #{ids.join(',')})"
77+
DB.run(sql)
78+
end
79+
end
6580
end
6681

6782
class Fortune < Sequel::Model(:Fortune)

frameworks/Ruby/sinatra-sequel/hello_world.rb

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,18 @@ def rand1
7878

7979
# Test type 5: Database updates
8080
get '/updates' do
81-
worlds =
82-
DB.synchronize do
81+
worlds = nil
82+
DB.synchronize do
83+
worlds =
8384
ALL_IDS.sample(bounded_queries).map do |id|
8485
world = World.with_pk(id)
8586
new_value = rand1
8687
new_value = rand1 while new_value == world.randomnumber
87-
world.update(randomnumber: new_value)
88+
world.randomnumber = new_value
8889
world
8990
end
90-
end
91+
World.batch_update(worlds)
92+
end
9193

9294
json worlds.map!(&:values)
9395
end

0 commit comments

Comments
 (0)