Skip to content

Commit 635f068

Browse files
authored
[ruby/roda] Use batch update for Roda on postgres (#9126)
1 parent 25862b3 commit 635f068

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

frameworks/Ruby/roda-sequel/boot.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,21 @@ def connect(dbtype)
7373
# Define ORM models
7474
class World < Sequel.Model(:World)
7575
def_column_alias(:randomnumber, :randomNumber) if DB.database_type == :mysql
76+
77+
def self.batch_update(worlds)
78+
if DB.database_type == :mysql
79+
worlds.map(&:save_changes)
80+
else
81+
ids = []
82+
sql = String.new("UPDATE world SET randomnumber = CASE id ")
83+
worlds.each do |world|
84+
sql << "when #{world.id} then #{world.randomnumber} "
85+
ids << world.id
86+
end
87+
sql << "ELSE randomnumber END WHERE id IN ( #{ids.join(',')})"
88+
DB.run(sql)
89+
end
90+
end
7691
end
7792

7893
class Fortune < Sequel.Model(:Fortune)

frameworks/Ruby/roda-sequel/hello_world.rb

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,19 @@ def rand1
5858
# Test type 5: Database updates
5959
r.is "updates" do
6060
response[CONTENT_TYPE] = JSON_TYPE
61-
worlds =
62-
DB.synchronize do
61+
worlds = []
62+
DB.synchronize do
63+
worlds =
6364
ALL_IDS.sample(bounded_queries).map do |id|
6465
world = World.with_pk(id)
6566
new_value = rand1
6667
new_value = rand1 while new_value == world.randomnumber
67-
world.update(randomnumber: new_value)
68-
world.values
68+
world.randomnumber = new_value
69+
world
6970
end
70-
end
71-
worlds.to_json
71+
World.batch_update(worlds)
72+
end
73+
worlds.map(&:values).to_json
7274
end
7375

7476
# Test type 6: Plaintext

0 commit comments

Comments
 (0)