diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2015-12-27 23:12:41 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2015-12-27 23:12:41 +0900 |
commit | bf79aa4fc14aeb2646331e767038acf0b77e9e7f (patch) | |
tree | ea732e021574697e7bf3b6495b0bc85192164d80 | |
parent | d5363e58135ea279f2a08c1a2d852ae2d11f0d65 (diff) | |
download | rails-bf79aa4fc14aeb2646331e767038acf0b77e9e7f.tar.gz rails-bf79aa4fc14aeb2646331e767038acf0b77e9e7f.tar.bz2 rails-bf79aa4fc14aeb2646331e767038acf0b77e9e7f.zip |
Improve `select_one` in `Mysql2Adapter`
Avoid instanciate `ActiveRecord::Result` and calling
`ActiveRecord::Result#hash_rows` for the performance.
-rw-r--r-- | activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb | 10 | ||||
-rw-r--r-- | activerecord/test/cases/adapters/mysql2/sp_test.rb | 6 |
2 files changed, 16 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index f4686b680c..7fbe2307c7 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -127,6 +127,16 @@ module ActiveRecord # execute(sql, name).map { |row| row.first } # 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) + execute(to_sql(arel, binds), name).each(as: :hash) do |row| + @connection.next_result while @connection.more_results? + return row + end + 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 = []) diff --git a/activerecord/test/cases/adapters/mysql2/sp_test.rb b/activerecord/test/cases/adapters/mysql2/sp_test.rb index cdaa2cca44..4197ba45f1 100644 --- a/activerecord/test/cases/adapters/mysql2/sp_test.rb +++ b/activerecord/test/cases/adapters/mysql2/sp_test.rb @@ -22,6 +22,12 @@ class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'" end + def test_multi_results_from_select_one + row = @connection.select_one('CALL topics(1);') + assert_equal 'David', row['author_name'] + assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_one'" + end + def test_multi_results_from_find_by_sql topics = Topic.find_by_sql 'CALL topics(3);' assert_equal 3, topics.size |