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

Remove #select_one from Mysql2Adapter #25507

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
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,6 @@ def select_all(arel, name = nil, binds = [], preparable: nil)
result
end

# Returns a record hash with the column names as keys and column values
# as values.
def select_one(arel, name = nil, binds = [])
arel, binds = binds_from_relation(arel, binds)
@connection.query_options.merge!(as: :hash)
select_result(to_sql(arel, binds), name, binds) do |result|
@connection.next_result while @connection.more_results?
result.first
end
ensure
@connection.query_options.merge!(as: :array)
end

# Returns an array of arrays containing the field values.
# Order is the same as that returned by +columns+.
def select_rows(sql, name = nil, binds = [])
Expand Down
8 changes: 7 additions & 1 deletion activerecord/lib/active_record/result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,14 @@ def [](idx)
hash_rows[idx]
end

def first
return nil if @rows.empty?
Hash[@columns.zip(@rows.first)]
end

def last
hash_rows.last
return nil if @rows.empty?
Hash[@columns.zip(@rows.last)]
end

def cast_values(type_overrides = {}) # :nodoc:
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/result_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ def result
], result.to_hash
end

test "first returns first row as a hash" do
assert_equal(
{'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'}, result.first)
end

test "last returns last row as a hash" do
assert_equal(
{'col_1' => 'row 3 col 1', 'col_2' => 'row 3 col 2'}, result.last)
end

test "each with block returns row hashes" do
result.each do |row|
assert_equal ['col_1', 'col_2'], row.keys
Expand Down