cache column defaults for AR object instantiation

This commit is contained in:
Aaron Patterson
2011-06-27 17:45:34 -07:00
parent b927f0a894
commit 2fe088a53d
3 changed files with 16 additions and 3 deletions

View File

@@ -710,6 +710,12 @@ module ActiveRecord #:nodoc:
connection_pool.columns_hash[table_name]
end
# Returns a hash where the keys are column names and the values are
# default values when instantiating the AR object for this table.
def column_defaults
connection_pool.column_defaults[table_name]
end
# Returns an array of column names as strings.
def column_names
@column_names ||= columns.map { |column| column.name }

View File

@@ -60,6 +60,7 @@ module ActiveRecord
attr_accessor :automatic_reconnect
attr_reader :spec, :connections
attr_reader :columns, :columns_hash, :primary_keys, :tables
attr_reader :column_defaults
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
# object which describes database connection information (e.g. adapter,
@@ -106,6 +107,12 @@ module ActiveRecord
}]
end
@column_defaults = Hash.new do |h, table_name|
h[table_name] = Hash[columns[table_name].map { |col|
[col.name, col.default]
}]
end
@primary_keys = Hash.new do |h, table_name|
h[table_name] = with_connection do |conn|
table_exists?(table_name) ? conn.primary_key(table_name) : 'id'
@@ -133,6 +140,7 @@ module ActiveRecord
def clear_cache!
@columns.clear
@columns_hash.clear
@column_defaults.clear
@tables.clear
end
@@ -140,6 +148,7 @@ module ActiveRecord
def clear_table_cache!(table_name)
@columns.delete table_name
@columns_hash.delete table_name
@column_defaults.delete table_name
@primary_keys.delete table_name
end

View File

@@ -317,9 +317,7 @@ module ActiveRecord
# that a new instance, or one populated from a passed-in Hash, still has all the attributes
# that instances loaded from the database would.
def attributes_from_column_definition
Hash[self.class.columns.map do |column|
[column.name, column.default]
end]
self.class.column_defaults.dup
end
end
end