aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation
Commit message (Collapse)AuthorAgeFilesLines
* Add ActiveRecord::Relation#in_batchesSina Siadat2015-08-072-9/+156
| | | | | | | | | | | | | | | | | `in_batches` yields Relation objects if a block is given, otherwise it returns an instance of `BatchEnumerator`. The existing `find_each` and `find_in_batches` methods work with batches of records. The new API allows working with relation batches as well. Examples: Person.in_batches.each_record(&:party_all_night!) Person.in_batches.update_all(awesome: true) Person.in_batches.delete_all Person.in_batches.map do |relation| relation.delete_all sleep 10 # Throttles the delete queries end
* Extra caller details added to ActiveRecord::RecordNotFoundSameer Rahmani2015-07-211-1/+2
| | | | | | | | | | | | | | | | ActiveRecord::RecordNotFound modified to store model name, primary_key and id of the caller model. It allows the catcher of this exception to make a better decision to what to do with it. For example consider this simple example: class SomeAbstractController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_404 private def redirect_to_404(e) return redirect_to(posts_url) if e.model == 'Post' raise end end
* Freeze string literals when not mutated.schneems2015-07-192-4/+4
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | I wrote a utility that helps find areas where you could optimize your program using a frozen string instead of a string literal, it's called [let_it_go](https://github.com/schneems/let_it_go). After going through the output and adding `.freeze` I was able to eliminate the creation of 1,114 string objects on EVERY request to [codetriage](codetriage.com). How does this impact execution? To look at memory: ```ruby require 'get_process_mem' mem = GetProcessMem.new GC.start GC.disable 1_114.times { " " } before = mem.mb after = mem.mb GC.enable puts "Diff: #{after - before} mb" ``` Creating 1,114 string objects results in `Diff: 0.03125 mb` of RAM allocated on every request. Or 1mb every 32 requests. To look at raw speed: ```ruby require 'benchmark/ips' number_of_objects_reduced = 1_114 Benchmark.ips do |x| x.report("freeze") { number_of_objects_reduced.times { " ".freeze } } x.report("no-freeze") { number_of_objects_reduced.times { " " } } end ``` We get the results ``` Calculating ------------------------------------- freeze 1.428k i/100ms no-freeze 609.000 i/100ms ------------------------------------------------- freeze 14.363k (± 8.5%) i/s - 71.400k no-freeze 6.084k (± 8.1%) i/s - 30.450k ``` Now we can do some maths: ```ruby ips = 6_226k # iterations / 1 second call_time_before = 1.0 / ips # seconds per iteration ips = 15_254 # iterations / 1 second call_time_after = 1.0 / ips # seconds per iteration diff = call_time_before - call_time_after number_of_objects_reduced * diff * 100 # => 0.4530373333993266 miliseconds saved per request ``` So we're shaving off 1 second of execution time for every 220 requests. Is this going to be an insane speed boost to any Rails app: nope. Should we merge it: yep. p.s. If you know of a method call that doesn't modify a string input such as [String#gsub](https://github.com/schneems/let_it_go/blob/b0e2da69f0cca87ab581022baa43291cdf48638c/lib/let_it_go/core_ext/string.rb#L37) please [give me a pull request to the appropriate file](https://github.com/schneems/let_it_go/blob/b0e2da69f0cca87ab581022baa43291cdf48638c/lib/let_it_go/core_ext/string.rb#L37), or open an issue in LetItGo so we can track and freeze more strings. Keep those strings Frozen ![](https://www.dropbox.com/s/z4dj9fdsv213r4v/let-it-go.gif?dl=1)
* Fix regression caused by a01d164bRafael Mendonça França2015-07-071-2/+2
| | | | | | | | | When preload is used in a default scope the preload_values were returning nested arrays and causing the preloader to fail because it doesn't know how to deal with nested arrays. So before calling preload! we need to splat the arguments. This is not needed to includes because it flatten its arguments.
* [skip ci] #distinct instead of #uniqJon Atack2015-07-031-2/+3
| | | | | | | | as #uniq will be removed from Rails 5.0 as per the Active Support exception raised: ActiveSupport::DeprecationException: DEPRECATION WARNING: uniq is deprecated and will be removed from Rails 5.0 (use distinct instead).
* Update .pluck documentation on uniqPrem Sichanugrist2015-06-261-1/+1
| | | | | | This is to show users that they can chain `.uniq` and `.pluck` to get the `DISTINCT column` result. They don't have to do `DISTINCT column` themselves.
* Include `Enumerable` in `ActiveRecord::Relation`Sean Griffin2015-06-193-17/+8
| | | | | | | | | | | After discussing, we've decided it makes more sense to include it. We're already forwarding every conflicting method to `to_a`, and there's no conflation of concerns. `Enumerable` has no mutating methods, and it just allows us to simplify the code. No existing methods will have a change in behavior. Un-overridden Enumerable methods will simply delegate to `each`. [Sean Griffin & bogdan]
* Use `Enumerable#sum` on `ActiveRecord::Relation` when a block is givenSean Griffin2015-06-191-2/+6
| | | | | | | | This matches our behavior in other cases where useful enumerable methods might have a different definition in `Relation`. Wanting to actually enumerate over the records in this case is completely reasonable, and wanting `.sum` is reasonable for the same reason it is on `Enumerable` in the first place.
* Merge pull request #20362 from kddeisz/enumerable_pluckRafael Mendonça França2015-06-011-0/+4
|\ | | | | Allow Enumerable#pluck to take a splat.
| * Allow Enumerable#pluck to take a splat.Kevin Deisz2015-05-291-0/+4
| | | | | | | | | | | | This allows easier integration with ActiveRecord, such that AR#pluck will now use Enumerable#pluck if the relation is loaded, without needing to hit the database.
* | Ensure symbols passed to `select` are always quotedSean Griffin2015-05-301-9/+7
|/ | | | | | | | | | | | | | | | | Our general contract in Active Record is that strings are assumed to be SQL literals, and symbols are assumed to reference a column. If a from clause is given, we shouldn't include the table name, but we should still quote the value as if it were a column. Upon fixing this, the tests were still failing on SQLite. This was because the column name being returned by the query was `"\"join\""` instead of `"join"`. This is actually a bug in SQLite that was fixed a long time ago, but I was using the version of SQLite included by OS X which has this bug. Since I'm guessing this will be a common case for contributors, I also added an explicit check with a more helpful error message. Fixes #20360
* Fix the shadowing warning for `reflection`Roque Pinel2015-05-281-2/+2
|
* Merge pull request #20196 from huoxito/preload-association-and-mergesRafael Mendonça França2015-05-281-1/+23
|\ | | | | Properly append preload / includes args on Merger
| * Properly append preload / includes args on MergerWashington Luiz2015-05-281-1/+23
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Couldn't find other way to get the association name from a given class other than looping through `reflect_on_all_associations` reflections .. Noticed this one while looking at this example: ```ruby class Product < ActiveRecord::Base has_many :variants has_many :translations end class Translation < ActiveRecord::Base belongs_to :product end class Variant < ActiveRecord::Base belongs_to :product end class BugTest < Minitest::Test def test_merge_stuff product = Product.create! name: 'huhu' variant = Variant.create! product_id: product.id Translation.create! locale: 'en', product_id: product.id product_relation = Product.all .preload(:translations) .joins(:translations) .merge(Translation.where(locale: 'en')) .where(name: 'huhu') assert_equal variant, Variant.joins(:product).merge(product_relation).first end end ```
* | Allow Relation#compact using delegationJordan Raine2015-05-281-1/+1
| |
* | deprecate `Relation#uniq` use `Relation#distinct` instead.Yves Senn2015-05-261-1/+3
|/ | | | | | | | | See #9683 for the reasons we switched to `distinct`. Here is the discussion that triggered the actual deprecation #20198. `uniq`, `uniq!` and `uniq_value` are still around. They will be removed in the next minor release after Rails 5.
* Remove redundant require 'set' linesMehmet Emin İNAÇ2015-05-151-1/+0
|
* [ci skip] Remove comments about Rails 3.1claudiob2015-05-111-3/+3
| | | | | | | | | Stems from https://github.com/rails/rails/pull/20105#issuecomment-100900939 where @senny said: > From my point of view, all the docs (guides, API) are version bound. > They should describe that version and continue to be available when newer versions are released. > The cross referencing can be done by the interested user.
* [ci skip] Stop explaining finders for Rails 3claudiob2015-05-101-14/+2
| | | | | Now that master points at Rails 5, we might not need to explain how things used to work in Rails 3. Or we might… up to you :grin:
* Merge pull request #19546 from DianthuDia/fix_unscope_for_less_thanYves Senn2015-04-281-1/+1
|\ | | | | | | Fix unscope for less than
| * Fix unscope for less thanTAKAHASHI Kazuaki2015-03-271-1/+1
| | | | | | | | | | | | Code such as the following will be corrected. Developer.where(id: -Float::INFINITY...2).unscope(where: :id)
* | Merge pull request #19718 from eagletmt/find_by-without-argYves Senn2015-04-281-4/+4
|\ \ | | | | | | | | | Raise ArgumentError when find_by receives no arguments
| * | Raise ArgumentError when find_by receives no argumentsKohei Suzuki2015-04-111-4/+4
| | | | | | | | | | | | | | | | | | | | | | | | | | | It fixes the strange error saying undefined method `take'. ``` RelationTest#test_find_by_without_arg_behaves_same_with_find_by({}): NoMethodError: undefined method `take' for #<ActiveRecord::QueryMethods::WhereChain:0x007f9c55db1d68> ```
* | | Revert "Merge pull request #19755 from yuki24/activerecord/support-for-set"Yves Senn2015-04-151-1/+0
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This reverts commit 524d40591eaa2f4d007409bfad386f6b107492eb, reversing changes made to 34d3a6095100245283861ef480a54d0643bbee4c. Reasoning behind the revert are in the PR discussion: https://github.com/rails/rails/pull/19755 - This means that types can no longer cast to/from `Set`, and reasonably work with `where` (we already have this problem for `array`/`json` types on pg) - This adds precedent for every other `Enumerable`, and we can't target `Enumerable` directly. - Calling `to_a` on a `Set` is reasonable.
* | | Add support for Set to Relation#whereYuki Nishijima2015-04-131-0/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | Previously `#where` used to treat `Set`objects as nil, but now it treats them as an array: set = Set.new([1, 2]) Author.where(:id => set) # => SELECT "authors".* FROM "authors" WHERE "authors"."id" IN (1, 2)
* | | Enhance documentation of pluck with a hint to ids [ci skip]wingfire2015-04-121-3/+5
|/ / | | | | | | | | Documentation is giving an example that can be replaced by a more dry command. Give a hint that ids can be used instead of pluck(:id).
* | [ci skip] Combine complementary AR #find doc linesAlexander Dimitriyadi2015-03-301-3/+1
| |
* | [skip ci] Improve `warn_on_records_fetched` documentationJon Atack2015-03-271-3/+2
|/ | | | | | | | - ‘dection’ -> ‘detection’ - ‘exceeds threshold’ -> ‘exceeds the threshold’ - Other minor improvements.
* Add `config.active_record.warn_on_records_fetched_greater_than` optionJason Nochlin2015-03-251-0/+50
| | | | | | | | | When set to an integer, a warning will be logged whenever a result set larger than the specified size is returned by a query. Fixes #16463 The warning is outputed a module which is prepended in an initializer, so there will be no performance impact if `config.active_record.warn_on_records_fetched_greater_than` is not set.
* Fix referencing wrong aliases while joining tables of has many throughpinglamb2015-03-221-1/+1
| | | | | | | | | | | association While joining table of has_many :through association, ActiveRecord will use the actual table name instead of through-join alias. It results with a wrong SQL and exception is raised. This only happens when calculation methods like #count is called. This issue is affecting Rails 4.1.x and 4.2.x as well.
* Drop `references_eager_loaded_tables?` test from `has_include?`Ben Woosley2015-03-171-1/+1
| | | | | | | It is redundant with tests in `eager_loading?`, but for the difference between `includes_values.present?` and `includes_values.any?`, which is a difference without a distinction because `false` has no meaning for `includes`.
* Spell PostgreSQL correctly :elephant:Akira Matsuda2015-02-281-1/+1
| | | | [ci skip]
* Removed non-standard and unused require 'active_support/deprecation' from ↵Vipul A M2015-02-271-1/+0
| | | | parts out of active_support.
* Fix c479480638508c20601af69ca46b5b606c2d5b4d to account for from_value -> ↵Jeremy Kemper2015-02-241-1/+1
| | | | from_clause in bdc5141652770fd227455681cde1f9899f55b0b9
* Merge pull request #18744 from mfazekas/no-table-name-with-fromRafael Mendonça França2015-02-241-5/+9
| | | | Fix appending table_name to select and group when used with subquery (fr...
* `Type#type_cast_from_database` -> `Type#deserialize`Sean Griffin2015-02-171-2/+2
|
* correct method name in deprecation messageyuuji.yaginuma2015-02-181-1/+1
|
* Deprecated passing of `start` value to `find_in_batches` and `find_each` in ↵Vipul A M2015-02-171-17/+31
| | | | favour of `begin_at` value.
* Add an option `end_at` to `find_in_batches`Vipul A M2015-02-091-12/+22
| | | | that complements the `start`parameter to specify where to stop batch processing
* Raise ArgumentError when passing nil to Relation#mergeRafael Mendonça França2015-02-061-1/+1
| | | | | | nil or false should not be valid argument to the merge method. Closes #12264
* Use keyword argument in the find_in_batches APIRafael Mendonça França2015-02-061-11/+7
| | | | | We already validate the keys, so it is better to use the built-in feature to do this
* Respect custom primary keys for associations in `Relation#where`Sean Griffin2015-02-041-1/+21
| | | | | | | | | | While we query the proper columns, we go through normal handling for converting the value to a primitive which assumes it should use the table's primary key. If the association specifies a different value (and we know that we're working with an association), we should use the custom primary key instead. Fixes #18813.
* Attribute assignment and type casting has nothing to do with columnsSean Griffin2015-01-311-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | It's finally finished!!!!!!! The reason the Attributes API was kept private in 4.2 was due to some publicly visible implementation details. It was previously implemented by overloading `columns` and `columns_hash`, to make them return column objects which were modified with the attribute information. This meant that those methods LIED! We didn't change the database schema. We changed the attribute information on the class. That is wrong! It should be the other way around, where schema loading just calls the attributes API for you. And now it does! Yes, this means that there is nothing that happens in automatic schema loading that you couldn't manually do yourself. (There's still some funky cases where we hit the connection adapter that I need to handle, before we can turn off automatic schema detection entirely.) There were a few weird test failures caused by this that had to be fixed. The main source came from the fact that the attribute methods are now defined in terms of `attribute_names`, which has a clause like `return [] unless table_exists?`. I don't *think* this is an issue, since the only place this caused failures were in a fake adapter which didn't override `table_exists?`. Additionally, there were a few cases where tests were failing because a migration was run, but the model was not reloaded. I'm not sure why these started failing from this change, I might need to clear an additional cache in `reload_schema_from_cache`. Again, since this is not normal usage, and it's expected that `reset_column_information` will be called after the table is modified, I don't think it's a problem. Still, test failures that were unrelated to the change are worrying, and I need to dig into them further. Finally, I spent a lot of time debugging issues with the mutex used in `define_attribute_methods`. I think we can just remove that method entirely, and define the attribute methods *manually* in the call to `define_attribute`, which would simplify the code *tremendously*. Ok. now to make this damn thing public, and work on moving it up to Active Model.
* Post.all.or(anything) == Post.allSean Griffin2015-01-291-2/+2
|
* Fixed AR::Relation#group method when argument is a SQL reserved keywordBogdan Gusiev2015-01-291-13/+15
|
* Don't error when grouped calculations return 0 recordsSean Griffin2015-01-281-1/+1
| | | | Fixes #18717
* Bring the implementation of Relation#or up to speedSean Griffin2015-01-282-36/+21
|
* Added #or to ActiveRecord::RelationMatthew Draper2015-01-281-0/+59
| | | | | | | Post.where('id = 1').or(Post.where('id = 2')) # => SELECT * FROM posts WHERE (id = 1) OR (id = 2) [Matthew Draper & Gael Muller]
* Remove Relation#bind_paramsSean Griffin2015-01-275-17/+27
| | | | | | | | `bound_attributes` is now used universally across the board, removing the need for the conversion layer. These changes are mostly mechanical, with the exception of the log subscriber. Additional, we had to implement `hash` on the attribute objects, so they could be used as a key for query caching.
* Use an `Attribute` object to represent a bind valueSean Griffin2015-01-274-8/+18
| | | | | | | | | | | The column is primarily used for type casting, which we're trying to separate from the idea of a column. Since what we really need is the combination of a name, type, and value, let's use the object that we already have to represent that concept, rather than this tuple. No consumers of the bind values have been changed, only the producers (outside of tests which care too much about internals). This is *finally* possible since the bind values are now produced from a reasonable number of lcoations.