diff options
Diffstat (limited to 'activerecord')
75 files changed, 892 insertions, 304 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 9e44131fa9..86738fa819 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,107 @@ +* Add support for bidirectional destroy dependencies. + + Fixes #13609. + + Example: + + class Content < ActiveRecord::Base + has_one :position, dependent: :destroy + end + + class Position < ActiveRecord::Base + belongs_to :content, dependent: :destroy + end + + *Seb Jacobs* + +* Includes HABTM returns correct size now. It's caused by the join dependency + only instantiates one HABTM object because the join table hasn't a primary key. + + Fixes #16032. + + Examples: + + before: + + Project.first.salaried_developers.size # => 3 + Project.includes(:salaried_developers).first.salaried_developers.size # => 1 + + after: + + Project.first.salaried_developers.size # => 3 + Project.includes(:salaried_developers).first.salaried_developers.size # => 3 + + *Bigxiang* + +* Add option to index errors in nested attributes + + For models which have nested attributes, errors within those models will + now be indexed if :index_errors is specified when defining a + has_many relationship, or if its set in the global config. + + Example: + + class Guitar < ActiveRecord::Base + has_many :tuning_pegs + accepts_nested_attributes_for :tuning_pegs + end + + class TuningPeg < ActiveRecord::Base + belongs_to :guitar + validates_numericality_of :pitch + end + + - Old style + - `guitar.errors["tuning_pegs.pitch"] = ["is not a number"]` + + - New style (if defined globally, or set in has_many_relationship) + - `guitar.errors["tuning_pegs[1].pitch"] = ["is not a number"]` + + *Michael Probber and Terence Sun* + +* Exit with non-zero status for failed database rake tasks. + + *Jay Hayes* + +* Queries such as `Computer.joins(:monitor).group(:status).count` will now be + interpreted as `Computer.joins(:monitor).group('computers.status').count` + so that when `Computer` and `Monitor` have both `status` columns we don't + have conflicts in projection. + + *Rafael Sales* + +* Add ability to default to `uuid` as primary key when generating database migrations + + config.generators do |g| + g.orm :active_record, primary_key_type: :uuid + end + + *Jon McCartie* + +* Don't cache arguments in #find_by if they are an ActiveRecord::Relation + + Fixes #20817 + + *Hiroaki Izu* + +* Qualify column name inserted by `group` in calculation + + Giving `group` an unqualified column name now works, even if the relation + has `JOIN` with another table which also has a column of the name. + + *Soutaro Matsumoto* + +* Don't cache prepared statements containing an IN clause or a SQL literal, as + these queries will change often and are unlikely to have a cache hit. + + *Sean Griffin* + +* Fix `rewhere` in a `has_many` association. + + Fixes #21955. + + *Josh Branchaud*, *Kal* + * `where` raises ArgumentError on unsupported types. Fixes #20473. @@ -71,9 +175,8 @@ database. - m = Model.create! - m.created_at.usec == m.reload.created_at.usec - # => false + m = Model.create! + m.created_at.usec == m.reload.created_at.usec # => false # due to different precision in Time.now and database column If the precision is low enough, (mysql default is 0, so it is always low @@ -261,9 +364,9 @@ Example: - @users = User.where("name like ?", "%Alberto%") - @users.cache_key - => "/users/query-5942b155a43b139f2471b872ac54251f-3-20150714212107656125000" + @users = User.where("name like ?", "%Alberto%") + @users.cache_key + # => "/users/query-5942b155a43b139f2471b872ac54251f-3-20150714212107656125000" *Alberto Fernández-Capel* diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 2abc5fa9d5..b806a2f832 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -149,7 +149,7 @@ module ActiveRecord class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: end - # This error is raised when trying to eager load a poloymorphic association using a JOIN. + # This error is raised when trying to eager load a polymorphic association using a JOIN. # Eager loading polymorphic associations is only possible with # {ActiveRecord::Relation#preload}[rdoc-ref:QueryMethods#preload]. class EagerLoadPolymorphicError < ActiveRecordError @@ -508,7 +508,7 @@ module ActiveRecord # to customize them. For example, to add a condition: # # class Blog < ActiveRecord::Base - # has_many :published_posts, -> { where published: true }, class_name: 'Post' + # has_many :published_posts, -> { where(published: true) }, class_name: 'Post' # end # # Inside the <tt>-> { ... }</tt> block you can use all of the usual Relation methods. @@ -520,7 +520,7 @@ module ActiveRecord # events that occur on the user's birthday: # # class User < ActiveRecord::Base - # has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event' + # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event' # end # # Note: Joining, eager loading and preloading of these associations is not fully possible. @@ -895,7 +895,7 @@ module ActiveRecord # In this case it is usually more natural to include an association which has conditions defined on it: # # class Post < ActiveRecord::Base - # has_many :approved_comments, -> { where approved: true }, class_name: 'Comment' + # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment' # end # # Post.includes(:approved_comments) @@ -1345,10 +1345,10 @@ module ActiveRecord # association objects. # # Option examples: - # has_many :comments, -> { order "posted_on" } - # has_many :comments, -> { includes :author } + # has_many :comments, -> { order("posted_on") } + # has_many :comments, -> { includes(:author) } # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person" - # has_many :tracks, -> { order "position" }, dependent: :destroy + # has_many :tracks, -> { order("position") }, dependent: :destroy # has_many :comments, dependent: :nullify # has_many :tags, as: :taggable # has_many :reports, -> { readonly } @@ -1476,12 +1476,12 @@ module ActiveRecord # has_one :credit_card, dependent: :destroy # destroys the associated credit card # has_one :credit_card, dependent: :nullify # updates the associated records foreign # # key value to NULL rather than destroying it - # has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment" - # has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person" + # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment" + # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person" # has_one :attachment, as: :attachable # has_one :boss, -> { readonly } # has_one :club, through: :membership - # has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable + # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable # has_one :credit_card, required: true def has_one(name, scope = nil, options = {}) reflection = Builder::HasOne.build(self, name, scope, options) @@ -1721,7 +1721,7 @@ module ActiveRecord # query when you access the associated collection. # # Scope examples: - # has_and_belongs_to_many :projects, -> { includes :milestones, :manager } + # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } # has_and_belongs_to_many :categories, ->(category) { # where("default_category = ?", category.name) # } @@ -1774,7 +1774,7 @@ module ActiveRecord # # Option examples: # has_and_belongs_to_many :projects - # has_and_belongs_to_many :projects, -> { includes :milestones, :manager } + # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } # has_and_belongs_to_many :nations, class_name: "Country" # has_and_belongs_to_many :categories, join_table: "prods_cats" # has_and_belongs_to_many :categories, -> { readonly } diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index a140dc239c..48437a1c9e 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -147,9 +147,9 @@ module ActiveRecord scope.includes! item.includes_values end + scope.unscope!(*item.unscope_values) scope.where_clause += item.where_clause scope.order_values |= item.order_values - scope.unscope!(*item.unscope_values) end reflection = reflection.next diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb index f71b10120f..7864d4c536 100644 --- a/activerecord/lib/active_record/associations/builder/has_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_many.rb @@ -5,7 +5,7 @@ module ActiveRecord::Associations::Builder # :nodoc: end def self.valid_options(options) - super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type] + super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors] end def self.valid_dependent_options diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 256df3ca11..f32dddb8f0 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -1,5 +1,3 @@ -require "active_support/deprecation" - module ActiveRecord module Associations # = Active Record Association Collection diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 81eb5136a1..0e98a3b3a4 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -131,9 +131,9 @@ module ActiveRecord def instantiate(result_set, aliases) primary_key = aliases.column_alias(join_root, join_root.primary_key) - seen = Hash.new { |h,parent_klass| - h[parent_klass] = Hash.new { |i,parent_id| - i[parent_id] = Hash.new { |j,child_klass| j[child_klass] = {} } + seen = Hash.new { |i, object_id| + i[object_id] = Hash.new { |j, child_class| + j[child_class] = {} } } @@ -150,7 +150,8 @@ module ActiveRecord message_bus.instrument('instantiation.active_record', payload) do result_set.each { |row_hash| - parent = parents[row_hash[primary_key]] ||= join_root.instantiate(row_hash, column_aliases) + parent_key = primary_key ? row_hash[primary_key] : row_hash + parent = parents[parent_key] ||= join_root.instantiate(row_hash, column_aliases) construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases) } end @@ -233,7 +234,6 @@ module ActiveRecord def construct(ar_parent, parent, row, rs, seen, model_cache, aliases) return if ar_parent.nil? - primary_id = ar_parent.id parent.children.each do |node| if node.reflection.collection? @@ -253,14 +253,14 @@ module ActiveRecord next end - model = seen[parent.base_klass][primary_id][node.base_klass][id] + model = seen[ar_parent.object_id][node.base_klass][id] if model construct(model, node, row, rs, seen, model_cache, aliases) else model = construct_model(ar_parent, node, row, model_cache, id, aliases) model.readonly! - seen[parent.base_klass][primary_id][node.base_klass][id] = model + seen[ar_parent.object_id][node.base_klass][id] = model construct(model, node, row, rs, seen, model_cache, aliases) end end diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index 3992a240b9..ecf6fb8643 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -54,6 +54,8 @@ module ActiveRecord autoload :BelongsTo, 'active_record/associations/preloader/belongs_to' end + NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, []) + # Eager loads the named associations for the given Active Record record(s). # # In this description, 'association name' shall refer to the name passed @@ -88,9 +90,6 @@ module ActiveRecord # [ :books, :author ] # { author: :avatar } # [ :books, { author: :avatar } ] - - NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, []) - def preload(records, associations, preload_scope = nil) records = Array.wrap(records).compact.uniq associations = Array.wrap(associations) @@ -107,6 +106,7 @@ module ActiveRecord private + # Loads all the given data into +records+ for the +association+. def preloaders_on(association, records, scope) case association when Hash @@ -132,6 +132,11 @@ module ActiveRecord } end + # Loads all the given data into +records+ for a singular +association+. + # + # Functions by instantiating a preloader class such as Preloader::HasManyThrough and + # call the +run+ method for each passed in class in the +records+ argument. + # # Not all records have the same class, so group then preload group on the reflection # itself so that if various subclass share the same association then we do not split # them unnecessarily @@ -181,6 +186,10 @@ module ActiveRecord def self.preloaded_records; []; end end + # Returns a class containing the logic needed to load preload the data + # and attach it to a relation. For example +Preloader::Association+ or + # +Preloader::HasManyThrough+. The class returned implements a `run` method + # that accepts a preloader. def preloader_for(reflection, owners, rhs_klass) return NullPreloader unless rhs_klass diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 7a5a8f8ae6..29dd0643d6 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -12,7 +12,6 @@ module ActiveRecord @preload_scope = preload_scope @model = owners.first && owners.first.class @scope = nil - @owners_by_key = nil @preloaded_records = [] end @@ -56,18 +55,6 @@ module ActiveRecord raise NotImplementedError end - def owners_by_key - @owners_by_key ||= if key_conversion_required? - owners.group_by do |owner| - owner[owner_key_name].to_s - end - else - owners.group_by do |owner| - owner[owner_key_name] - end - end - end - def options reflection.options end @@ -75,32 +62,33 @@ module ActiveRecord private def associated_records_by_owner(preloader) - owners_map = owners_by_key - owner_keys = owners_map.keys.compact - - # Each record may have multiple owners, and vice-versa - records_by_owner = owners.each_with_object({}) do |owner,h| - h[owner] = [] + records = load_records + owners.each_with_object({}) do |owner, result| + result[owner] = records[convert_key(owner[owner_key_name])] || [] end + end - if owner_keys.any? - # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) - # Make several smaller queries if necessary or make one query if the adapter supports it - sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) - - records = load_slices sliced - records.each do |record, owner_key| - owners_map[owner_key].each do |owner| - records_by_owner[owner] << record - end + def owner_keys + unless defined?(@owner_keys) + @owner_keys = owners.map do |owner| + owner[owner_key_name] end + @owner_keys.uniq! + @owner_keys.compact! end - - records_by_owner + @owner_keys end def key_conversion_required? - association_key_type != owner_key_type + @key_conversion_required ||= association_key_type != owner_key_type + end + + def convert_key(key) + if key_conversion_required? + key.to_s + else + key + end end def association_key_type @@ -111,17 +99,17 @@ module ActiveRecord @model.type_for_attribute(owner_key_name.to_s).type end - def load_slices(slices) - @preloaded_records = slices.flat_map { |slice| + def load_records + return {} if owner_keys.empty? + # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) + # Make several smaller queries if necessary or make one query if the adapter supports it + slices = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) + @preloaded_records = slices.flat_map do |slice| records_for(slice) - } - - @preloaded_records.map { |record| - key = record[association_key_name] - key = key.to_s if key_conversion_required? - - [record, key] - } + end + @preloaded_records.group_by do |record| + convert_key(record[association_key_name]) + end end def reflection_scope diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index 03cb8cb8c3..c7cc48ba16 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -1,5 +1,3 @@ -require "active_support/deprecation" - module ActiveRecord module Associations class SingularAssociation < Association #:nodoc: diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index d35bc3e794..fc12c3f45a 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -140,6 +140,8 @@ module ActiveRecord included do Associations::Builder::Association.extensions << AssociationBuilderExtension + mattr_accessor :index_nested_attribute_errors, instance_writer: false + self.index_nested_attribute_errors = false end module ClassMethods # :nodoc: @@ -315,7 +317,7 @@ module ActiveRecord def validate_collection_association(reflection) if association = association_instance_get(reflection.name) if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) - records.each { |record| association_valid?(reflection, record) } + records.each_with_index { |record, index| association_valid?(reflection, record, index) } end end end @@ -323,14 +325,18 @@ module ActiveRecord # Returns whether or not the association is valid and applies any errors to # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt> # enabled records if they're marked_for_destruction? or destroyed. - def association_valid?(reflection, record) + def association_valid?(reflection, record, index=nil) return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?) validation_context = self.validation_context unless [:create, :update].include?(self.validation_context) unless valid = record.valid?(validation_context) if reflection.options[:autosave] record.errors.each do |attribute, message| - attribute = "#{reflection.name}.#{attribute}" + if index.nil? || (!reflection.options[:index_errors] && !ActiveRecord::Base.index_nested_attribute_errors) + attribute = "#{reflection.name}.#{attribute}" + else + attribute = "#{reflection.name}[#{index}].#{attribute}" + end errors[attribute] << message errors[attribute].uniq! end diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index bfedc4af3f..cfd8cbda67 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -292,10 +292,15 @@ module ActiveRecord end def destroy #:nodoc: + @_destroy_callback_already_called ||= false + return if @_destroy_callback_already_called + @_destroy_callback_already_called = true _run_destroy_callbacks { super } rescue RecordNotDestroyed => e @_association_destroy_exception = e false + ensure + @_destroy_callback_already_called = false end def touch(*) #:nodoc: 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 dbacf56795..848aeb821c 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -29,7 +29,17 @@ module ActiveRecord # Returns an ActiveRecord::Result instance. def select_all(arel, name = nil, binds = []) arel, binds = binds_from_relation arel, binds - select(to_sql(arel, binds), name, binds) + sql = to_sql(arel, binds) + if arel.is_a?(String) + preparable = false + else + preparable = visitor.preparable + end + if prepared_statements && preparable + select_prepared(sql, name, binds) + else + select(sql, name, binds) + end end # Returns a record hash with the column names as keys and column values @@ -67,7 +77,7 @@ module ActiveRecord # Executes +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. - def exec_query(sql, name = 'SQL', binds = []) + def exec_query(sql, name = 'SQL', binds = [], prepare: false) end # Executes insert +sql+ statement in the context of this connection using @@ -358,9 +368,12 @@ module ActiveRecord # Returns an ActiveRecord::Result instance. def select(sql, name = nil, binds = []) - exec_query(sql, name, binds) + exec_query(sql, name, binds, prepare: false) end + def select_prepared(sql, name = nil, binds = []) + exec_query(sql, name, binds, prepare: true) + end # Returns the last auto-generated ID from the affected table. def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index bceda5abd9..e2ef56798b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -210,7 +210,7 @@ module ActiveRecord # An array of ColumnDefinition objects, representing the column changes # that have been defined. attr_accessor :indexes - attr_reader :name, :temporary, :options, :as, :foreign_keys + attr_reader :name, :temporary, :options, :as, :foreign_keys, :native def initialize(types, name, temporary, options, as = nil) @columns_hash = {} @@ -238,86 +238,19 @@ module ActiveRecord end # Instantiates a new column for the table. - # The +type+ parameter is normally one of the migrations native types, - # which is one of the following: - # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>, - # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>, - # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>, - # <tt>:binary</tt>, <tt>:boolean</tt>. - # - # You may use a type not in this list as long as it is supported by your - # database (for example, "polygon" in MySQL), but this will not be database - # agnostic and should usually be avoided. - # - # Available options are (none of these exists by default): - # * <tt>:limit</tt> - - # Requests a maximum column length. This is number of characters for a <tt>:string</tt> column - # and number of bytes for <tt>:text</tt>, <tt>:binary</tt> and <tt>:integer</tt> columns. - # * <tt>:default</tt> - - # The column's default value. Use nil for NULL. - # * <tt>:null</tt> - - # Allows or disallows +NULL+ values in the column. This option could - # have been named <tt>:null_allowed</tt>. - # * <tt>:precision</tt> - - # Specifies the precision for a <tt>:decimal</tt> column. - # * <tt>:scale</tt> - - # Specifies the scale for a <tt>:decimal</tt> column. + # See {connection.add_column}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_column] + # for available options. + # + # Additional options are: # * <tt>:index</tt> - # Create an index for the column. Can be either <tt>true</tt> or an options hash. # - # Note: The precision is the total number of significant digits - # and the scale is the number of digits that can be stored following - # the decimal point. For example, the number 123.45 has a precision of 5 - # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can - # range from -999.99 to 999.99. - # - # Please be aware of different RDBMS implementations behavior with - # <tt>:decimal</tt> columns: - # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <= - # <tt>:precision</tt>, and makes no comments about the requirements of - # <tt>:precision</tt>. - # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30]. - # Default is (10,0). - # * PostgreSQL: <tt>:precision</tt> [1..infinity], - # <tt>:scale</tt> [0..infinity]. No default. - # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used. - # Internal storage as strings. No default. - # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>, - # but the maximum supported <tt>:precision</tt> is 16. No default. - # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127]. - # Default is (38,0). - # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62]. - # Default unknown. - # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38]. - # Default (38,0). - # # This method returns <tt>self</tt>. # # == Examples - # # Assuming +td+ is an instance of TableDefinition - # td.column(:granted, :boolean) - # # granted BOOLEAN - # - # td.column(:picture, :binary, limit: 2.megabytes) - # # => picture BLOB(2097152) - # - # td.column(:sales_stage, :string, limit: 20, default: 'new', null: false) - # # => sales_stage VARCHAR(20) DEFAULT 'new' NOT NULL - # - # td.column(:bill_gates_money, :decimal, precision: 15, scale: 2) - # # => bill_gates_money DECIMAL(15,2) # - # td.column(:sensor_reading, :decimal, precision: 30, scale: 20) - # # => sensor_reading DECIMAL(30,20) - # - # # While <tt>:scale</tt> defaults to zero on most databases, it - # # probably wouldn't hurt to include it. - # td.column(:huge_integer, :decimal, precision: 30) - # # => huge_integer DECIMAL(30) - # - # # Defines a column with a database-specific type. - # td.column(:foo, 'polygon') - # # => foo polygon + # # Assuming +td+ is an instance of TableDefinition + # td.column(:granted, :boolean, index: true) # # == Short-hand examples # @@ -455,10 +388,6 @@ module ActiveRecord ColumnDefinition.new name, type end - def native - @native - end - def aliased_types(name, fallback) 'timestamp' == name ? :datetime : fallback end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index d3fbc18f97..d5f8dbc8fc 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -446,12 +446,81 @@ module ActiveRecord execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}" end - # Adds a new column to the named table. - # See TableDefinition#column for details of the options you can use. - # - # Note: Not all options will be available, generally this command should - # ignore most of them. In favor of doing a low-level call to simply - # create a column. + # Add a new +type+ column named +column_name+ to +table_name+. + # + # The +type+ parameter is normally one of the migrations native types, + # which is one of the following: + # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>, + # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>, + # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>, + # <tt>:binary</tt>, <tt>:boolean</tt>. + # + # You may use a type not in this list as long as it is supported by your + # database (for example, "polygon" in MySQL), but this will not be database + # agnostic and should usually be avoided. + # + # Available options are (none of these exists by default): + # * <tt>:limit</tt> - + # Requests a maximum column length. This is number of characters for a <tt>:string</tt> column + # and number of bytes for <tt>:text</tt>, <tt>:binary</tt> and <tt>:integer</tt> columns. + # * <tt>:default</tt> - + # The column's default value. Use nil for NULL. + # * <tt>:null</tt> - + # Allows or disallows +NULL+ values in the column. This option could + # have been named <tt>:null_allowed</tt>. + # * <tt>:precision</tt> - + # Specifies the precision for a <tt>:decimal</tt> column. + # * <tt>:scale</tt> - + # Specifies the scale for a <tt>:decimal</tt> column. + # + # Note: The precision is the total number of significant digits + # and the scale is the number of digits that can be stored following + # the decimal point. For example, the number 123.45 has a precision of 5 + # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can + # range from -999.99 to 999.99. + # + # Please be aware of different RDBMS implementations behavior with + # <tt>:decimal</tt> columns: + # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <= + # <tt>:precision</tt>, and makes no comments about the requirements of + # <tt>:precision</tt>. + # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30]. + # Default is (10,0). + # * PostgreSQL: <tt>:precision</tt> [1..infinity], + # <tt>:scale</tt> [0..infinity]. No default. + # * SQLite2: Any <tt>:precision</tt> and <tt>:scale</tt> may be used. + # Internal storage as strings. No default. + # * SQLite3: No restrictions on <tt>:precision</tt> and <tt>:scale</tt>, + # but the maximum supported <tt>:precision</tt> is 16. No default. + # * Oracle: <tt>:precision</tt> [1..38], <tt>:scale</tt> [-84..127]. + # Default is (38,0). + # * DB2: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..62]. + # Default unknown. + # * SqlServer?: <tt>:precision</tt> [1..38], <tt>:scale</tt> [0..38]. + # Default (38,0). + # + # == Examples + # + # add_column(:users, :picture, :binary, limit: 2.megabytes) + # # ALTER TABLE "users" ADD "picture" blob(2097152) + # + # add_column(:articles, :status, :string, limit: 20, default: 'draft', null: false) + # # ALTER TABLE "articles" ADD "status" varchar(20) DEFAULT 'draft' NOT NULL + # + # add_column(:answers, :bill_gates_money, :decimal, precision: 15, scale: 2) + # # ALTER TABLE "answers" ADD "bill_gates_money" decimal(15,2) + # + # add_column(:measurements, :sensor_reading, :decimal, precision: 30, scale: 20) + # # ALTER TABLE "measurements" ADD "sensor_reading" decimal(30,20) + # + # # While :scale defaults to zero on most databases, it + # # probably wouldn't hurt to include it. + # add_column(:measurements, :huge_integer, :decimal, precision: 30) + # # ALTER TABLE "measurements" ADD "huge_integer" decimal(30) + # + # # Defines a column with a database-specific type. + # add_column(:shapes, :triangle, 'polygon') + # # ALTER TABLE "shapes" ADD "triangle" polygon def add_column(table_name, column_name, type, options = {}) at = create_alter_table table_name at.add_column(column_name, type, options) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 9b46df721a..402159ac13 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -1,5 +1,6 @@ require 'active_record/type' require 'active_support/core_ext/benchmark' +require 'active_record/connection_adapters/determine_if_preparable_visitor' require 'active_record/connection_adapters/schema_cache' require 'active_record/connection_adapters/sql_type_metadata' require 'active_record/connection_adapters/abstract/schema_dumper' diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index f710ec10fc..251acf1c83 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -134,6 +134,7 @@ module ActiveRecord time: { name: "time" }, date: { name: "date" }, binary: { name: "blob" }, + blob: { name: "blob" }, boolean: { name: "tinyint", limit: 1 }, bigint: { name: "bigint" }, json: { name: "json" }, @@ -152,6 +153,7 @@ module ActiveRecord if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) @prepared_statements = true + @visitor.extend(DetermineIfPreparableVisitor) else @prepared_statements = false end @@ -167,6 +169,10 @@ module ActiveRecord end end + def version + @version ||= Version.new(full_version.match(/^\d+\.\d+\.\d+/)[0]) + end + # Returns true, since this connection adapter supports migrations. def supports_migrations? true @@ -477,7 +483,10 @@ module ActiveRecord end def tables(name = nil) # :nodoc: - select_values("SHOW FULL TABLES", 'SCHEMA') + sql = "SELECT table_name FROM information_schema.tables " + sql << "WHERE table_schema = #{quote(@config[:database])}" + + select_values(sql, 'SCHEMA') end alias data_sources tables @@ -679,12 +688,18 @@ module ActiveRecord # Maps logical Rails types to MySQL-specific data types. def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil) sql = case type.to_s - when 'binary' - binary_to_sql(limit) when 'integer' integer_to_sql(limit) when 'text' text_to_sql(limit) + when 'blob' + binary_to_sql(limit) + when 'binary' + if (0..0xfff) === limit + "varbinary(#{limit})" + else + binary_to_sql(limit) + end else super(type, limit, precision, scale) end @@ -924,10 +939,6 @@ module ActiveRecord subselect.from subsubselect.distinct.as('__active_record_temp') end - def version - @version ||= Version.new(full_version.match(/^\d+\.\d+\.\d+/)[0]) - end - def mariadb? full_version =~ /mariadb/i end @@ -997,15 +1008,6 @@ module ActiveRecord MySQL::TableDefinition.new(native_database_types, name, temporary, options, as) end - def binary_to_sql(limit) # :nodoc: - case limit - when 0..0xfff; "varbinary(#{limit})" - when nil; "blob" - when 0x1000..0xffffffff; "blob(#{limit})" - else raise(ActiveRecordError, "No binary type has byte length #{limit}") - end - end - def integer_to_sql(limit) # :nodoc: case limit when 1; 'tinyint' @@ -1028,6 +1030,16 @@ module ActiveRecord end end + def binary_to_sql(limit) # :nodoc: + case limit + when 0..0xff; 'tinyblob' + when nil, 0x100..0xffff; 'blob' + when 0x10000..0xffffff; 'mediumblob' + when 0x1000000..0xffffffff; 'longblob' + else raise(ActiveRecordError, "No binary type has byte length #{limit}") + end + end + class MysqlJson < Type::Internal::AbstractJson # :nodoc: def changed_in_place?(raw_old_value, new_value) # Normalization is required because MySQL JSON data format includes diff --git a/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb new file mode 100644 index 0000000000..0fdc185c45 --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb @@ -0,0 +1,22 @@ +module ActiveRecord + module ConnectionAdapters + module DetermineIfPreparableVisitor + attr_reader :preparable + + def accept(*) + @preparable = true + super + end + + def visit_Arel_Nodes_In(*) + @preparable = false + super + end + + def visit_Arel_Nodes_SqlLiteral(*) + @preparable = false + super + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb index bcf397cd77..29e8c73d46 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb @@ -7,6 +7,10 @@ module ActiveRecord super end + def blob(*args, **options) + args.each { |name| column(name, :blob, options) } + end + def json(*args, **options) args.each { |name| column(name, :json, options) } end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb index 6448b8b5e2..3c48d0554e 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb @@ -27,6 +27,14 @@ module ActiveRecord private + def schema_type(column) + if column.sql_type == 'tinyblob' + 'blob' + else + super + end + end + def schema_limit(column) super unless column.type == :boolean end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 4461722bb4..42c4a14f00 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -126,7 +126,9 @@ module ActiveRecord # 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 = []) - execute(sql, name).to_a + result = execute(sql, name) + @connection.next_result while @connection.more_results? + result.to_a end # Executes the SQL statement in the context of this connection. @@ -140,8 +142,9 @@ module ActiveRecord super end - def exec_query(sql, name = 'SQL', binds = []) + def exec_query(sql, name = 'SQL', binds = [], prepare: false) result = execute(sql, name) + @connection.next_result while @connection.more_results? ActiveRecord::Result.new(result.fields, result.to_a) end diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index b3894481cc..fddb318553 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -235,11 +235,11 @@ module ActiveRecord @client_encoding = ENCODINGS[result.rows.last.last] end - def exec_query(sql, name = 'SQL', binds = []) + def exec_query(sql, name = 'SQL', binds = [], prepare: false) if without_prepared_statement?(binds) result_set, affected_rows = exec_without_stmt(sql, name) else - result_set, affected_rows = exec_stmt(sql, name, binds) + result_set, affected_rows = exec_stmt(sql, name, binds, cache_stmt: prepare) end yield affected_rows if block_given? @@ -378,12 +378,12 @@ module ActiveRecord private - def exec_stmt(sql, name, binds) + def exec_stmt(sql, name, binds, cache_stmt: false) cache = {} type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) } log(sql, name, binds) do - if binds.empty? + if !cache_stmt stmt = @connection.prepare(sql) else cache = @statements[sql] ||= { @@ -399,7 +399,7 @@ module ActiveRecord # place when an error occurs. To support older MySQL versions, we # need to close the statement and delete the statement from the # cache. - if binds.empty? + if !cache_stmt stmt.close else @statements.delete sql @@ -417,7 +417,7 @@ module ActiveRecord affected_rows = stmt.affected_rows stmt.free_result - stmt.close if binds.empty? + stmt.close if !cache_stmt [result_set, affected_rows] 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 43e18ebb2b..0e0c0e993a 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb @@ -156,8 +156,8 @@ module ActiveRecord end end - def exec_query(sql, name = 'SQL', binds = []) - execute_and_clear(sql, name, binds) do |result| + def exec_query(sql, name = 'SQL', binds = [], prepare: false) + execute_and_clear(sql, name, binds, prepare: prepare) do |result| types = {} fields = result.fields fields.each_with_index do |fname, i| diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 0686b35425..236c067fd5 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -198,6 +198,7 @@ module ActiveRecord @visitor = Arel::Visitors::PostgreSQL.new self if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) @prepared_statements = true + @visitor.extend(DetermineIfPreparableVisitor) else @prepared_statements = false end @@ -553,16 +554,22 @@ module ActiveRecord FEATURE_NOT_SUPPORTED = "0A000" #:nodoc: - def execute_and_clear(sql, name, binds) - result = without_prepared_statement?(binds) ? exec_no_cache(sql, name, binds) : - exec_cache(sql, name, binds) + def execute_and_clear(sql, name, binds, prepare: false) + if without_prepared_statement?(binds) + result = exec_no_cache(sql, name, []) + elsif !prepare + result = exec_no_cache(sql, name, binds) + else + result = exec_cache(sql, name, binds) + end ret = yield result result.clear ret end def exec_no_cache(sql, name, binds) - log(sql, name, binds) { @connection.async_exec(sql, []) } + type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) } + log(sql, name, binds) { @connection.async_exec(sql, type_casted_binds) } end def exec_cache(sql, name, binds) diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 505a71720f..9028c1fcb9 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -89,6 +89,7 @@ module ActiveRecord if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) @prepared_statements = true + @visitor.extend(DetermineIfPreparableVisitor) else @prepared_statements = false end @@ -231,15 +232,18 @@ module ActiveRecord end end - def exec_query(sql, name = nil, binds = []) + def exec_query(sql, name = nil, binds = [], prepare: false) type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) } log(sql, name, binds) do # Don't cache statements if they are not prepared - if without_prepared_statement?(binds) + unless prepare stmt = @connection.prepare(sql) begin cols = stmt.columns + unless without_prepared_statement?(binds) + stmt.bind_params(type_casted_binds) + end records = stmt.to_a ensure stmt.close @@ -252,7 +256,7 @@ module ActiveRecord stmt = cache[:stmt] cols = cache[:cols] ||= stmt.columns stmt.reset! - stmt.bind_params type_casted_binds + stmt.bind_params(type_casted_binds) end ActiveRecord::Result.new(cols, stmt.to_a) @@ -307,22 +311,18 @@ module ActiveRecord # SCHEMA STATEMENTS ======================================== - def tables(name = nil, table_name = nil) #:nodoc: - sql = <<-SQL - SELECT name - FROM sqlite_master - WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence' - SQL - sql << " AND name = #{quote_table_name(table_name)}" if table_name - - exec_query(sql, 'SCHEMA').map do |row| - row['name'] - end + def tables(name = nil) # :nodoc: + select_values("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'", 'SCHEMA') end alias data_sources tables def table_exists?(table_name) - table_name && tables(nil, table_name).any? + return false unless table_name.present? + + sql = "SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name <> 'sqlite_sequence'" + sql << " AND name = #{quote(table_name)}" + + select_values(sql, 'SCHEMA').any? end alias data_source_exists? table_exists? diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index db3e9d1d52..142b6e8599 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -177,7 +177,7 @@ module ActiveRecord hash = args.first return super if hash.values.any? { |v| - v.nil? || Array === v || Hash === v + v.nil? || Array === v || Hash === v || Relation === v } # We can't cache Post.find_by(author: david) ...yet diff --git a/activerecord/lib/active_record/explain_subscriber.rb b/activerecord/lib/active_record/explain_subscriber.rb index 9adabd7819..90bcf5a205 100644 --- a/activerecord/lib/active_record/explain_subscriber.rb +++ b/activerecord/lib/active_record/explain_subscriber.rb @@ -14,7 +14,7 @@ module ActiveRecord end # SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on - # our own EXPLAINs now matter how loopingly beautiful that would be. + # our own EXPLAINs no matter how loopingly beautiful that would be. # # 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. diff --git a/activerecord/lib/active_record/integration.rb b/activerecord/lib/active_record/integration.rb index 19d2589db3..466c8509a4 100644 --- a/activerecord/lib/active_record/integration.rb +++ b/activerecord/lib/active_record/integration.rb @@ -10,9 +10,9 @@ module ActiveRecord # Indicates the format used to generate the timestamp in the cache key. # Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>. # - # This is +:nsec+, by default. + # This is +:usec+, by default. class_attribute :cache_timestamp_format, :instance_writer => false - self.cache_timestamp_format = :nsec + self.cache_timestamp_format = :usec end # Returns a String, which Action Pack uses for constructing a URL to this diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 90b8a29869..c8b96b8de0 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -194,17 +194,18 @@ module ActiveRecord # # == Available transformations # + # === Creation + # + # * <tt>create_join_table(table_1, table_2, options)</tt>: Creates a join + # table having its name as the lexical order of the first two + # arguments. See + # ActiveRecord::ConnectionAdapters::SchemaStatements#create_join_table for + # details. # * <tt>create_table(name, options)</tt>: Creates a table called +name+ and # makes the table object available to a block that can then add columns to it, # following the same format as +add_column+. See example above. The options hash # is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create # table definition. - # * <tt>drop_table(name)</tt>: Drops the table called +name+. - # * <tt>change_table(name, options)</tt>: Allows to make column alterations to - # the table called +name+. It makes the table object available to a block that - # can then add/remove columns, indexes or foreign keys to it. - # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ - # to +new_name+. # * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column # to the table called +table_name+ # named +column_name+ specified to be one of the following types: @@ -215,24 +216,59 @@ module ActiveRecord # Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g. # <tt>{ limit: 50, null: false }</tt>) -- see # ActiveRecord::ConnectionAdapters::TableDefinition#column for details. - # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames - # a column but keeps the type and content. - # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes - # the column to a different type using the same parameters as add_column. - # * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column - # named +column_name+ from the table called +table_name+. + # * <tt>add_foreign_key(from_table, to_table, options)</tt>: Adds a new + # foreign key. +from_table+ is the table with the key column, +to_table+ contains + # the referenced primary key. # * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index # with the name of the column. Other options include # <tt>:name</tt>, <tt>:unique</tt> (e.g. # <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt> # (e.g. <tt>{ order: { name: :desc } }</tt>). + # * <tt>add_reference(:table_name, :reference_name)</tt>: Adds a new column + # +reference_name_id+ by default an integer. See + # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details. + # * <tt>add_timestamps(table_name, options)</tt>: Adds timestamps (+created_at+ + # and +updated_at+) columns to +table_name+. + # + # === Modification + # + # * <tt>change_column(table_name, column_name, type, options)</tt>: Changes + # the column to a different type using the same parameters as add_column. + # * <tt>change_column_default(table_name, column_name, default)</tt>: Sets a + # default value for +column_name+ definded by +default+ on +table_name+. + # * <tt>change_column_null(table_name, column_name, null, default = nil)</tt>: + # Sets or removes a +NOT NULL+ constraint on +column_name+. The +null+ flag + # indicates whether the value can be +NULL+. See + # ActiveRecord::ConnectionAdapters::SchemaStatements#change_column_null for + # details. + # * <tt>change_table(name, options)</tt>: Allows to make column alterations to + # the table called +name+. It makes the table object available to a block that + # can then add/remove columns, indexes or foreign keys to it. + # * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames + # a column but keeps the type and content. + # * <tt>rename_index(table_name, old_name, new_name)</tt>: Renames an index. + # * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ + # to +new_name+. + # + # === Deletion + # + # * <tt>drop_table(name)</tt>: Drops the table called +name+. + # * <tt>drop_join_table(table_1, table_2, options)</tt>: Drops the join table + # specified by the given arguments. + # * <tt>remove_column(table_name, column_name, type, options)</tt>: Removes the column + # named +column_name+ from the table called +table_name+. + # * <tt>remove_columns(table_name, *column_names)</tt>: Removes the given + # columns from the table definition. + # * <tt>remove_foreign_key(from_table, options_or_to_table)</tt>: Removes the + # given foreign key from the table called +table_name+. # * <tt>remove_index(table_name, column: column_names)</tt>: Removes the index # specified by +column_names+. # * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index # specified by +index_name+. - # * <tt>add_reference(:table_name, :reference_name)</tt>: Adds a new column - # +reference_name_id+ by default an integer. See - # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details. + # * <tt>remove_reference(table_name, ref_name, options)</tt>: Removes the + # reference(s) on +table_name+ specified by +ref_name+. + # * <tt>remove_timestamps(table_name, options)</tt>: Removes the timestamp + # columns (+created_at+ and +updated_at+) from the table definition. # # == Irreversible transformations # diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index d940ac244a..b6f3695856 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -34,7 +34,7 @@ db_namespace = namespace :db do end end - # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases." + # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases." task :purge => [:load_config] do ActiveRecord::Tasks::DatabaseTasks.purge_current end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 16d5774fec..f45844a9ea 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -219,6 +219,8 @@ module ActiveRecord end def aggregate_column(column_name) + return column_name if Arel::Expressions === column_name + if @klass.column_names.include?(column_name.to_s) Arel::Attribute.new(@klass.unscoped.table, column_name) else @@ -273,15 +275,10 @@ module ActiveRecord else group_fields = group_attrs end + group_fields = arel_columns(group_fields) - group_aliases = group_fields.map { |field| - column_alias_for(field) - } - group_columns = group_aliases.zip(group_fields).map { |aliaz,field| - [aliaz, field] - } - - group = group_fields + group_aliases = group_fields.map { |field| column_alias_for(field) } + group_columns = group_aliases.zip(group_fields) if operation == 'count' && column_name == :all aggregate_alias = 'count_all' @@ -297,7 +294,7 @@ module ActiveRecord ] select_values += select_values unless having_clause.empty? - select_values.concat group_fields.zip(group_aliases).map { |field,aliaz| + select_values.concat group_columns.map { |aliaz, field| if field.respond_to?(:as) field.as(aliaz) else @@ -306,7 +303,7 @@ module ActiveRecord } relation = except(:group) - relation.group_values = group + relation.group_values = group_fields relation.select_values = select_values calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes) @@ -367,9 +364,9 @@ module ActiveRecord end end - # TODO: refactor to allow non-string `select_values` (eg. Arel nodes). def select_for_count if select_values.present? + return select_values.first if select_values.one? select_values.join(", ") else :all diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 0dcecbd42d..f5afc1000d 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -375,7 +375,7 @@ module ActiveRecord # # This means it can be used in association definitions: # - # has_many :comments, -> { unscope where: :trashed } + # has_many :comments, -> { unscope(where: :trashed) } # def unscope(*args) check_if_method_has_arguments!(:unscope, args) @@ -552,8 +552,6 @@ module ActiveRecord WhereChain.new(spawn) elsif opts.blank? self - elsif !opts.is_a?(String) && !opts.respond_to?(:to_h) - raise ArgumentError, "Unsupported argument type: #{opts} (#{opts.class})" else spawn.where!(opts, *rest) end diff --git a/activerecord/lib/active_record/relation/where_clause_factory.rb b/activerecord/lib/active_record/relation/where_clause_factory.rb index 83ac074f97..a81ff98e49 100644 --- a/activerecord/lib/active_record/relation/where_clause_factory.rb +++ b/activerecord/lib/active_record/relation/where_clause_factory.rb @@ -20,8 +20,10 @@ module ActiveRecord attributes, binds = predicate_builder.create_binds(attributes) parts = predicate_builder.build_from_hash(attributes) - else + when Arel::Nodes::Node parts = [opts] + else + raise ArgumentError, "Unsupported argument type: #{opts} (#{opts.class})" end WhereClause.new(parts, binds) diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index 17bc066e4d..cdcb73382f 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -17,7 +17,7 @@ module ActiveRecord # # class Post < ActiveRecord::Base # def self.default_scope - # where published: true + # where(published: true) # end # end # diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index ea7927a435..c0c29a618c 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -94,8 +94,9 @@ module ActiveRecord rescue DatabaseAlreadyExists $stderr.puts "#{configuration['database']} already exists" rescue Exception => error - $stderr.puts error, *(error.backtrace) + $stderr.puts error $stderr.puts "Couldn't create database for #{configuration.inspect}" + raise end def create_all @@ -115,8 +116,9 @@ module ActiveRecord rescue ActiveRecord::NoDatabaseError $stderr.puts "Database '#{configuration['database']}' does not exist" rescue Exception => error - $stderr.puts error, *(error.backtrace) + $stderr.puts error $stderr.puts "Couldn't drop #{configuration['database']}" + raise end def drop_all diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index 9ab64d0325..9ec3c8a94a 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -19,11 +19,15 @@ module ActiveRecord path = Pathname.new configuration['database'] file = path.absolute? ? path.to_s : File.join(root, path) - FileUtils.rm(file) if File.exist?(file) + FileUtils.rm(file) + rescue Errno::ENOENT => error + raise NoDatabaseError.new(error.message, error) end def purge drop + rescue NoDatabaseError + ensure create end diff --git a/activerecord/lib/rails/generators/active_record/migration.rb b/activerecord/lib/rails/generators/active_record/migration.rb index b7418cf42f..c2b2209638 100644 --- a/activerecord/lib/rails/generators/active_record/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration.rb @@ -13,6 +13,13 @@ module ActiveRecord ActiveRecord::Migration.next_migration_number(next_migration_number) end end + + private + + def primary_key_type + key_type = options[:primary_key_type] + ", id: :#{key_type}" if key_type + end end end end diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb index 0d57de4d65..4e5872b585 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -5,6 +5,8 @@ module ActiveRecord class MigrationGenerator < Base # :nodoc: argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]" + class_option :primary_key_type, type: :string, desc: "The type for primary key" + def create_migration_file set_local_assigns! validate_file_name! diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb index 5b3e57dcf6..fadab2a1e6 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb @@ -1,6 +1,6 @@ class <%= migration_class_name %> < ActiveRecord::Migration def change - create_table :<%= table_name %> do |t| + create_table :<%= table_name %><%= primary_key_type %> do |t| <% attributes.each do |attribute| -%> <% if attribute.password_digest? -%> t.string :password_digest<%= attribute.inject_options %> diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index 7e8d68ce69..395951ac9d 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -7,14 +7,13 @@ module ActiveRecord check_class_collision - class_option :migration, :type => :boolean - class_option :timestamps, :type => :boolean - class_option :parent, :type => :string, :desc => "The parent class for the generated model" - class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns" + class_option :migration, type: :boolean + class_option :timestamps, type: :boolean + class_option :parent, type: :string, desc: "The parent class for the generated model" + class_option :indexes, type: :boolean, default: true, desc: "Add indexes for references and belongs_to columns" + class_option :primary_key_type, type: :string, desc: "The type for primary key" - # creates the migration file for the model. - def create_migration_file return unless options[:migration] && options[:parent].nil? attributes.each { |a| a.attr_options.delete(:index) if a.reference? && !a.has_index? } if options[:indexes] == false diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 5699fa110f..decac9e83b 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -118,15 +118,6 @@ class MysqlConnectionTest < ActiveRecord::MysqlTestCase end end - # Test that MySQL allows multiple results for stored procedures - if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) - def test_multi_results - rows = ActiveRecord::Base.connection.select_rows('CALL ten();') - assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" - assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" - end - end - def test_mysql_connection_collation_is_configured assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection') assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection') diff --git a/activerecord/test/cases/adapters/mysql/sp_test.rb b/activerecord/test/cases/adapters/mysql/sp_test.rb index a3d5110032..579c3273c6 100644 --- a/activerecord/test/cases/adapters/mysql/sp_test.rb +++ b/activerecord/test/cases/adapters/mysql/sp_test.rb @@ -1,15 +1,29 @@ require "cases/helper" require 'models/topic' +require 'models/reply' -class StoredProcedureTest < ActiveRecord::MysqlTestCase +class MysqlStoredProcedureTest < ActiveRecord::MysqlTestCase fixtures :topics + def setup + @connection = ActiveRecord::Base.connection + end + # Test that MySQL allows multiple results for stored procedures - if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) + # + # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default. + # http://dev.mysql.com/doc/refman/5.6/en/call.html + if ActiveRecord::Base.connection.version >= '5.6.0' || Mysql.const_defined?(:CLIENT_MULTI_RESULTS) + def test_multi_results + rows = @connection.select_rows('CALL ten();') + assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" + assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'" + end + def test_multi_results_from_find_by_sql - topics = Topic.find_by_sql 'CALL topics();' - assert_equal 1, topics.size - assert ActiveRecord::Base.connection.active?, "Bad connection use by 'MysqlAdapter.select'" + topics = Topic.find_by_sql 'CALL topics(3);' + assert_equal 3, topics.size + assert @connection.active?, "Bad connection use by 'MysqlAdapter.select'" end end end diff --git a/activerecord/test/cases/adapters/mysql/sql_types_test.rb b/activerecord/test/cases/adapters/mysql/sql_types_test.rb index 25b28de7f0..d18579f242 100644 --- a/activerecord/test/cases/adapters/mysql/sql_types_test.rb +++ b/activerecord/test/cases/adapters/mysql/sql_types_test.rb @@ -4,7 +4,7 @@ class MysqlSqlTypesTest < ActiveRecord::MysqlTestCase def test_binary_types assert_equal 'varbinary(64)', type_to_sql(:binary, 64) assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095) - assert_equal 'blob(4096)', type_to_sql(:binary, 4096) + assert_equal 'blob', type_to_sql(:binary, 4096) assert_equal 'blob', type_to_sql(:binary) end diff --git a/activerecord/test/cases/adapters/mysql2/sp_test.rb b/activerecord/test/cases/adapters/mysql2/sp_test.rb new file mode 100644 index 0000000000..8b12945f24 --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/sp_test.rb @@ -0,0 +1,29 @@ +require "cases/helper" +require 'models/topic' +require 'models/reply' + +class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase + fixtures :topics + + def setup + @connection = ActiveRecord::Base.connection + end + + # Test that MySQL allows multiple results for stored procedures + # + # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default. + # http://dev.mysql.com/doc/refman/5.6/en/call.html + if ActiveRecord::Base.connection.version >= '5.6.0' + def test_multi_results + rows = @connection.select_rows('CALL ten();') + assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" + assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'" + end + + def test_multi_results_from_find_by_sql + topics = Topic.find_by_sql 'CALL topics(3);' + assert_equal 3, topics.size + assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select'" + end + end +end diff --git a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb index ae505d29c9..4926bc2267 100644 --- a/activerecord/test/cases/adapters/mysql2/sql_types_test.rb +++ b/activerecord/test/cases/adapters/mysql2/sql_types_test.rb @@ -4,7 +4,7 @@ class Mysql2SqlTypesTest < ActiveRecord::Mysql2TestCase def test_binary_types assert_equal 'varbinary(64)', type_to_sql(:binary, 64) assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095) - assert_equal 'blob(4096)', type_to_sql(:binary, 4096) + assert_equal 'blob', type_to_sql(:binary, 4096) assert_equal 'blob', type_to_sql(:binary) end diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 820d41e13b..722e2377c1 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -127,7 +127,7 @@ module ActiveRecord def test_statement_key_is_logged bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new) - @connection.exec_query('SELECT $1::integer', 'SQL', [bind]) + @connection.exec_query('SELECT $1::integer', 'SQL', [bind], prepare: true) name = @subscriber.payloads.last[:statement_name] assert name res = @connection.exec_query("EXPLAIN (FORMAT JSON) EXECUTE #{name}(1)") diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index f89a394f96..93e98ec872 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -168,7 +168,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase def test_raise_wraped_exception_on_bad_prepare assert_raises(ActiveRecord::StatementInvalid) do - @connection.exec_query "select * from developers where id = ?", 'sql', [[nil, 1]] + @connection.exec_query "select * from developers where id = ?", 'sql', [bind_param(1)] end end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 77d99bc116..640df31e2e 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -294,7 +294,7 @@ module ActiveRecord def test_tables_logs_name sql = <<-SQL SELECT name FROM sqlite_master - WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence' + WHERE type IN ('table','view') AND name <> 'sqlite_sequence' SQL assert_logged [[sql.squish, 'SCHEMA', []]] do @conn.tables('hello') @@ -313,8 +313,7 @@ module ActiveRecord with_example_table do sql = <<-SQL SELECT name FROM sqlite_master - WHERE (type = 'table' OR type = 'view') - AND NOT name = 'sqlite_sequence' AND name = \"ex\" + WHERE type IN ('table','view') AND name <> 'sqlite_sequence' AND name = 'ex' SQL assert_logged [[sql.squish, 'SCHEMA', []]] do assert @conn.table_exists?('ex') diff --git a/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb b/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb new file mode 100644 index 0000000000..2b867965ba --- /dev/null +++ b/activerecord/test/cases/associations/bidirectional_destroy_dependencies_test.rb @@ -0,0 +1,41 @@ +require 'cases/helper' +require 'models/content' + +class BidirectionalDestroyDependenciesTest < ActiveRecord::TestCase + fixtures :content, :content_positions + + def setup + Content.destroyed_ids.clear + ContentPosition.destroyed_ids.clear + end + + def test_bidirectional_dependence_when_destroying_item_with_belongs_to_association + content_position = ContentPosition.find(1) + content = content_position.content + assert_not_nil content + + content_position.destroy + + assert_equal [content_position.id], ContentPosition.destroyed_ids + assert_equal [content.id], Content.destroyed_ids + end + + def test_bidirectional_dependence_when_destroying_item_with_has_one_association + content = Content.find(1) + content_position = content.content_position + assert_not_nil content_position + + content.destroy + + assert_equal [content.id], Content.destroyed_ids + assert_equal [content_position.id], ContentPosition.destroyed_ids + end + + def test_bidirectional_dependence_when_destroying_item_with_has_one_association_fails_first_time + content = ContentWhichRequiresTwoDestroyCalls.find(1) + + 2.times { content.destroy } + + assert_equal content.destroyed?, true + end +end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index ddfb856a05..bc1bff79d3 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -24,6 +24,8 @@ require 'models/membership' require 'models/club' require 'models/categorization' require 'models/sponsor' +require 'models/mentor' +require 'models/contract' class EagerAssociationTest < ActiveRecord::TestCase fixtures :posts, :comments, :authors, :essays, :author_addresses, :categories, :categories_posts, @@ -1218,6 +1220,16 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length } end + def test_eager_load_multiple_associations_with_references + mentor = Mentor.create!(name: "Barış Can DAYLIK") + developer = Developer.create!(name: "Mehmet Emin İNAÇ", mentor: mentor) + Contract.create!(developer: developer) + project = Project.create!(name: "VNGRS", mentor: mentor) + project.developers << developer + projects = Project.references(:mentors).includes(mentor: { developers: :contracts }, developers: :contracts) + assert_equal projects.last.mentor.developers.first.contracts, projects.last.developers.last.contracts + end + test "scoping with a circular preload" do assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) } end diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 20af436e02..e9f679e6de 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -957,4 +957,23 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase projects = ProjectUnscopingDavidDefaultScope.includes(:developers).where(id: project.id) assert_equal 1, projects.first.developers.size end + + def test_preloaded_associations_size + assert_equal Project.first.salaried_developers.size, + Project.preload(:salaried_developers).first.salaried_developers.size + + assert_equal Project.includes(:salaried_developers).references(:salaried_developers).first.salaried_developers.size, + Project.preload(:salaried_developers).first.salaried_developers.size + + # Nested HATBM + first_project = Developer.first.projects.first + preloaded_first_project = + Developer.preload(projects: :salaried_developers). + first. + projects. + detect { |p| p.id == first_project.id } + + assert preloaded_first_project.salaried_developers.loaded?, true + assert_equal first_project.salaried_developers.size, preloaded_first_project.salaried_developers.size + end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index cd19a7a5bc..eb94870a35 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -2181,6 +2181,26 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id) end + test "can unscope and where the default scope of the associated model" do + Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: 'other') }, class_name: "Bulb" + car = Car.create! + bulb1 = Bulb.create! name: "defaulty", car: car + bulb2 = Bulb.create! name: "other", car: car + + assert_equal [bulb1], car.bulbs + assert_equal [bulb2], car.other_bulbs + end + + test "can rewhere the default scope of the associated model" do + Car.has_many :old_bulbs, -> { rewhere(name: 'old') }, class_name: "Bulb" + car = Car.create! + bulb1 = Bulb.create! name: "defaulty", car: car + bulb2 = Bulb.create! name: "old", car: car + + assert_equal [bulb1], car.bulbs + assert_equal [bulb2], car.old_bulbs + end + test 'unscopes the default scope of associated model when used with include' do car = Car.create! bulb = Bulb.create! name: "other", car: car diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index ece4dab539..57d1c8feda 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -83,10 +83,10 @@ class AutomaticInverseFindingTests < ActiveRecord::TestCase assert_equal rating.comment, comment, "The Rating's comment should be the original Comment" - rating.comment.body = "Brogramming is the act of programming, like a bro." + rating.comment.body = "Fennec foxes are the smallest of the foxes." assert_equal rating.comment.body, comment.body, "Changing the Comment's body on the association should change the original Comment's body" - comment.body = "Broseiden is the king of the sea of bros." + comment.body = "Kittens are adorable." assert_equal comment.body, rating.comment.body, "Changing the original Comment's body should change the Comment's body on the association" end @@ -97,10 +97,10 @@ class AutomaticInverseFindingTests < ActiveRecord::TestCase assert_equal rating.comment, comment, "The Rating's comment should be the original Comment" - rating.comment.body = "Brogramming is the act of programming, like a bro." + rating.comment.body = "Fennec foxes are the smallest of the foxes." assert_equal rating.comment.body, comment.body, "Changing the Comment's body on the association should change the original Comment's body" - comment.body = "Broseiden is the king of the sea of bros." + comment.body = "Kittens are adorable." assert_equal comment.body, rating.comment.body, "Changing the original Comment's body should change the Comment's body on the association" end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 37ec3f1106..0df8f1f798 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -24,6 +24,8 @@ require 'models/molecule' require 'models/member' require 'models/member_detail' require 'models/organization' +require 'models/guitar' +require 'models/tuning_peg' class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase def test_autosave_validation @@ -397,6 +399,40 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttrib assert_not molecule.persisted?, 'Molecule should not be persisted when its electrons are invalid' end + def test_errors_should_be_indexed_when_passed_as_array + guitar = Guitar.new + tuning_peg_valid = TuningPeg.new + tuning_peg_valid.pitch = 440.0 + tuning_peg_invalid = TuningPeg.new + + guitar.tuning_pegs = [tuning_peg_valid, tuning_peg_invalid] + + assert_not tuning_peg_invalid.valid? + assert tuning_peg_valid.valid? + assert_not guitar.valid? + assert_equal ["is not a number"], guitar.errors["tuning_pegs[1].pitch"] + assert_not_equal ["is not a number"], guitar.errors["tuning_pegs.pitch"] + end + + def test_errors_should_be_indexed_when_global_flag_is_set + old_attribute_config = ActiveRecord::Base.index_nested_attribute_errors + ActiveRecord::Base.index_nested_attribute_errors = true + + molecule = Molecule.new + valid_electron = Electron.new(name: 'electron') + invalid_electron = Electron.new + + molecule.electrons = [valid_electron, invalid_electron] + + assert_not invalid_electron.valid? + assert valid_electron.valid? + assert_not molecule.valid? + assert_equal ["can't be blank"], molecule.errors["electrons[1].name"] + assert_not_equal ["can't be blank"], molecule.errors["electrons.name"] + ensure + ActiveRecord::Base.index_nested_attribute_errors = old_attribute_config + end + def test_valid_adding_with_nested_attributes molecule = Molecule.new valid_electron = Electron.new(name: 'electron') diff --git a/activerecord/test/cases/cache_key_test.rb b/activerecord/test/cases/cache_key_test.rb new file mode 100644 index 0000000000..bb2829b3c1 --- /dev/null +++ b/activerecord/test/cases/cache_key_test.rb @@ -0,0 +1,25 @@ +require "cases/helper" + +module ActiveRecord + class CacheKeyTest < ActiveRecord::TestCase + self.use_transactional_tests = false + + class CacheMe < ActiveRecord::Base; end + + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table(:cache_mes) { |t| t.timestamps } + end + + teardown do + @connection.drop_table :cache_mes, if_exists: true + end + + test "test_cache_key_format_is_not_too_precise" do + record = CacheMe.create + key = record.cache_key + + assert_equal key, record.reload.cache_key + end + end +end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index d904b802fa..4a0e6f497f 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -31,11 +31,20 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 318, Account.sum(:credit_limit) end + def test_should_sum_arel_attribute + assert_equal 318, Account.sum(Account.arel_table[:credit_limit]) + end + def test_should_average_field value = Account.average(:credit_limit) assert_equal 53.0, value end + def test_should_average_arel_attribute + value = Account.average(Account.arel_table[:credit_limit]) + assert_equal 53.0, value + end + def test_should_resolve_aliased_attributes assert_equal 318, Account.sum(:available_credit) end @@ -60,14 +69,26 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 60, Account.maximum(:credit_limit) end + def test_should_get_maximum_of_arel_attribute + assert_equal 60, Account.maximum(Account.arel_table[:credit_limit]) + end + def test_should_get_maximum_of_field_with_include assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(:credit_limit) end + def test_should_get_maximum_of_arel_attribute_with_include + assert_equal 55, Account.where("companies.name != 'Summit'").references(:companies).includes(:firm).maximum(Account.arel_table[:credit_limit]) + end + def test_should_get_minimum_of_field assert_equal 50, Account.minimum(:credit_limit) end + def test_should_get_minimum_of_arel_attribute + assert_equal 50, Account.minimum(Account.arel_table[:credit_limit]) + end + def test_should_group_by_field c = Account.group(:firm_id).sum(:credit_limit) [1,6,2].each do |firm_id| @@ -102,6 +123,25 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 60, c[2] end + def test_should_generate_valid_sql_with_joins_and_group + assert_nothing_raised ActiveRecord::StatementInvalid do + AuditLog.joins(:developer).group(:id).count + end + end + + def test_should_calculate_against_given_relation + developer = Developer.create!(name: "developer") + developer.audit_logs.create!(message: "first log") + developer.audit_logs.create!(message: "second log") + + c = developer.audit_logs.joins(:developer).group(:id).count + + assert_equal developer.audit_logs.count, c.size + developer.audit_logs.each do |log| + assert_equal 1, c[log.id] + end + end + def test_should_order_by_grouped_field c = Account.group(:firm_id).order("firm_id").sum(:credit_limit) assert_equal [1, 2, 6, 9], c.keys.compact @@ -131,6 +171,14 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 3, accounts.select(:firm_id).count end + def test_limit_should_apply_before_count_arel_attribute + accounts = Account.limit(3).where('firm_id IS NOT NULL') + + firm_id_attribute = Account.arel_table[:firm_id] + assert_equal 3, accounts.count(firm_id_attribute) + assert_equal 3, accounts.select(firm_id_attribute).count + end + def test_count_should_shortcut_with_limit_zero accounts = Account.limit(0) @@ -353,10 +401,23 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 6, Account.select("DISTINCT accounts.id").includes(:firm).count end + def test_count_selected_arel_attribute + assert_equal 5, Account.select(Account.arel_table[:firm_id]).count + assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count + end + def test_count_with_column_parameter assert_equal 5, Account.count(:firm_id) end + def test_count_with_arel_attribute + assert_equal 5, Account.count(Account.arel_table[:firm_id]) + end + + def test_count_with_arel_star + assert_equal 6, Account.count(Arel.star) + end + def test_count_with_distinct assert_equal 4, Account.select(:credit_limit).distinct.count @@ -378,12 +439,27 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 4, Account.joins(:firm).distinct.count('companies.id') end + def test_count_arel_attribute_in_joined_table_with + assert_equal 5, Account.joins(:firm).count(Company.arel_table[:id]) + assert_equal 4, Account.joins(:firm).distinct.count(Company.arel_table[:id]) + end + + def test_count_selected_arel_attribute_in_joined_table + assert_equal 5, Account.joins(:firm).select(Company.arel_table[:id]).count + assert_equal 4, Account.joins(:firm).distinct.select(Company.arel_table[:id]).count + end + def test_should_count_field_in_joined_table_with_group_by c = Account.group('accounts.firm_id').joins(:firm).count('companies.id') [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) } end + def test_should_count_field_of_root_table_with_conflicting_group_by_column + assert_equal({ 1 => 1 }, Firm.joins(:accounts).group(:firm_id).count) + assert_equal({ 1 => 1 }, Firm.joins(:accounts).group('accounts.firm_id').count) + end + def test_count_with_no_parameters_isnt_deprecated assert_not_deprecated { Account.count } end diff --git a/activerecord/test/cases/collection_cache_key_test.rb b/activerecord/test/cases/collection_cache_key_test.rb index 724234d7f4..53058c5a4a 100644 --- a/activerecord/test/cases/collection_cache_key_test.rb +++ b/activerecord/test/cases/collection_cache_key_test.rb @@ -53,7 +53,7 @@ module ActiveRecord test "cache_key with custom timestamp column" do topics = Topic.where("title like ?", "%Topic%") - last_topic_timestamp = topics(:fifth).written_on.utc.to_s(:nsec) + last_topic_timestamp = topics(:fifth).written_on.utc.to_s(:usec) assert_match(last_topic_timestamp, topics.cache_key(:written_on)) end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 307b68764e..6686ce012d 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -265,6 +265,12 @@ class FinderTest < ActiveRecord::TestCase assert_equal [Account], accounts.collect(&:class).uniq end + def test_find_by_association_subquery + author = authors(:david) + assert_equal author.post, Post.find_by(author: Author.where(id: author)) + assert_equal author.post, Post.find_by(author_id: Author.where(id: author)) + end + def test_take assert_equal topics(:first), Topic.take end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 89bd3f888e..d82a3040fc 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -47,7 +47,7 @@ def in_memory_db? end def subsecond_precision_supported? - !current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.send(:version) >= '5.6.4' + !current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.version >= '5.6.4' end def mysql_enforcing_gtid_consistency? diff --git a/activerecord/test/cases/integration_test.rb b/activerecord/test/cases/integration_test.rb index 9169207b0a..08a186ae07 100644 --- a/activerecord/test/cases/integration_test.rb +++ b/activerecord/test/cases/integration_test.rb @@ -81,7 +81,7 @@ class IntegrationTest < ActiveRecord::TestCase def test_cache_key_format_for_existing_record_with_updated_at dev = Developer.first - assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key + assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:usec)}", dev.cache_key end def test_cache_key_format_for_existing_record_with_updated_at_and_custom_cache_timestamp_format @@ -111,19 +111,19 @@ class IntegrationTest < ActiveRecord::TestCase def test_cache_key_for_updated_on dev = Developer.first dev.updated_at = nil - assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key + assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:usec)}", dev.cache_key end def test_cache_key_for_newer_updated_at dev = Developer.first dev.updated_at += 3600 - assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:nsec)}", dev.cache_key + assert_equal "developers/#{dev.id}-#{dev.updated_at.utc.to_s(:usec)}", dev.cache_key end def test_cache_key_for_newer_updated_on dev = Developer.first dev.updated_on += 3600 - assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:nsec)}", dev.cache_key + assert_equal "developers/#{dev.id}-#{dev.updated_on.utc.to_s(:usec)}", dev.cache_key end def test_cache_key_format_is_precise_enough @@ -134,8 +134,16 @@ class IntegrationTest < ActiveRecord::TestCase assert_not_equal key, dev.cache_key end + def test_cache_key_format_is_not_too_precise + skip("Subsecond precision is not supported") unless subsecond_precision_supported? + dev = Developer.first + dev.touch + key = dev.cache_key + assert_equal key, dev.reload.cache_key + end + def test_named_timestamps_for_cache_key owner = owners(:blackbeard) - assert_equal "owners/#{owner.id}-#{owner.happy_at.utc.to_s(:nsec)}", owner.cache_key(:updated_at, :happy_at) + assert_equal "owners/#{owner.id}-#{owner.happy_at.utc.to_s(:usec)}", owner.cache_key(:updated_at, :happy_at) end end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index b0fb905760..675149556f 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -57,9 +57,6 @@ module ActiveRecord def test_empty_where_values_hash relation = Relation.new(FakeKlass, :b, nil) assert_equal({}, relation.where_values_hash) - - relation.where! :hello - assert_equal({}, relation.where_values_hash) end def test_has_values @@ -153,10 +150,10 @@ module ActiveRecord end test 'merging a hash into a relation' do - relation = Relation.new(FakeKlass, :b, nil) - relation = relation.merge where: :lol, readonly: true + relation = Relation.new(Post, Post.arel_table, Post.predicate_builder) + relation = relation.merge where: {name: :lol}, readonly: true - assert_equal Relation::WhereClause.new([:lol], []), relation.where_clause + assert_equal({"name"=>:lol}, relation.where_clause.to_h) assert_equal true, relation.readonly_value end @@ -185,7 +182,7 @@ module ActiveRecord end test '#values returns a dup of the values' do - relation = Relation.new(FakeKlass, :b, nil).where! :foo + relation = Relation.new(Post, Post.arel_table, Post.predicate_builder).where!(name: :foo) values = relation.values values[:where] = nil diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index feb1c29656..2a2c2bc8d0 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -215,7 +215,7 @@ class SchemaDumperTest < ActiveRecord::TestCase def test_schema_dump_includes_length_for_mysql_blob_and_text_fields output = standard_dump - assert_match %r{t\.binary\s+"tiny_blob",\s+limit: 255$}, output + assert_match %r{t\.blob\s+"tiny_blob",\s+limit: 255$}, output assert_match %r{t\.binary\s+"normal_blob",\s+limit: 65535$}, output assert_match %r{t\.binary\s+"medium_blob",\s+limit: 16777215$}, output assert_match %r{t\.binary\s+"long_blob",\s+limit: 4294967295$}, output diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index c3fd0b2383..c31f94b2f2 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -60,7 +60,7 @@ module ActiveRecord $stderr.expects(:puts). with("Couldn't create database for #{@configuration.inspect}") - ActiveRecord::Tasks::DatabaseTasks.create @configuration + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } end def test_create_when_database_exists_outputs_info_to_stderr diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb index 750d5e42dc..0aea0c3b38 100644 --- a/activerecord/test/cases/tasks/sqlite_rake_test.rb +++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb @@ -53,7 +53,7 @@ module ActiveRecord $stderr.expects(:puts). with("Couldn't create database for #{@configuration.inspect}") - ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root' } end end diff --git a/activerecord/test/fixtures/content.yml b/activerecord/test/fixtures/content.yml new file mode 100644 index 0000000000..0d12ee03dc --- /dev/null +++ b/activerecord/test/fixtures/content.yml @@ -0,0 +1,3 @@ +content: + id: 1 + title: How to use Rails diff --git a/activerecord/test/fixtures/content_positions.yml b/activerecord/test/fixtures/content_positions.yml new file mode 100644 index 0000000000..9e85773f8e --- /dev/null +++ b/activerecord/test/fixtures/content_positions.yml @@ -0,0 +1,3 @@ +content_positions: + id: 1 + content_id: 1 diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index a96b8ef0f2..1dcd9fc21e 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -10,7 +10,6 @@ class Company < AbstractCompany has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account" has_many :contracts has_many :developers, :through => :contracts - has_many :accounts scope :of_first_firm, lambda { joins(:account => :firm). diff --git a/activerecord/test/models/content.rb b/activerecord/test/models/content.rb new file mode 100644 index 0000000000..140e1dfc78 --- /dev/null +++ b/activerecord/test/models/content.rb @@ -0,0 +1,40 @@ +class Content < ActiveRecord::Base + self.table_name = 'content' + has_one :content_position, dependent: :destroy + + def self.destroyed_ids + @destroyed_ids ||= [] + end + + before_destroy do |object| + Content.destroyed_ids << object.id + end +end + +class ContentWhichRequiresTwoDestroyCalls < ActiveRecord::Base + self.table_name = 'content' + has_one :content_position, foreign_key: 'content_id', dependent: :destroy + + after_initialize do + @destroy_count = 0 + end + + before_destroy do + @destroy_count += 1 + if @destroy_count == 1 + throw :abort + end + end +end + +class ContentPosition < ActiveRecord::Base + belongs_to :content, dependent: :destroy + + def self.destroyed_ids + @destroyed_ids ||= [] + end + + before_destroy do |object| + ContentPosition.destroyed_ids << object.id + end +end diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 7c5941b1af..9a907273f8 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -15,6 +15,8 @@ class Developer < ActiveRecord::Base end end + belongs_to :mentor + accepts_nested_attributes_for :projects has_and_belongs_to_many :shared_computers, class_name: "Computer" diff --git a/activerecord/test/models/guitar.rb b/activerecord/test/models/guitar.rb new file mode 100644 index 0000000000..cd068ff53d --- /dev/null +++ b/activerecord/test/models/guitar.rb @@ -0,0 +1,4 @@ +class Guitar < ActiveRecord::Base + has_many :tuning_pegs, index_errors: true + accepts_nested_attributes_for :tuning_pegs +end diff --git a/activerecord/test/models/mentor.rb b/activerecord/test/models/mentor.rb new file mode 100644 index 0000000000..11f1e4bff8 --- /dev/null +++ b/activerecord/test/models/mentor.rb @@ -0,0 +1,3 @@ +class Mentor < ActiveRecord::Base + has_many :developers +end
\ No newline at end of file diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb index 5328330653..b034e0e267 100644 --- a/activerecord/test/models/project.rb +++ b/activerecord/test/models/project.rb @@ -1,4 +1,5 @@ class Project < ActiveRecord::Base + belongs_to :mentor has_and_belongs_to_many :developers, -> { distinct.order 'developers.name desc, developers.id desc' } has_and_belongs_to_many :readonly_developers, -> { readonly }, :class_name => "Developer" has_and_belongs_to_many :non_unique_developers, -> { order 'developers.name desc, developers.id desc' }, :class_name => 'Developer' diff --git a/activerecord/test/models/tuning_peg.rb b/activerecord/test/models/tuning_peg.rb new file mode 100644 index 0000000000..1252d6dc1d --- /dev/null +++ b/activerecord/test/models/tuning_peg.rb @@ -0,0 +1,4 @@ +class TuningPeg < ActiveRecord::Base + belongs_to :guitar + validates_numericality_of :pitch +end diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb index 52d3290c84..92e0b197a7 100644 --- a/activerecord/test/schema/mysql2_specific_schema.rb +++ b/activerecord/test/schema/mysql2_specific_schema.rb @@ -2,7 +2,7 @@ ActiveRecord::Schema.define do create_table :binary_fields, force: true do |t| t.binary :var_binary, limit: 255 t.binary :var_binary_large, limit: 4095 - t.column :tiny_blob, 'tinyblob', limit: 255 + t.blob :tiny_blob, limit: 255 t.binary :normal_blob, limit: 65535 t.binary :medium_blob, limit: 16777215 t.binary :long_blob, limit: 2147483647 @@ -40,6 +40,17 @@ BEGIN END SQL + ActiveRecord::Base.connection.execute <<-SQL +DROP PROCEDURE IF EXISTS topics; +SQL + + ActiveRecord::Base.connection.execute <<-SQL +CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER +BEGIN + select * from topics limit num; +END +SQL + ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true ActiveRecord::Base.connection.execute <<-SQL diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb index 90f5a60d7b..553cb56103 100644 --- a/activerecord/test/schema/mysql_specific_schema.rb +++ b/activerecord/test/schema/mysql_specific_schema.rb @@ -2,7 +2,7 @@ ActiveRecord::Schema.define do create_table :binary_fields, force: true do |t| t.binary :var_binary, limit: 255 t.binary :var_binary_large, limit: 4095 - t.column :tiny_blob, 'tinyblob', limit: 255 + t.blob :tiny_blob, limit: 255 t.binary :normal_blob, limit: 65535 t.binary :medium_blob, limit: 16777215 t.binary :long_blob, limit: 2147483647 @@ -45,9 +45,9 @@ DROP PROCEDURE IF EXISTS topics; SQL ActiveRecord::Base.connection.execute <<-SQL -CREATE PROCEDURE topics() SQL SECURITY INVOKER +CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER BEGIN - select * from topics limit 1; + select * from topics limit num; END SQL diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index d334a2740e..66a1f5aa8a 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -207,6 +207,14 @@ ActiveRecord::Schema.define do add_index :companies, [:firm_id, :type], name: "company_partial_index", where: "rating > 10" add_index :companies, :name, name: 'company_name_index', using: :btree + create_table :content, force: true do |t| + t.string :title + end + + create_table :content_positions, force: true do |t| + t.integer :content_id + end + create_table :vegetables, force: true do |t| t.string :name t.integer :seller_id @@ -253,6 +261,7 @@ ActiveRecord::Schema.define do t.string :first_name t.integer :salary, default: 70000 t.integer :firm_id + t.integer :mentor_id if subsecond_precision_supported? t.datetime :created_at, precision: 6 t.datetime :updated_at, precision: 6 @@ -347,6 +356,10 @@ ActiveRecord::Schema.define do t.column :key, :string end + create_table :guitar, force: true do |t| + t.string :color + end + create_table :inept_wizards, force: true do |t| t.column :name, :string, null: false t.column :city, :string, null: false @@ -452,6 +465,10 @@ ActiveRecord::Schema.define do t.string :name end + create_table :mentors, force: true do |t| + t.string :name + end + create_table :minivans, force: true, id: false do |t| t.string :minivan_id t.string :name @@ -660,6 +677,7 @@ ActiveRecord::Schema.define do t.string :name t.string :type t.integer :firm_id + t.integer :mentor_id end create_table :randomly_named_table1, force: true do |t| @@ -845,6 +863,11 @@ ActiveRecord::Schema.define do t.belongs_to :ship end + create_table :tuning_pegs, force: true do |t| + t.integer :guitar_id + t.float :pitch + end + create_table :tyres, force: true do |t| t.integer :car_id end |