Skip to content
Browse files

Use show create table.

Conflicts:

	activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
  • Loading branch information...
1 parent 47bc206 commit 8d55a6d4e8e79723b0dabb2f3375158488ccf456 @kennyj kennyj committed with jonleighton Nov 22, 2011
View
5 activerecord/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 3.1.4 (unreleased) ##
+* Perf fix: MySQL primary key lookup was still slow for very large
+ tables. *GH 3678*
+
+ *Kenny J*
+
* Perf fix: If a table has no primary key, don't repeatedly ask the database for it.
*Julius de Bruijn*
View
13 activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -572,12 +572,15 @@ def show_variable(name)
# Returns a table's primary key and belonging sequence.
def pk_and_sequence_for(table)
- keys = []
- result = execute("SHOW INDEX FROM #{quote_table_name(table)} WHERE Key_name = 'PRIMARY'", 'SCHEMA')
- result.each(:symbolize_keys => true, :as => :hash) do |row|
- keys << row[:Column_name]
+ result = execute("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA')
+ create_table = result.first[1]
+
+ if create_table.to_s =~ /PRIMARY KEY\s+\((.+)\)/
+ keys = $1.split(",").map { |key| key.gsub(/`/, "") }
+ keys.length == 1 ? [keys.first, nil] : nil
+ else
+ nil
end
- keys.length == 1 ? [keys.first, nil] : nil
end
# Returns just a table's primary key
View
15 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -755,13 +755,16 @@ def show_variable(name)
# Returns a table's primary key and belonging sequence.
def pk_and_sequence_for(table) #:nodoc:
- keys = []
- result = execute("SHOW INDEX FROM #{quote_table_name(table)} WHERE Key_name = 'PRIMARY'", 'SCHEMA')
- result.each_hash do |h|
- keys << h["Column_name"]
- end
+ result = execute("SHOW CREATE TABLE #{quote_table_name(table)}", 'SCHEMA')
+ create_table = result.fetch_hash["Create Table"]
result.free
- keys.length == 1 ? [keys.first, nil] : nil
+
+ if create_table.to_s =~ /PRIMARY KEY\s+\((.+)\)/
+ keys = $1.split(",").map { |key| key.gsub(/`/, "") }
+ keys.length == 1 ? [keys.first, nil] : nil
+ else
+ nil
+ end
end
# Returns just a table's primary key

0 comments on commit 8d55a6d

Please sign in to comment.
Something went wrong with that request. Please try again.