Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a factory method to eliminate "results as hash" check #468

Merged
merged 1 commit into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -92,10 +92,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 @@ -175,4 +171,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