Skip to content

Commit 1e58ffd

Browse files
committed
Merge pull request rails#25507 from bquorning/optimize-for-first-result-and-remove-mysql-select_one
Remove #select_one from Mysql2Adapter
1 parent bdd2eee commit 1e58ffd

File tree

3 files changed

+17
-14
lines changed

3 files changed

+17
-14
lines changed

activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,6 @@ def select_all(arel, name = nil, binds = [], preparable: nil)
1313
result
1414
end
1515

16-
# Returns a record hash with the column names as keys and column values
17-
# as values.
18-
def select_one(arel, name = nil, binds = [])
19-
arel, binds = binds_from_relation(arel, binds)
20-
@connection.query_options.merge!(as: :hash)
21-
select_result(to_sql(arel, binds), name, binds) do |result|
22-
@connection.next_result while @connection.more_results?
23-
result.first
24-
end
25-
ensure
26-
@connection.query_options.merge!(as: :array)
27-
end
28-
2916
# Returns an array of arrays containing the field values.
3017
# Order is the same as that returned by +columns+.
3118
def select_rows(sql, name = nil, binds = [])

activerecord/lib/active_record/result.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,14 @@ def [](idx)
7575
hash_rows[idx]
7676
end
7777

78+
def first
79+
return nil if @rows.empty?
80+
Hash[@columns.zip(@rows.first)]
81+
end
82+
7883
def last
79-
hash_rows.last
84+
return nil if @rows.empty?
85+
Hash[@columns.zip(@rows.last)]
8086
end
8187

8288
def cast_values(type_overrides = {}) # :nodoc:

activerecord/test/cases/result_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,16 @@ def result
2222
], result.to_hash
2323
end
2424

25+
test "first returns first row as a hash" do
26+
assert_equal(
27+
{'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'}, result.first)
28+
end
29+
30+
test "last returns last row as a hash" do
31+
assert_equal(
32+
{'col_1' => 'row 3 col 1', 'col_2' => 'row 3 col 2'}, result.last)
33+
end
34+
2535
test "each with block returns row hashes" do
2636
result.each do |row|
2737
assert_equal ['col_1', 'col_2'], row.keys

0 commit comments

Comments
 (0)