Skip to content

Commit

Permalink
Merge pull request #468 from sparklemotion/stop-checking-hash
Browse files Browse the repository at this point in the history
Use a factory method to eliminate "results as hash" check
  • Loading branch information
tenderlove committed Jan 10, 2024
2 parents f1afbb8 + c1fc1af commit 21db633
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 8 deletions.
13 changes: 12 additions & 1 deletion lib/sqlite3/database.rb
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def execute sql, bind_vars = [], *args, &block

prepare(sql) do |stmt|
stmt.bind_params(bind_vars)
stmt = ResultSet.new self, stmt
stmt = build_result_set stmt

if block
stmt.each do |row|
Expand Down Expand Up @@ -746,6 +746,17 @@ def translate_from_db types, row
@type_translator.call types, row
end

# Given a statement, return a result set.
# This is not intended for general consumption
# :nodoc:
def build_result_set stmt
if results_as_hash
HashResultSet.new(self, stmt)
else
ResultSet.new(self, stmt)
end
end

private

NULL_TRANSLATOR = lambda { |_, row| row }
Expand Down
8 changes: 4 additions & 4 deletions lib/sqlite3/resultset.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@ def eof?
# For hashes, the column names are the keys of the hash, and the column
# types are accessible via the +types+ property.
def next
if @db.results_as_hash
return next_hash
end

row = @stmt.step
return nil if @stmt.done?

Expand Down Expand Up @@ -174,4 +170,8 @@ def next_hash
row
end
end

class HashResultSet < ResultSet # :nodoc:
alias :next :next_hash
end
end
6 changes: 3 additions & 3 deletions lib/sqlite3/statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ def execute(*bind_vars)
reset! if active? || done?

bind_params(*bind_vars) unless bind_vars.empty?
@results = ResultSet.new(@connection, self)
results = @connection.build_result_set self

step if column_count == 0

yield @results if block_given?
@results
yield results if block_given?
results
end

# Execute the statement. If no block was given, this returns an array of
Expand Down
1 change: 1 addition & 0 deletions test/test_integration_resultset.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def test_real_translation

def test_next_results_as_hash
@db.results_as_hash = true
@result = @stmt.execute
@result.reset(1)
hash = @result.next
assert_equal({"a" => 1, "b" => "foo"},
Expand Down

0 comments on commit 21db633

Please sign in to comment.