Skip to content

Commit 0641461

Browse files
committed
Optimize Model.as_set calls to avoid queries in the static_cache plugin
1 parent c8f003b commit 0641461

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

CHANGELOG

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
=== master
22

3+
* Optimize Model.as_set calls to avoid queries in the static_cache plugin (jeremyevans)
4+
35
* Support filtering by associations with sets in the pg_array_associations plugin (jeremyevans)
46

57
* Support sets in the to_dot extension (jeremyevans)

lib/sequel/plugins/static_cache.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,19 @@ def as_hash(key_column = nil, value_column = nil, opts = OPTS)
176176
h
177177
end
178178

179+
# Use the cache instead of a query to get the results.
180+
def as_set(column)
181+
set = Set.new
182+
183+
if column.is_a?(Array)
184+
@all.each{|r| set.add(r.values.values_at(*column))}
185+
else
186+
@all.each{|r| set.add(r[column])}
187+
end
188+
189+
set
190+
end
191+
179192
# Alias of as_hash for backwards compatibility.
180193
def to_hash(*a)
181194
as_hash(*a)

spec/extensions/static_cache_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,13 @@
132132
proc{@c.map(:id){}}.must_raise(Sequel::Error)
133133
end
134134

135+
it "should have as_set not send a query" do
136+
@c.as_set(:id).must_equal Set[1, 2]
137+
@db.sqls.must_equal []
138+
@c.as_set([:id,:id]).must_equal Set[[1,1], [2,2]]
139+
@db.sqls.must_equal []
140+
end
141+
135142
it "should have other enumerable methods work without sending a query" do
136143
a = @c.sort_by{|o| o.id}
137144
a.first.must_equal @c1

0 commit comments

Comments
 (0)