Skip to content

Commit c1fc1af

Browse files
committed
Use a factory method to eliminate "results as hash" check
"Results as hash" should be set on the database, so we should only need to check it once when we first start the query. This patch pulls result set construction in to a factory method on the database object. Doing this eliminates a "translate to hash" check that is performed on every row fetch.
1 parent f54bbc9 commit c1fc1af

File tree

4 files changed

+20
-8
lines changed

4 files changed

+20
-8
lines changed

lib/sqlite3/database.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def execute sql, bind_vars = [], *args, &block
224224

225225
prepare(sql) do |stmt|
226226
stmt.bind_params(bind_vars)
227-
stmt = ResultSet.new self, stmt
227+
stmt = build_result_set stmt
228228

229229
if block
230230
stmt.each do |row|
@@ -746,6 +746,17 @@ def translate_from_db types, row
746746
@type_translator.call types, row
747747
end
748748

749+
# Given a statement, return a result set.
750+
# This is not intended for general consumption
751+
# :nodoc:
752+
def build_result_set stmt
753+
if results_as_hash
754+
HashResultSet.new(self, stmt)
755+
else
756+
ResultSet.new(self, stmt)
757+
end
758+
end
759+
749760
private
750761

751762
NULL_TRANSLATOR = lambda { |_, row| row }

lib/sqlite3/resultset.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,6 @@ def eof?
9292
# For hashes, the column names are the keys of the hash, and the column
9393
# types are accessible via the +types+ property.
9494
def next
95-
if @db.results_as_hash
96-
return next_hash
97-
end
98-
9995
row = @stmt.step
10096
return nil if @stmt.done?
10197

@@ -175,4 +171,8 @@ def next_hash
175171
row
176172
end
177173
end
174+
175+
class HashResultSet < ResultSet # :nodoc:
176+
alias :next :next_hash
177+
end
178178
end

lib/sqlite3/statement.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,12 @@ def execute(*bind_vars)
7979
reset! if active? || done?
8080

8181
bind_params(*bind_vars) unless bind_vars.empty?
82-
@results = ResultSet.new(@connection, self)
82+
results = @connection.build_result_set self
8383

8484
step if column_count == 0
8585

86-
yield @results if block_given?
87-
@results
86+
yield results if block_given?
87+
results
8888
end
8989

9090
# Execute the statement. If no block was given, this returns an array of

test/test_integration_resultset.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ def test_real_translation
9797

9898
def test_next_results_as_hash
9999
@db.results_as_hash = true
100+
@result = @stmt.execute
100101
@result.reset(1)
101102
hash = @result.next
102103
assert_equal({"a" => 1, "b" => "foo"},

0 commit comments

Comments
 (0)