aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/associations/association.rb6
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb22
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb13
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb18
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb16
-rw-r--r--activerecord/lib/active_record/attribute_assignment.rb106
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb5
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb159
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb56
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/transaction.rb156
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb45
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb97
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/cast.rb28
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/oid.rb15
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb29
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb80
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb10
-rw-r--r--activerecord/lib/active_record/core.rb16
-rw-r--r--activerecord/lib/active_record/explain_subscriber.rb3
-rw-r--r--activerecord/lib/active_record/fixtures.rb9
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb42
-rw-r--r--activerecord/lib/active_record/persistence.rb25
-rw-r--r--activerecord/lib/active_record/railties/console_sandbox.rb2
-rw-r--r--activerecord/lib/active_record/railties/databases.rake4
-rw-r--r--activerecord/lib/active_record/reflection.rb4
-rw-r--r--activerecord/lib/active_record/relation.rb12
-rw-r--r--activerecord/lib/active_record/relation/batches.rb13
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb8
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb31
-rw-r--r--activerecord/lib/active_record/schema_migration.rb1
-rw-r--r--activerecord/lib/active_record/transactions.rb37
-rw-r--r--activerecord/lib/active_record/validations.rb6
-rw-r--r--activerecord/lib/rails/generators/active_record/model/templates/model.rb5
37 files changed, 648 insertions, 450 deletions
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index 9f47e7e631..495f0cde59 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -233,10 +233,10 @@ module ActiveRecord
def stale_state
end
- def build_record(attributes, options)
- reflection.build_association(attributes, options) do |record|
+ def build_record(attributes)
+ reflection.build_association(attributes) do |record|
attributes = create_scope.except(*(record.changed - [reflection.foreign_key]))
- record.assign_attributes(attributes, :without_protection => true)
+ record.assign_attributes(attributes)
end
end
end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index b15df4f308..fe3e5b00f7 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -95,22 +95,22 @@ module ActiveRecord
first_or_last(:last, *args)
end
- def build(attributes = {}, options = {}, &block)
+ def build(attributes = {}, &block)
if attributes.is_a?(Array)
- attributes.collect { |attr| build(attr, options, &block) }
+ attributes.collect { |attr| build(attr, &block) }
else
- add_to_target(build_record(attributes, options)) do |record|
+ add_to_target(build_record(attributes)) do |record|
yield(record) if block_given?
end
end
end
- def create(attributes = {}, options = {}, &block)
- create_record(attributes, options, &block)
+ def create(attributes = {}, &block)
+ create_record(attributes, &block)
end
- def create!(attributes = {}, options = {}, &block)
- create_record(attributes, options, true, &block)
+ def create!(attributes = {}, &block)
+ create_record(attributes, true, &block)
end
# Add +records+ to this association. Returns +self+ so method calls may
@@ -373,7 +373,7 @@ module ActiveRecord
# replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do
count_with = $2.to_s
- count_with = '*' if count_with.blank? || count_with =~ /,/
+ count_with = '*' if count_with.blank? || count_with =~ /,/ || count_with =~ /\.\*/
"SELECT #{$1}COUNT(#{count_with}) FROM"
end
end
@@ -425,16 +425,16 @@ module ActiveRecord
persisted + memory
end
- def create_record(attributes, options, raise = false, &block)
+ def create_record(attributes, raise = false, &block)
unless owner.persisted?
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
end
if attributes.is_a?(Array)
- attributes.collect { |attr| create_record(attr, options, raise, &block) }
+ attributes.collect { |attr| create_record(attr, raise, &block) }
else
transaction do
- add_to_target(build_record(attributes, options)) do |record|
+ add_to_target(build_record(attributes)) do |record|
yield(record) if block_given?
insert_record(record, true, raise)
end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 66132b7260..c113957faa 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -222,8 +222,8 @@ module ActiveRecord
#
# person.pets.size # => 5 # size of the collection
# person.pets.count # => 0 # count from database
- def build(attributes = {}, options = {}, &block)
- @association.build(attributes, options, &block)
+ def build(attributes = {}, &block)
+ @association.build(attributes, &block)
end
##
@@ -253,8 +253,8 @@ module ActiveRecord
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
- def create(attributes = {}, options = {}, &block)
- @association.create(attributes, options, &block)
+ def create(attributes = {}, &block)
+ @association.create(attributes, &block)
end
##
@@ -265,14 +265,13 @@ module ActiveRecord
# end
#
# class Pet
- # attr_accessible :name
# validates :name, presence: true
# end
#
# person.pets.create!(name: nil)
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
- def create!(attributes = {}, options = {}, &block)
- @association.create!(attributes, options, &block)
+ def create!(attributes = {}, &block)
+ @association.create!(attributes, &block)
end
##
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 88ff11f953..c7d8a84a7e 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -37,6 +37,20 @@ module ActiveRecord
super
end
+ def concat_records(records)
+ ensure_not_nested
+
+ records = super
+
+ if owner.new_record? && records
+ records.flatten.each do |record|
+ build_through_record(record)
+ end
+ end
+
+ records
+ end
+
def insert_record(record, validate = true, raise = false)
ensure_not_nested
@@ -82,10 +96,10 @@ module ActiveRecord
@through_records.delete(record.object_id)
end
- def build_record(attributes, options = {})
+ def build_record(attributes)
ensure_not_nested
- record = super(attributes, options)
+ record = super(attributes)
inverse = source_reflection.inverse_of
if inverse
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index b84cb4922d..32f4557c28 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -17,16 +17,16 @@ module ActiveRecord
replace(record)
end
- def create(attributes = {}, options = {}, &block)
- create_record(attributes, options, &block)
+ def create(attributes = {}, &block)
+ create_record(attributes, &block)
end
- def create!(attributes = {}, options = {}, &block)
- create_record(attributes, options, true, &block)
+ def create!(attributes = {}, &block)
+ create_record(attributes, true, &block)
end
- def build(attributes = {}, options = {})
- record = build_record(attributes, options)
+ def build(attributes = {})
+ record = build_record(attributes)
yield(record) if block_given?
set_new_record(record)
record
@@ -51,8 +51,8 @@ module ActiveRecord
replace(record)
end
- def create_record(attributes, options, raise_error = false)
- record = build_record(attributes, options)
+ def create_record(attributes, raise_error = false)
+ record = build_record(attributes)
yield(record) if block_given?
saved = record.save
set_new_record(record)
diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb
index d9989274c8..af13b75a9d 100644
--- a/activerecord/lib/active_record/attribute_assignment.rb
+++ b/activerecord/lib/active_record/attribute_assignment.rb
@@ -1,98 +1,24 @@
module ActiveRecord
- ActiveSupport.on_load(:active_record_config) do
- mattr_accessor :whitelist_attributes, instance_accessor: false
- mattr_accessor :mass_assignment_sanitizer, instance_accessor: false
- end
-
module AttributeAssignment
extend ActiveSupport::Concern
- include ActiveModel::MassAssignmentSecurity
-
- included do
- initialize_mass_assignment_sanitizer
- end
-
- module ClassMethods
- def inherited(child) # :nodoc:
- child.send :initialize_mass_assignment_sanitizer if self == Base
- super
- end
-
- private
-
- # The primary key and inheritance column can never be set by mass-assignment for security reasons.
- def attributes_protected_by_default
- default = [ primary_key, inheritance_column ]
- default << 'id' unless primary_key.eql? 'id'
- default
- end
+ include ActiveModel::DeprecatedMassAssignmentSecurity
+ include ActiveModel::ForbiddenAttributesProtection
- def initialize_mass_assignment_sanitizer
- attr_accessible(nil) if Model.whitelist_attributes
- self.mass_assignment_sanitizer = Model.mass_assignment_sanitizer if Model.mass_assignment_sanitizer
- end
- end
-
- # Allows you to set all the attributes at once by passing in a hash with keys
- # matching the attribute names (which again matches the column names).
- #
- # If any attributes are protected by either +attr_protected+ or
- # +attr_accessible+ then only settable attributes will be assigned.
+ # Allows you to set all the attributes by passing in a hash of attributes with
+ # keys matching the attribute names (which again matches the column names).
#
- # class User < ActiveRecord::Base
- # attr_protected :is_admin
- # end
- #
- # user = User.new
- # user.attributes = { :username => 'Phusion', :is_admin => true }
- # user.username # => "Phusion"
- # user.is_admin? # => false
- def attributes=(new_attributes)
- return unless new_attributes.is_a?(Hash)
-
- assign_attributes(new_attributes)
- end
-
- # Allows you to set all the attributes for a particular mass-assignment
- # security role by passing in a hash of attributes with keys matching
- # the attribute names (which again matches the column names) and the role
- # name using the :as option.
- #
- # To bypass mass-assignment security you can use the :without_protection => true
- # option.
- #
- # class User < ActiveRecord::Base
- # attr_accessible :name
- # attr_accessible :name, :is_admin, :as => :admin
- # end
- #
- # user = User.new
- # user.assign_attributes({ :name => 'Josh', :is_admin => true })
- # user.name # => "Josh"
- # user.is_admin? # => false
- #
- # user = User.new
- # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
- # user.name # => "Josh"
- # user.is_admin? # => true
- #
- # user = User.new
- # user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
- # user.name # => "Josh"
- # user.is_admin? # => true
- def assign_attributes(new_attributes, options = {})
+ # If the passed hash responds to <tt>permitted?</tt> method and the return value
+ # of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
+ # exception is raised.
+ def assign_attributes(new_attributes)
return if new_attributes.blank?
attributes = new_attributes.stringify_keys
multi_parameter_attributes = []
nested_parameter_attributes = []
- previous_options = @mass_assignment_options
- @mass_assignment_options = options
- unless options[:without_protection]
- attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role)
- end
+ attributes = sanitize_for_mass_assignment(attributes)
attributes.each do |k, v|
if k.include?("(")
@@ -106,19 +32,9 @@ module ActiveRecord
assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
- ensure
- @mass_assignment_options = previous_options
- end
-
- protected
-
- def mass_assignment_options
- @mass_assignment_options ||= {}
end
- def mass_assignment_role
- mass_assignment_options[:as] || :default
- end
+ alias attributes= assign_attributes
private
@@ -143,7 +59,7 @@ module ActiveRecord
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum,
# f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the
- # attribute will be set to nil.
+ # attribute will be set to +nil+.
def assign_multiparameter_attributes(pairs)
execute_callstack_for_multiparameter_attributes(
extract_callstack_for_multiparameter_attributes(pairs)
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 7b7811a706..aa6704d5c9 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -18,7 +18,7 @@ module ActiveRecord
# Sets the primary key value
def id=(value)
- write_attribute(self.class.primary_key, value)
+ write_attribute(self.class.primary_key, value) if self.class.primary_key
end
# Queries the primary key value
@@ -53,8 +53,7 @@ module ActiveRecord
end
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
- # primary_key_prefix_type setting, though. Since primary keys are usually protected from mass assignment,
- # remember to let your database generate them or include the key in +attr_accessible+.
+ # primary_key_prefix_type setting, though.
def primary_key
@primary_key = reset_primary_key unless defined? @primary_key
@primary_key
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index 11e4d34de2..32e3c7f5d8 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -3,8 +3,7 @@ module ActiveRecord
module DatabaseStatements
def initialize
super
- @_current_transaction_records = []
- @transaction_joinable = nil
+ reset_transaction
end
# Converts an arel AST to SQL
@@ -108,20 +107,6 @@ module ActiveRecord
exec_delete(to_sql(arel, binds), name, binds)
end
- # Checks whether there is currently no transaction active. This is done
- # by querying the database driver, and does not use the transaction
- # house-keeping information recorded by #increment_open_transactions and
- # friends.
- #
- # Returns true if there is no transaction active, false if there is a
- # transaction active, and nil if this information is unknown.
- #
- # Not all adapters supports transaction state introspection. Currently,
- # only the PostgreSQL adapter supports this.
- def outside_transaction?
- nil
- end
-
# Returns +true+ when the connection adapter supports prepared statement
# caching, otherwise returns +false+
def supports_statement_cache?
@@ -173,76 +158,60 @@ module ActiveRecord
def transaction(options = {})
options.assert_valid_keys :requires_new, :joinable
- last_transaction_joinable = @transaction_joinable
- @transaction_joinable = options.fetch(:joinable, true)
- requires_new = options[:requires_new] || !last_transaction_joinable
- transaction_open = false
-
- begin
- if requires_new || open_transactions == 0
- if open_transactions == 0
- begin_db_transaction
- elsif requires_new
- create_savepoint
- end
- increment_open_transactions
- transaction_open = true
- @_current_transaction_records.push([])
- end
+ if !options[:requires_new] && current_transaction.joinable?
yield
- rescue Exception => database_transaction_rollback
- if transaction_open && !outside_transaction?
- transaction_open = false
- txn = decrement_open_transactions
- txn.aborted!
- if open_transactions == 0
- rollback_db_transaction
- rollback_transaction_records(true)
- else
- rollback_to_savepoint
- rollback_transaction_records(false)
- end
- end
- raise unless database_transaction_rollback.is_a?(ActiveRecord::Rollback)
+ else
+ within_new_transaction(options) { yield }
end
+ rescue ActiveRecord::Rollback
+ # rollbacks are silently swallowed
+ end
+
+ def within_new_transaction(options = {}) #:nodoc:
+ begin_transaction(options)
+ yield
+ rescue Exception => error
+ rollback_transaction
+ raise
ensure
- @transaction_joinable = last_transaction_joinable
-
- if outside_transaction?
- @current_transaction = nil
- elsif transaction_open
- txn = decrement_open_transactions
- txn.committed!
- begin
- if open_transactions == 0
- commit_db_transaction
- commit_transaction_records
- else
- release_savepoint
- save_point_records = @_current_transaction_records.pop
- unless save_point_records.blank?
- @_current_transaction_records.push([]) if @_current_transaction_records.empty?
- @_current_transaction_records.last.concat(save_point_records)
- end
- end
- rescue Exception
- if open_transactions == 0
- rollback_db_transaction
- rollback_transaction_records(true)
- else
- rollback_to_savepoint
- rollback_transaction_records(false)
- end
- raise
- end
+ begin
+ commit_transaction unless error
+ rescue Exception
+ rollback_transaction
+ raise
end
end
+ def current_transaction #:nodoc:
+ @transaction
+ end
+
+ def transaction_open?
+ @transaction.open?
+ end
+
+ def begin_transaction(options = {}) #:nodoc:
+ @transaction = @transaction.begin
+ @transaction.joinable = options.fetch(:joinable, true)
+ @transaction
+ end
+
+ def commit_transaction #:nodoc:
+ @transaction = @transaction.commit
+ end
+
+ def rollback_transaction #:nodoc:
+ @transaction = @transaction.rollback
+ end
+
+ def reset_transaction #:nodoc:
+ @transaction = ClosedTransaction.new(self)
+ end
+
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
# can be called.
def add_transaction_record(record)
- last_batch = @_current_transaction_records.last
- last_batch << record if last_batch
+ @transaction.add_record(record)
end
# Begins the transaction (and turns off auto-committing).
@@ -356,42 +325,6 @@ module ActiveRecord
update_sql(sql, name)
end
- # Send a rollback message to all records after they have been rolled back. If rollback
- # is false, only rollback records since the last save point.
- def rollback_transaction_records(rollback)
- if rollback
- records = @_current_transaction_records.flatten
- @_current_transaction_records.clear
- else
- records = @_current_transaction_records.pop
- end
-
- unless records.blank?
- records.uniq.each do |record|
- begin
- record.rolledback!(rollback)
- rescue => e
- record.logger.error(e) if record.respond_to?(:logger) && record.logger
- end
- end
- end
- end
-
- # Send a commit message to all records after they have been committed.
- def commit_transaction_records
- records = @_current_transaction_records.flatten
- @_current_transaction_records.clear
- unless records.blank?
- records.uniq.each do |record|
- begin
- record.committed!
- rescue => e
- record.logger.error(e) if record.respond_to?(:logger) && record.logger
- end
- end
- end
- end
-
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
[sql, binds]
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
new file mode 100644
index 0000000000..9d6111b51e
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
@@ -0,0 +1,56 @@
+module ActiveRecord
+ module ConnectionAdapters # :nodoc:
+ # The goal of this module is to move Adapter specific column
+ # definitions to the Adapter instead of having it in the schema
+ # dumper itself. This code represents the normal case.
+ # We can then redefine how certain data types may be handled in the schema dumper on the
+ # Adapter level by over-writing this code inside the database spececific adapters
+ module ColumnDumper
+ def column_spec(column, types)
+ spec = prepare_column_options(column, types)
+ (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
+ spec
+ end
+
+ # This can be overridden on a Adapter level basis to support other
+ # extended datatypes (Example: Adding an array option in the
+ # PostgreSQLAdapter)
+ def prepare_column_options(column, types)
+ spec = {}
+ spec[:name] = column.name.inspect
+
+ # AR has an optimization which handles zero-scale decimals as integers. This
+ # code ensures that the dumper still dumps the column as a decimal.
+ spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
+ 'decimal'
+ else
+ column.type.to_s
+ end
+ spec[:limit] = column.limit.inspect if column.limit != types[column.type][:limit] && spec[:type] != 'decimal'
+ spec[:precision] = column.precision.inspect if column.precision
+ spec[:scale] = column.scale.inspect if column.scale
+ spec[:null] = 'false' unless column.null
+ spec[:default] = default_string(column.default) if column.has_default?
+ spec
+ end
+
+ # Lists the valid migration options
+ def migration_keys
+ [:name, :limit, :precision, :scale, :default, :null]
+ end
+
+ private
+
+ def default_string(value)
+ case value
+ when BigDecimal
+ value.to_s
+ when Date, DateTime, Time
+ "'#{value.to_s(:db)}'"
+ else
+ value.inspect
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
new file mode 100644
index 0000000000..2117eae5cb
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
@@ -0,0 +1,156 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class Transaction #:nodoc:
+ attr_reader :connection
+
+ def initialize(connection)
+ @connection = connection
+ end
+ end
+
+ class ClosedTransaction < Transaction #:nodoc:
+ def number
+ 0
+ end
+
+ def begin
+ RealTransaction.new(connection, self)
+ end
+
+ def closed?
+ true
+ end
+
+ def open?
+ false
+ end
+
+ def joinable?
+ false
+ end
+
+ # This is a noop when there are no open transactions
+ def add_record(record)
+ end
+ end
+
+ class OpenTransaction < Transaction #:nodoc:
+ attr_reader :parent, :records
+ attr_writer :joinable
+
+ def initialize(connection, parent)
+ super connection
+
+ @parent = parent
+ @records = []
+ @finishing = false
+ @joinable = true
+ end
+
+ # This state is necesarry so that we correctly handle stuff that might
+ # happen in a commit/rollback. But it's kinda distasteful. Maybe we can
+ # find a better way to structure it in the future.
+ def finishing?
+ @finishing
+ end
+
+ def joinable?
+ @joinable && !finishing?
+ end
+
+ def number
+ if finishing?
+ parent.number
+ else
+ parent.number + 1
+ end
+ end
+
+ def begin
+ if finishing?
+ parent.begin
+ else
+ SavepointTransaction.new(connection, self)
+ end
+ end
+
+ def rollback
+ @finishing = true
+ perform_rollback
+ parent
+ end
+
+ def commit
+ @finishing = true
+ perform_commit
+ parent
+ end
+
+ def add_record(record)
+ records << record
+ end
+
+ def rollback_records
+ records.uniq.each do |record|
+ begin
+ record.rolledback!(parent.closed?)
+ rescue => e
+ record.logger.error(e) if record.respond_to?(:logger) && record.logger
+ end
+ end
+ end
+
+ def commit_records
+ records.uniq.each do |record|
+ begin
+ record.committed!
+ rescue => e
+ record.logger.error(e) if record.respond_to?(:logger) && record.logger
+ end
+ end
+ end
+
+ def closed?
+ false
+ end
+
+ def open?
+ true
+ end
+ end
+
+ class RealTransaction < OpenTransaction #:nodoc:
+ def initialize(connection, parent)
+ super
+ connection.begin_db_transaction
+ end
+
+ def perform_rollback
+ connection.rollback_db_transaction
+ rollback_records
+ end
+
+ def perform_commit
+ connection.commit_db_transaction
+ commit_records
+ end
+ end
+
+ class SavepointTransaction < OpenTransaction #:nodoc:
+ def initialize(connection, parent)
+ super
+ connection.create_savepoint
+ end
+
+ def perform_rollback
+ connection.rollback_to_savepoint
+ rollback_records
+ end
+
+ def perform_commit
+ connection.release_savepoint
+ records.each { |r| parent.add_record(r) }
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 27700e4fd2..3a8fbcf93f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -3,7 +3,9 @@ require 'bigdecimal'
require 'bigdecimal/util'
require 'active_support/core_ext/benchmark'
require 'active_record/connection_adapters/schema_cache'
+require 'active_record/connection_adapters/abstract/schema_dumper'
require 'monitor'
+require 'active_support/deprecation'
module ActiveRecord
module ConnectionAdapters # :nodoc:
@@ -33,6 +35,12 @@ module ActiveRecord
autoload :QueryCache
end
+ autoload_at 'active_record/connection_adapters/abstract/transaction' do
+ autoload :ClosedTransaction
+ autoload :RealTransaction
+ autoload :SavepointTransaction
+ end
+
# Active Record supports multiple database systems. AbstractAdapter and
# related classes form the abstraction layer which makes this possible.
# An AbstractAdapter represents a connection to a database, and provides an
@@ -52,6 +60,7 @@ module ActiveRecord
include QueryCache
include ActiveSupport::Callbacks
include MonitorMixin
+ include ColumnDumper
define_callbacks :checkout, :checkin
@@ -62,14 +71,11 @@ module ActiveRecord
def initialize(connection, logger = nil, pool = nil) #:nodoc:
super()
- @active = nil
@connection = connection
@in_use = false
@instrumenter = ActiveSupport::Notifications.instrumenter
@last_use = false
@logger = logger
- @open_transactions = 0
- @current_transaction = nil
@pool = pool
@query_cache = Hash.new { |h,sql| h[sql] = {} }
@query_cache_enabled = false
@@ -182,19 +188,21 @@ module ActiveRecord
# checking whether the database is actually capable of responding, i.e. whether
# the connection isn't stale.
def active?
- @active != false
end
# Disconnects from the database if already connected, and establishes a
- # new connection with the database.
+ # new connection with the database. Implementors should call super if they
+ # override the default implementation.
def reconnect!
- @active = true
+ clear_cache!
+ reset_transaction
end
# Disconnects from the database if already connected. Otherwise, this
# method does nothing.
def disconnect!
- @active = false
+ clear_cache!
+ reset_transaction
end
# Reset the state of this connection, directing the DBMS to clear
@@ -238,33 +246,20 @@ module ActiveRecord
end
def open_transactions
- count = 0
- txn = current_transaction
-
- while txn
- count += 1
- txn = txn.next
- end
-
- count
+ @transaction.number
end
- attr_reader :current_transaction
-
def increment_open_transactions
- @current_transaction = Transaction.new(current_transaction)
+ ActiveSupport::Deprecation.warn "#increment_open_transactions is deprecated and has no effect"
end
def decrement_open_transactions
- return unless current_transaction
-
- txn = current_transaction
- @current_transaction = txn.next
- txn
+ ActiveSupport::Deprecation.warn "#decrement_open_transactions is deprecated and has no effect"
end
def transaction_joinable=(joinable)
- @transaction_joinable = joinable
+ ActiveSupport::Deprecation.warn "#transaction_joinable= is deprecated. Please pass the :joinable option to #begin_transaction instead."
+ @transaction.joinable = joinable
end
def create_savepoint
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 8fc172f6e8..328d080687 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -74,6 +74,7 @@ module ActiveRecord
end
def reconnect!
+ super
disconnect!
connect
end
@@ -82,6 +83,7 @@ module ActiveRecord
# Disconnects from the database if already connected.
# Otherwise, this method does nothing.
def disconnect!
+ super
unless @connection.nil?
@connection.close
@connection = nil
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index bb63fddf9b..0b936bbf39 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -189,14 +189,15 @@ module ActiveRecord
end
def reconnect!
+ super
disconnect!
- clear_cache!
connect
end
# Disconnects from the database if already connected. Otherwise, this
# method does nothing.
def disconnect!
+ super
@connection.close rescue nil
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb b/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb
new file mode 100644
index 0000000000..b7d24f2bb3
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/array_parser.rb
@@ -0,0 +1,97 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLColumn < Column
+ module ArrayParser
+ private
+ # Loads pg_array_parser if available. String parsing can be
+ # performed quicker by a native extension, which will not create
+ # a large amount of Ruby objects that will need to be garbage
+ # collected. pg_array_parser has a C and Java extension
+ begin
+ require 'pg_array_parser'
+ include PgArrayParser
+ rescue LoadError
+ def parse_pg_array(string)
+ parse_data(string, 0)
+ end
+ end
+
+ def parse_data(string, index)
+ local_index = index
+ array = []
+ while(local_index < string.length)
+ case string[local_index]
+ when '{'
+ local_index,array = parse_array_contents(array, string, local_index + 1)
+ when '}'
+ return array
+ end
+ local_index += 1
+ end
+
+ array
+ end
+
+ def parse_array_contents(array, string, index)
+ is_escaping = false
+ is_quoted = false
+ was_quoted = false
+ current_item = ''
+
+ local_index = index
+ while local_index
+ token = string[local_index]
+ if is_escaping
+ current_item << token
+ is_escaping = false
+ else
+ if is_quoted
+ case token
+ when '"'
+ is_quoted = false
+ was_quoted = true
+ when "\\"
+ is_escaping = true
+ else
+ current_item << token
+ end
+ else
+ case token
+ when "\\"
+ is_escaping = true
+ when ','
+ add_item_to_array(array, current_item, was_quoted)
+ current_item = ''
+ was_quoted = false
+ when '"'
+ is_quoted = true
+ when '{'
+ internal_items = []
+ local_index,internal_items = parse_array_contents(internal_items, string, local_index + 1)
+ array.push(internal_items)
+ when '}'
+ add_item_to_array(array, current_item, was_quoted)
+ return local_index,array
+ else
+ current_item << token
+ end
+ end
+ end
+
+ local_index += 1
+ end
+ return local_index,array
+ end
+
+ def add_item_to_array(array, current_item, quoted)
+ if current_item.length == 0
+ elsif !quoted && current_item == 'NULL'
+ array.push nil
+ else
+ array.push current_item
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
index b59195f98a..62d091357d 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
@@ -45,6 +45,21 @@ module ActiveRecord
end
end
+ def array_to_string(value, column, adapter, should_be_quoted = false)
+ casted_values = value.map do |val|
+ if String === val
+ if val == "NULL"
+ "\"#{val}\""
+ else
+ quote_and_escape(adapter.type_cast(val, column, true))
+ end
+ else
+ adapter.type_cast(val, column, true)
+ end
+ end
+ "{#{casted_values.join(',')}}"
+ end
+
def string_to_json(string)
if String === string
ActiveSupport::JSON.decode(string)
@@ -71,6 +86,10 @@ module ActiveRecord
end
end
+ def string_to_array(string, oid)
+ parse_pg_array(string).map{|val| oid.type_cast val}
+ end
+
private
HstorePair = begin
@@ -90,6 +109,15 @@ module ActiveRecord
end
end
end
+
+ def quote_and_escape(value)
+ case value
+ when "NULL"
+ value
+ else
+ "\"#{value.gsub(/"/,"\\\"")}\""
+ end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
index eb3084e066..c8437c18cc 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -1,3 +1,5 @@
+require 'active_support/deprecation'
+
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
@@ -214,6 +216,10 @@ module ActiveRecord
end
def outside_transaction?
+ ActiveSupport::Deprecation.warn(
+ "#outside_transaction? is deprecated. This method was only really used " \
+ "internally, but you can use #transaction_open? instead."
+ )
@connection.transaction_status == PGconn::PQTRANS_IDLE
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
index b8e7687b21..52344f61c0 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
@@ -63,6 +63,21 @@ module ActiveRecord
end
end
+ class Array < Type
+ attr_reader :subtype
+ def initialize(subtype)
+ @subtype = subtype
+ end
+
+ def type_cast(value)
+ if String === value
+ ConnectionAdapters::PostgreSQLColumn.string_to_array value, @subtype
+ else
+ value
+ end
+ end
+ end
+
class Integer < Type
def type_cast(value)
return if value.nil?
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
index 85721601a9..37d43d891d 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -19,6 +19,12 @@ module ActiveRecord
return super unless column
case value
+ when Array
+ if column.array
+ "'#{PostgreSQLColumn.array_to_string(value, column, self)}'"
+ else
+ super
+ end
when Hash
case column.sql_type
when 'hstore' then super(PostgreSQLColumn.hstore_to_string(value), column)
@@ -59,24 +65,35 @@ module ActiveRecord
end
end
- def type_cast(value, column)
- return super unless column
+ def type_cast(value, column, array_member = false)
+ return super(value, column) unless column
case value
+ when NilClass
+ if column.array && array_member
+ 'NULL'
+ elsif column.array
+ value
+ else
+ super(value, column)
+ end
+ when Array
+ return super(value, column) unless column.array
+ PostgreSQLColumn.array_to_string(value, column, self)
when String
- return super unless 'bytea' == column.sql_type
+ return super(value, column) unless 'bytea' == column.sql_type
{ :value => value, :format => 1 }
when Hash
case column.sql_type
when 'hstore' then PostgreSQLColumn.hstore_to_string(value)
when 'json' then PostgreSQLColumn.json_to_string(value)
- else super
+ else super(value, column)
end
when IPAddr
- return super unless ['inet','cidr'].includes? column.sql_type
+ return super(value, column) unless ['inet','cidr'].includes? column.sql_type
PostgreSQLColumn.cidr_to_string(value)
else
- super
+ super(value, column)
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index 60f01c297e..8a073bf878 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -111,7 +111,7 @@ module ActiveRecord
inddef = row[3]
oid = row[4]
- columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")]
+ columns = Hash[query(<<-SQL, "SCHEMA")]
SELECT a.attnum, a.attname
FROM pg_attribute a
WHERE a.attrelid = #{oid}
@@ -252,7 +252,7 @@ module ActiveRecord
if pk && sequence
quoted_sequence = quote_table_name(sequence)
- select_value <<-end_sql, 'Reset sequence'
+ select_value <<-end_sql, 'SCHEMA'
SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
end_sql
end
@@ -262,7 +262,7 @@ module ActiveRecord
def pk_and_sequence_for(table) #:nodoc:
# First try looking for a sequence with a dependency on the
# given table's primary key.
- result = query(<<-end_sql, 'PK and serial sequence')[0]
+ result = query(<<-end_sql, 'SCHEMA')[0]
SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
@@ -283,7 +283,7 @@ module ActiveRecord
# If that fails, try parsing the primary key's default value.
# Support the 7.x and 8.0 nextval('foo'::text) as well as
# the 8.1+ nextval('foo'::regclass).
- result = query(<<-end_sql, 'PK and custom sequence')[0]
+ result = query(<<-end_sql, 'SCHEMA')[0]
SELECT attr.attname,
CASE
WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index d1751d70c6..761052a788 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -2,6 +2,7 @@ require 'active_record/connection_adapters/abstract_adapter'
require 'active_record/connection_adapters/statement_pool'
require 'active_record/connection_adapters/postgresql/oid'
require 'active_record/connection_adapters/postgresql/cast'
+require 'active_record/connection_adapters/postgresql/array_parser'
require 'active_record/connection_adapters/postgresql/quoting'
require 'active_record/connection_adapters/postgresql/schema_statements'
require 'active_record/connection_adapters/postgresql/database_statements'
@@ -41,16 +42,23 @@ module ActiveRecord
module ConnectionAdapters
# PostgreSQL-specific extensions to column definitions in a table.
class PostgreSQLColumn < Column #:nodoc:
+ attr_accessor :array
# Instantiates a new PostgreSQL column definition in a table.
def initialize(name, default, oid_type, sql_type = nil, null = true)
@oid_type = oid_type
- super(name, self.class.extract_value_from_default(default), sql_type, null)
+ if sql_type =~ /\[\]$/
+ @array = true
+ super(name, self.class.extract_value_from_default(default), sql_type[0..sql_type.length - 3], null)
+ else
+ @array = false
+ super(name, self.class.extract_value_from_default(default), sql_type, null)
+ end
end
# :stopdoc:
class << self
include ConnectionAdapters::PostgreSQLColumn::Cast
-
+ include ConnectionAdapters::PostgreSQLColumn::ArrayParser
attr_accessor :money_precision
end
# :startdoc:
@@ -243,6 +251,10 @@ module ActiveRecord
# In addition, default connection parameters of libpq can be set per environment variables.
# See http://www.postgresql.org/docs/9.1/static/libpq-envars.html .
class PostgreSQLAdapter < AbstractAdapter
+ class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
+ attr_accessor :array
+ end
+
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
def xml(*args)
options = args.extract_options!
@@ -277,6 +289,23 @@ module ActiveRecord
def json(name, options = {})
column(name, 'json', options)
end
+
+ def column(name, type = nil, options = {})
+ super
+ column = self[name]
+ column.array = options[:array]
+
+ self
+ end
+
+ private
+
+ def new_column_definition(base, name, type)
+ definition = ColumnDefinition.new base, name, type
+ @columns << definition
+ @columns_hash[name] = definition
+ definition
+ end
end
ADAPTER_NAME = 'PostgreSQL'
@@ -314,6 +343,19 @@ module ActiveRecord
ADAPTER_NAME
end
+ # Adds `:array` option to the default set provided by the
+ # AbstractAdapter
+ def prepare_column_options(column, types)
+ spec = super
+ spec[:array] = 'true' if column.respond_to?(:array) && column.array
+ spec
+ end
+
+ # Adds `:array` as a valid migration key
+ def migration_keys
+ super + [:array]
+ end
+
# Returns +true+, since this connection adapter supports prepared statement
# caching.
def supports_statement_cache?
@@ -431,9 +473,8 @@ module ActiveRecord
# Close then reopen the connection.
def reconnect!
- clear_cache!
+ super
@connection.reset
- @open_transactions = 0
configure_connection
end
@@ -445,7 +486,7 @@ module ActiveRecord
# Disconnects from the database if already connected. Otherwise, this
# method does nothing.
def disconnect!
- clear_cache!
+ super
@connection.close rescue nil
end
@@ -494,6 +535,13 @@ module ActiveRecord
@table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i
end
+ def add_column_options!(sql, options)
+ if options[:array] || options[:column].try(:array)
+ sql << '[]'
+ end
+ super
+ end
+
# Set the authorized user for this session
def session_auth=(user)
clear_cache!
@@ -548,7 +596,7 @@ module ActiveRecord
private
def initialize_type_map
- result = execute('SELECT oid, typname, typelem, typdelim FROM pg_type', 'SCHEMA')
+ result = execute('SELECT oid, typname, typelem, typdelim, typinput FROM pg_type', 'SCHEMA')
leaves, nodes = result.partition { |row| row['typelem'] == '0' }
# populate the leaf nodes
@@ -556,11 +604,19 @@ module ActiveRecord
OID::TYPE_MAP[row['oid'].to_i] = OID::NAMES[row['typname']]
end
+ arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
+
# populate composite types
nodes.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
vector = OID::Vector.new row['typdelim'], OID::TYPE_MAP[row['typelem'].to_i]
OID::TYPE_MAP[row['oid'].to_i] = vector
end
+
+ # populate array types
+ arrays.find_all { |row| OID::TYPE_MAP.key? row['typelem'].to_i }.each do |row|
+ array = OID::Array.new OID::TYPE_MAP[row['typelem'].to_i]
+ OID::TYPE_MAP[row['oid'].to_i] = array
+ end
end
FEATURE_NOT_SUPPORTED = "0A000" # :nodoc:
@@ -703,12 +759,12 @@ module ActiveRecord
# - ::regclass is a function that gives the id for a table name
def column_definitions(table_name) #:nodoc:
exec_query(<<-end_sql, 'SCHEMA').rows
- SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull, a.atttypid, a.atttypmod
- FROM pg_attribute a LEFT JOIN pg_attrdef d
- ON a.attrelid = d.adrelid AND a.attnum = d.adnum
- WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
- AND a.attnum > 0 AND NOT a.attisdropped
- ORDER BY a.attnum
+ SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull, a.atttypid, a.atttypmod
+ FROM pg_attribute a LEFT JOIN pg_attrdef d
+ ON a.attrelid = d.adrelid AND a.attnum = d.adnum
+ WHERE a.attrelid = '#{quote_table_name(table_name)}'::regclass
+ AND a.attnum > 0 AND NOT a.attisdropped
+ ORDER BY a.attnum
end_sql
end
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 4fe0013f0f..4a48812807 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -104,6 +104,8 @@ module ActiveRecord
def initialize(connection, logger, config)
super(connection, logger)
+
+ @active = nil
@statements = StatementPool.new(@connection,
config.fetch(:statement_limit) { 1000 })
@config = config
@@ -154,11 +156,15 @@ module ActiveRecord
true
end
+ def active?
+ @active != false
+ end
+
# Disconnects from the database if already connected. Otherwise, this
# method does nothing.
def disconnect!
super
- clear_cache!
+ @active = false
@connection.close rescue nil
end
@@ -397,7 +403,7 @@ module ActiveRecord
table_name,
row['name'],
row['unique'] != 0,
- exec_query("PRAGMA index_info('#{row['name']}')", "Columns for index #{row['name']} on #{table_name}").map { |col|
+ exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col|
col['name']
})
end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index cf64985ddb..f97c363871 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -160,19 +160,10 @@ module ActiveRecord
# In both instances, valid attribute keys are determined by the column names of the associated table --
# hence you can't have attributes that aren't part of the table columns.
#
- # +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
- # in the +options+ parameter.
- #
- # ==== Examples
+ # ==== Example:
# # Instantiates a single new object
# User.new(:first_name => 'Jamie')
- #
- # # Instantiates a single new object using the :admin mass-assignment security role
- # User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
- #
- # # Instantiates a single new object bypassing mass-assignment security
- # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
- def initialize(attributes = nil, options = {})
+ def initialize(attributes = nil)
defaults = self.class.column_defaults.dup
defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
@@ -183,7 +174,7 @@ module ActiveRecord
ensure_proper_type
populate_with_current_scope_attributes
- assign_attributes(attributes, options) if attributes
+ assign_attributes(attributes) if attributes
yield self if block_given?
run_callbacks :initialize unless _initialize_callbacks.empty?
@@ -386,7 +377,6 @@ module ActiveRecord
@destroyed = false
@marked_for_destruction = false
@new_record = true
- @mass_assignment_options = nil
@txn = nil
@_start_transaction_state = {}
end
diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb
index d5ba343b4c..0f927496fb 100644
--- a/activerecord/lib/active_record/explain_subscriber.rb
+++ b/activerecord/lib/active_record/explain_subscriber.rb
@@ -18,8 +18,9 @@ module ActiveRecord
# On the other hand, we want to monitor the performance of our real database
# queries, not the performance of the access to the query cache.
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
+ EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)/i
def ignore_payload?(payload)
- payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name])
+ payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
end
ActiveSupport::Notifications.subscribe("sql.active_record", new)
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index b1db5f6f9f..60fc653735 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -843,9 +843,7 @@ module ActiveRecord
end
@fixture_connections = enlist_fixture_connections
@fixture_connections.each do |connection|
- connection.increment_open_transactions
- connection.transaction_joinable = false
- connection.begin_db_transaction
+ connection.begin_transaction joinable: false
end
# Load fixtures for every test.
else
@@ -868,10 +866,7 @@ module ActiveRecord
# Rollback changes if a transaction is active.
if run_in_transaction?
@fixture_connections.each do |connection|
- if connection.open_transactions != 0
- connection.rollback_db_transaction
- connection.decrement_open_transactions
- end
+ connection.rollback_transaction if connection.transaction_open?
end
@fixture_connections.clear
end
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 3005dc042c..2e7fb3bbb3 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -194,18 +194,6 @@ module ActiveRecord
# the parent model is saved. This happens inside the transaction initiated
# by the parents save method. See ActiveRecord::AutosaveAssociation.
#
- # === Using with attr_accessible
- #
- # The use of <tt>attr_accessible</tt> can interfere with nested attributes
- # if you're not careful. For example, if the <tt>Member</tt> model above
- # was using <tt>attr_accessible</tt> like this:
- #
- # attr_accessible :name
- #
- # You would need to modify it to look like this:
- #
- # attr_accessible :name, :posts_attributes
- #
# === Validating the presence of a parent model
#
# If you want to validate that a child record is associated with a parent
@@ -224,9 +212,7 @@ module ActiveRecord
module ClassMethods
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
- # Defines an attributes writer for the specified association(s). If you
- # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
- # will need to add the attribute writer to the allowed list.
+ # Defines an attributes writer for the specified association(s).
#
# Supported options:
# [:allow_destroy]
@@ -296,7 +282,7 @@ module ActiveRecord
remove_method(:#{association_name}_attributes=)
end
def #{association_name}_attributes=(attributes)
- assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
+ assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
end
eoruby
else
@@ -334,21 +320,21 @@ module ActiveRecord
# If the given attributes include a matching <tt>:id</tt> attribute, or
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
# then the existing record will be marked for destruction.
- def assign_nested_attributes_for_one_to_one_association(association_name, attributes, assignment_opts = {})
+ def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
options = self.nested_attributes_options[association_name]
attributes = attributes.with_indifferent_access
if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
- assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
+ assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
- elsif attributes['id'].present? && !assignment_opts[:without_protection]
+ elsif attributes['id'].present?
raise_nested_attributes_record_not_found(association_name, attributes['id'])
elsif !reject_new_record?(association_name, attributes)
method = "build_#{association_name}"
if respond_to?(method)
- send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
+ send(method, attributes.except(*UNASSIGNABLE_KEYS))
else
raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
end
@@ -382,7 +368,7 @@ module ActiveRecord
# { :name => 'John' },
# { :id => '2', :_destroy => true }
# ])
- def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
+ def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
options = self.nested_attributes_options[association_name]
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
@@ -427,7 +413,7 @@ module ActiveRecord
if attributes['id'].blank?
unless reject_new_record?(association_name, attributes)
- association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
+ association.build(attributes.except(*UNASSIGNABLE_KEYS))
end
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
unless association.loaded? || call_reject_if(association_name, attributes)
@@ -443,10 +429,8 @@ module ActiveRecord
end
if !call_reject_if(association_name, attributes)
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
end
- elsif assignment_opts[:without_protection]
- association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
else
raise_nested_attributes_record_not_found(association_name, attributes['id'])
end
@@ -455,8 +439,8 @@ module ActiveRecord
# Updates a record with the +attributes+ or marks it for destruction if
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
- def assign_to_or_mark_for_destruction(record, attributes, allow_destroy, assignment_opts)
- record.assign_attributes(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
+ def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
+ record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
end
@@ -485,9 +469,5 @@ module ActiveRecord
def raise_nested_attributes_record_not_found(association_name, record_id)
raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
end
-
- def unassignable_keys(assignment_opts)
- assignment_opts[:without_protection] ? UNASSIGNABLE_KEYS - %w[id] : UNASSIGNABLE_KEYS
- end
end
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 7bd65c180d..2eaad1d469 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -17,12 +17,6 @@ module ActiveRecord
# # Create a single new object
# User.create(:first_name => 'Jamie')
#
- # # Create a single new object using the :admin mass-assignment security role
- # User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
- #
- # # Create a single new object bypassing mass-assignment security
- # User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
- #
# # Create an Array of new objects
# User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
#
@@ -35,11 +29,11 @@ module ActiveRecord
# User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
# u.is_admin = false
# end
- def create(attributes = nil, options = {}, &block)
+ def create(attributes = nil, &block)
if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr, options, &block) }
+ attributes.collect { |attr| create(attr, &block) }
else
- object = new(attributes, options, &block)
+ object = new(attributes, &block)
object.save
object
end
@@ -183,27 +177,22 @@ module ActiveRecord
# Updates the attributes of the model from the passed-in hash and saves the
# record, all wrapped in a transaction. If the object is invalid, the saving
# will fail and false will be returned.
- #
- # When updating model attributes, mass-assignment security protection is respected.
- # If no +:as+ option is supplied then the +:default+ role will be used.
- # If you want to bypass the protection given by +attr_protected+ and
- # +attr_accessible+ then you can do so using the +:without_protection+ option.
- def update_attributes(attributes, options = {})
+ def update_attributes(attributes)
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
- assign_attributes(attributes, options)
+ assign_attributes(attributes)
save
end
end
# Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead
# of +save+, so an exception is raised if the record is invalid.
- def update_attributes!(attributes, options = {})
+ def update_attributes!(attributes)
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
- assign_attributes(attributes, options)
+ assign_attributes(attributes)
save!
end
end
diff --git a/activerecord/lib/active_record/railties/console_sandbox.rb b/activerecord/lib/active_record/railties/console_sandbox.rb
index 65a3d68619..90b462fad6 100644
--- a/activerecord/lib/active_record/railties/console_sandbox.rb
+++ b/activerecord/lib/active_record/railties/console_sandbox.rb
@@ -1,6 +1,4 @@
-ActiveRecord::Base.connection.increment_open_transactions
ActiveRecord::Base.connection.begin_db_transaction
at_exit do
ActiveRecord::Base.connection.rollback_db_transaction
- ActiveRecord::Base.connection.decrement_open_transactions
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index bcb26f72c8..d134978128 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -245,7 +245,7 @@ db_namespace = namespace :db do
end
end
- task :load_if_ruby => [:environment, 'db:create'] do
+ task :load_if_ruby => ['db:create', :environment] do
db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
end
@@ -328,7 +328,7 @@ db_namespace = namespace :db do
end
end
- task :load_if_sql => [:environment, 'db:create'] do
+ task :load_if_sql => ['db:create', :environment] do
db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
end
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index d9c65fa170..f322b96f79 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -181,8 +181,8 @@ module ActiveRecord
# Returns a new, unsaved instance of the associated class. +options+ will
# be passed to the class's constructor.
- def build_association(*options, &block)
- klass.new(*options, &block)
+ def build_association(attributes, &block)
+ klass.new(attributes, &block)
end
def table_name
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 2d0457636e..ed80422336 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -151,22 +151,22 @@ module ActiveRecord
# user.last_name = "O'Hara"
# end
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
- def first_or_create(attributes = nil, options = {}, &block)
- first || create(attributes, options, &block)
+ def first_or_create(attributes = nil, &block)
+ first || create(attributes, &block)
end
# Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
#
# Expects arguments in the same format as <tt>Base.create!</tt>.
- def first_or_create!(attributes = nil, options = {}, &block)
- first || create!(attributes, options, &block)
+ def first_or_create!(attributes = nil, &block)
+ first || create!(attributes, &block)
end
# Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
#
# Expects arguments in the same format as <tt>Base.new</tt>.
- def first_or_initialize(attributes = nil, options = {}, &block)
- first || new(attributes, options, &block)
+ def first_or_initialize(attributes = nil, &block)
+ first || new(attributes, &block)
end
# Runs EXPLAIN on the query or queries triggered by this relation and
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index 4d14506965..d32048cce1 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -36,12 +36,12 @@ module ActiveRecord
# want multiple workers dealing with the same processing queue. You can
# make worker 1 handle all the records between id 0 and 10,000 and
# worker 2 handle from 10,000 and beyond (by setting the +:start+
- # option on that worker).
+ # option on that worker). You can also use non-integer-based primary keys
+ # if start point is set.
#
# It's not possible to set the order. That is automatically set to
- # ascending on the primary key ("id ASC") to make the batch ordering
- # work. This also mean that this method only works with integer-based
- # primary keys. You can't set the limit either, that's used to control
+ # ascending on the primary key (e.g. "id ASC") to make the batch ordering
+ # work. You can't set the limit either, that's used to control
# the batch sizes.
#
# Person.where("age > 21").find_in_batches do |group|
@@ -62,7 +62,8 @@ module ActiveRecord
ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
end
- start = options.delete(:start).to_i
+ start = options.delete(:start)
+ start ||= 0
batch_size = options.delete(:batch_size) || 1000
relation = relation.reorder(batch_order).limit(batch_size)
@@ -70,7 +71,7 @@ module ActiveRecord
while records.any?
records_size = records.size
- primary_key_offset = records.last.id
+ primary_key_offset = records.last.send(primary_key)
yield records
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 36fc08e6ad..263fdce250 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -10,8 +10,12 @@ module ActiveRecord
table = Arel::Table.new(column, default_table.engine)
association = klass.reflect_on_association(column.to_sym)
- value.each do |k, v|
- queries.concat expand(association && association.klass, table, k, v)
+ if value.empty?
+ queries.concat ['1 = 2']
+ else
+ value.each do |k, v|
+ queries.concat expand(association && association.klass, table, k, v)
+ end
end
else
column = column.to_s
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 310b4c1459..36bde44e7c 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -107,27 +107,11 @@ HEADER
column_specs = columns.map do |column|
raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" if @types[column.type].nil?
next if column.name == pk
- spec = {}
- spec[:name] = column.name.inspect
-
- # AR has an optimization which handles zero-scale decimals as integers. This
- # code ensures that the dumper still dumps the column as a decimal.
- spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
- 'decimal'
- else
- column.type.to_s
- end
- spec[:limit] = column.limit.inspect if column.limit != @types[column.type][:limit] && spec[:type] != 'decimal'
- spec[:precision] = column.precision.inspect if column.precision
- spec[:scale] = column.scale.inspect if column.scale
- spec[:null] = 'false' unless column.null
- spec[:default] = default_string(column.default) if column.has_default?
- (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
- spec
+ @connection.column_spec(column, @types)
end.compact
# find all migration keys used in this table
- keys = [:name, :limit, :precision, :scale, :default, :null]
+ keys = @connection.migration_keys
# figure out the lengths for each column based on above keys
lengths = keys.map { |key|
@@ -170,17 +154,6 @@ HEADER
stream
end
- def default_string(value)
- case value
- when BigDecimal
- value.to_s
- when Date, DateTime, Time
- "'#{value.to_s(:db)}'"
- else
- value.inspect
- end
- end
-
def indexes(table, stream)
if (indexes = @connection.indexes(table)).any?
add_index_statements = indexes.map do |index|
diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb
index ca22154c84..9830abe7d8 100644
--- a/activerecord/lib/active_record/schema_migration.rb
+++ b/activerecord/lib/active_record/schema_migration.rb
@@ -4,7 +4,6 @@ require 'active_record/base'
module ActiveRecord
class SchemaMigration < ActiveRecord::Base
- attr_accessible :version
def self.table_name
"#{Base.table_name_prefix}schema_migrations#{Base.table_name_suffix}"
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index e008b32170..934393b4e7 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -1,32 +1,6 @@
require 'thread'
module ActiveRecord
- class Transaction
- attr_reader :next
-
- def initialize(txn = nil)
- @next = txn
- @committed = false
- @aborted = false
- end
-
- def committed!
- @committed = true
- end
-
- def aborted!
- @aborted = true
- end
-
- def committed?
- @committed
- end
-
- def aborted?
- @aborted
- end
- end
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
module Transactions
extend ActiveSupport::Concern
@@ -191,7 +165,7 @@ module ActiveRecord
# writing, the only database that we're aware of that supports true nested
# transactions, is MS-SQL. Because of this, Active Record emulates nested
# transactions by using savepoints on MySQL and PostgreSQL. See
- # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
+ # http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
# for more information about savepoints.
#
# === Callbacks
@@ -333,11 +307,11 @@ module ActiveRecord
def with_transaction_returning_status
status = nil
self.class.transaction do
- @txn = self.class.connection.current_transaction
add_to_transaction
begin
status = yield
rescue ActiveRecord::Rollback
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
status = nil
end
@@ -353,17 +327,20 @@ module ActiveRecord
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
@_start_transaction_state[:new_record] = @new_record
@_start_transaction_state[:destroyed] = @destroyed
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
end
# Clear the new record state and id of a record.
def clear_transaction_record_state #:nodoc:
- @_start_transaction_state.clear if @txn.committed?
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ @_start_transaction_state.clear if @_start_transaction_state[:level] < 1
end
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
def restore_transaction_record_state(force = false) #:nodoc:
unless @_start_transaction_state.empty?
- if @txn.aborted? || force
+ @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
+ if @_start_transaction_state[:level] < 1 || force
restore_state = @_start_transaction_state
was_frozen = @attributes.frozen?
@attributes = @attributes.dup if was_frozen
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index cef2bbd563..ed561bfb3c 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -32,11 +32,11 @@ module ActiveRecord
module ClassMethods
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
# so an exception is raised if the record is invalid.
- def create!(attributes = nil, options = {}, &block)
+ def create!(attributes = nil, &block)
if attributes.is_a?(Array)
- attributes.collect { |attr| create!(attr, options, &block) }
+ attributes.collect { |attr| create!(attr, &block) }
else
- object = new(attributes, options)
+ object = new(attributes)
yield(object) if block_given?
object.save!
object
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/model.rb b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
index 2cca17b94f..056f55470c 100644
--- a/activerecord/lib/rails/generators/active_record/model/templates/model.rb
+++ b/activerecord/lib/rails/generators/active_record/model/templates/model.rb
@@ -3,10 +3,5 @@ class <%= class_name %> < <%= parent_class_name.classify %>
<% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %>
<% end -%>
-<% if !accessible_attributes.empty? -%>
- attr_accessible <%= accessible_attributes.map {|a| ":#{a.name}" }.sort.join(', ') %>
-<% else -%>
- # attr_accessible :title, :body
-<% end -%>
end
<% end -%>