Commit Graph

331 Commits

Author SHA1 Message Date
Sean Griffin
4ecabed2f6 Revert "Perform a more efficient query in Relation#any?"
This reverts commit 6d5b1fdf55611de2a1071c37544933bb588ae88e.

`eager_load` and `references` can include hashes, which won't match up
with `references`

A test case has been added to demonstrate the problem
2015-12-14 10:05:53 -07:00
Sean Griffin
6a6dbb4c51 Merge pull request #13008 from ktheory/sanitize_order
Support SQL sanitization in AR::QueryMethods#order
2015-10-29 15:29:06 -06:00
Ted Johansson
b901a49473 Add deprecation warning to ActiveRecord::Relation#update
When passing an instance of `ActiveRecord::Base` to `#update`, it would
internally call `#find`, resulting in a misleading deprecation warning.

This change gives this deprecated use of `#update` its own, meaningful
warning.
2015-10-15 17:00:28 +08:00
Sean Griffin
926002a7f3 Skip the test added in 9cc324a on buggy versions of SQlite
See 7dcfc25e7c52682a4343c2ba7188a69e7c06c936 for more details
2015-09-21 11:37:36 -06:00
Sean Griffin
9cc324a3f1 Ensure aliased attributes passed to select are quoted if using from
Fixes #21488

[Sean Griffin & johanlunds]
2015-09-21 11:14:32 -06:00
Wojciech Wnętrzak
c82c5f8ffd Deprecate passing conditions to AR::Relation destroy_all and delete_all methods 2015-09-06 16:14:16 +02:00
Rafael Mendonça França
1b4399dfe7 Fix regression caused by a01d164b
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.
2015-07-07 13:40:50 -03:00
Rafael Mendonça França
7cc9754209 Merge pull request #20196 from huoxito/preload-association-and-merges
Properly append preload / includes args on Merger
2015-05-28 01:52:14 -03:00
Washington Luiz
a01d164b94 Properly append preload / includes args on Merger
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
```
2015-05-28 01:49:34 -03:00
Yves Senn
adfab2dcf4 deprecate Relation#uniq use Relation#distinct instead.
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.
2015-05-26 10:35:14 +02:00
Kohei Suzuki
28375dd621 Raise ArgumentError when find_by receives no arguments
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>
```
2015-04-11 07:48:01 +09:00
Rafael Mendonça França
c479480638 Merge pull request #18744 from mfazekas/no-table-name-with-from
Fix appending table_name to select and group when used with subquery (fr...
2015-02-24 16:56:01 -03:00
Eugene Gilburg
d7a7a050e1 Optimize none? and one? relation query methods to use LIMIT and COUNT.
Use SQL COUNT and LIMIT 1 queries for none? and one? methods if no block or limit is given,
instead of loading the entire collection to memory. The any? and many? methods already
follow this behavior.

[Eugene Gilburg & Rafael Mendonça França]
2015-02-12 17:40:59 -02:00
Bogdan Gusiev
e94330fe40 Fixed AR::Relation#group method when argument is a SQL reserved keyword 2015-01-29 17:27:02 +02:00
Sean Griffin
b06f64c348 Remove Relation#bind_params
`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.
2015-01-27 16:10:03 -07:00
Sean Griffin
6c235dd958 Use an Attribute object to represent a bind value
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.
2015-01-27 12:07:06 -07:00
Sean Griffin
765a3123c8 Remove unused bind and bind! methods from Relation 2015-01-26 16:12:59 -07:00
Sean Griffin
a384c002af Generate a query that makes sense when testing having clauses
PG expects us to not give it nonsenes

[Sean Griffin & anthonynavarre]
2015-01-26 15:01:28 -07:00
Sean Griffin
39f2c3b3ea Change having_values to use the WhereClause class
This fixed an issue where `having` can only be called after the last
call to `where`, because it messes with the same `bind_values` array.
With this change, the two can be called as many times as needed, in any
order, and the final query will be correct. However, once something
assigns `bind_values`, that stops. This is because we have to move all
of the bind values from the having clause over to the where clause since
we can't differentiate the two, and assignment was likely in the form
of:

`relation.bind_values += other.bind_values`

This will go away once we remove all places that are assigning
`bind_values`, which is next on the list.

While this fixes a bug that was present in at least 4.2 (more likely
present going back as far as 3.0, becoming more likely in 4.1 and later
as we switched to prepared statements in more cases), I don't think this
can be easily backported. The internal changes to `Relation` are
non-trivial, anything that involves modifying the `bind_values` array
would need to change, and I'm not confident that we have sufficient test
coverage of all of those locations (when `having` was called with a hash
that could generate bind values).

[Sean Griffin & anthonynavarre]
2015-01-26 14:44:05 -07:00
Sean Griffin
b9d668f8cb Don't remove join dependencies in Relation#exists?
Fixes #18632
2015-01-23 12:05:14 -07:00
Yves Senn
3ae9818143 remove deprecation warning when modifying a Relation with cached arel.
This adresses 1b7aa62b18 (commitcomment-9147803)
2015-01-05 10:08:56 +01:00
Rafael Mendonça França
0fbd1fc888 Remove deprecated ActiveRecord::Base.disable_implicit_join_references= 2015-01-04 11:58:44 -03:00
Rafael Mendonça França
78dab2a856 Remove support to activerecord-deprecated_finders 2015-01-02 12:06:24 -03:00
Rafael Mendonça França
9598c9655f Merge pull request #11898 from prathamesh-sonpatki/patch-update
Changed ActiveRecord::Relation#update behavior so that it will work on Relation objects without giving id

Conflicts:
	activerecord/CHANGELOG.md
2015-01-02 10:48:48 -03:00
Sean Griffin
a60770d3bf Remove klass and arel_table as a dependency of PredicateBuilder
This class cares far too much about the internals of other parts of
Active Record. This is an attempt to break out a meaningful object which
represents the needs of the predicate builder. I'm not fully satisfied
with the name, but the general concept is an object which represents a
table, the associations to/from that table, and the types associated
with it. Many of these exist at the `ActiveRecord::Base` class level,
not as properties of the table itself, hence the need for another
object. Currently it provides these by holding a reference to the class,
but that will likely change in the future. This allows the predicate
builder to remain wholy concerned with building predicates.

/cc @mrgilman
2014-12-26 15:19:42 -07:00
Sean Griffin
1d6bb77636 Inject the PredicateBuilder into the Relation instance
Construction of relations can be a hotspot, we don't want to create one
of these in the constructor. This also allows us to do more expensive
things in the predicate builder's constructor, since it's created once
per AR::Base subclass
2014-12-26 13:53:56 -07:00
Prathamesh Sonpatki
5ef713c53c Allow ActiveRecord::Relation#update to run on result of a relation with callbacks and validations
- Right now, there is no method to update multiple records with
  validations and callbacks.
- Changed the behavior of existing `update` method so that when `id`
  attribute is not given and the method is called on an `Relation`
  object, it will execute update for every record of the `Relation` and
  will run validations and callbacks for every record.
- Added test case for validating that the callbacks run when `update` is
  called on a `Relation`.
- Changed test_create_columns_not_equal_attributes test from
  persistence_test to include author_name column on topics table as it
  it used in before_update callback.
- This change introduces performance issues when a large number of
  records are to be updated because it runs UPDATE query for every
  record of the result. The `update_all` method can be used in that case
  if callbacks are not required because it will only run single UPDATE
  for all the records.
2014-12-20 15:33:18 +05:30
Melanie Gilman
c0609dd0f0 Deprecate Class handler in PredicateBuilder
Users should pass strings to queries instead of classes
2014-12-04 15:06:21 -05:00
Erik Michaels-Ober
d1374f99bf Pass symbol as an argument instead of a block 2014-11-29 11:53:24 +01:00
Sean Griffin
c01b20b658 rm reorder_bind_params
Arel handles this for us automatically. Updated tests, as BindParam is
no longer a subclass of SqlLiteral. We should remove the second argument
to substitute_at entirely, as it's no longer used
2014-11-17 14:57:01 -08:00
Arun Agrawal
9ae210ba09 Build fix when running in isolation
`Computer` class needs to be require

See #17217 for more details
2014-11-14 10:24:11 +01:00
Yves Senn
e581b01116 switch assert_operator arguments as discussed in #16860.
Working with two different machines is hard 😓
2014-09-11 08:07:35 +02:00
Yves Senn
16868b53f9 A NullRelation should represent nothing. Closes #15176.
[Matthew Draper & Yves Senn]

Closes #16860. (pull request to discuss the implementation)
2014-09-11 08:04:48 +02:00
Akira Matsuda
f7d09faac9 Ignore SCHEMA queries when asserting no queries 2014-08-28 14:38:42 +09:00
Godfrey Chan
58c5261efa Fixed find_by("sql fragment without bindings") on master
* Also duplicated find_by tests from relations_test.rb to finder_test.rb now
	that we have a completely different implementation on the class (in core.rb
	with AST caching stuff).

* Also removed a (failing) test that used mocks. Now that we have tests for the
  behavior, there's no point having another test that tests the implementation
	(that it delegates). Further, what the test was implying is nolonger true with
	the current implementation, because Class.find_by is a real method now.
2014-08-25 17:48:13 -07:00
Rafael Mendonça França
5eae77c44b Move test to the proper file
All preload tests are in the eager_test file
2014-05-26 23:50:49 -03:00
Sean Griffin
a8afc6395b Add missing test case for quoting behavior
It appears that the only time that `quote` is called with a column,
but without first calling `type_cast` is when where is called with an
array. My previous pull request broke this behavior, without failing
tests. This adds a test for the only case I can think of that exercises
the `if column.type == :integer` branch of `quote` effectively.
2014-05-26 08:08:32 -07:00
Matthew Draper
110d3d0c0b Merge pull request #14803 from kuldeepaggarwal/null_relation_sum_fix
Fixed a problem where `sum` used with a `group` was not returning a Hash.
2014-05-22 14:59:23 +09:30
Aaron Patterson
b713e207d4 fix multiple hash preloads. Fixes #14994 2014-05-20 10:16:57 -07:00
Leandro Facchinetti
5866437eef Fix Relation#delete_all inconsistency
When relation scopes include one of `uniq`, `group`, `having` or
`offset`, the generated query ignores them and that causes unintended
records to be deleted. This solves the issue by restricting the deletion
when those scopes are present.

rails/rails#11985
2014-05-16 00:39:02 -03:00
Kuldeep Aggarwal
6d36c1dd05 Fixed a problem where sum, size, average, minimum and maximum used
with a grouping was not returning a Hash.
2014-05-15 00:49:29 +05:30
Bogdan Gusiev
7e20bdc20d Put back Relation#join method as a delegate to Array
This is a regression 4.0 -> 4.1 fix.
In 4.1.0 Relation#join is delegated to Arel#SelectManager.
In 4.0 series it is delegated to Array#join

This patch puts back the behaviour of 4.0
2014-05-05 16:45:16 +03:00
Aaron Patterson
94cd2f7f2e Merge branch 'master' into adequaterecord
* master: (74 commits)
  [ci skip] builtin -> built-in
  Fix code indentation and improve formatting
  Grammar fix in Getting Started Guide
  Make URL escaping more consistent
  Optimize URI escaping
  Always escape string passed to url helper.
  Remove statement assuming coffee shop/public space wifi is inherently insecure
  Don't rely on Arel master in bug report template [ci skip]
  wrap methods in backticks [ci skip]
  "subhash" --> "sub-hash"
  multibyte_conformance.rb --> multibyte_conformance_test.rb
  Fix inconsistent behavior from String#first/#last
  `@destroyed` should always be set to `false` when an object is duped.
  remove warning `warning: ambiguous first argument; put parentheses or even spaces`
  :uglify -> :uglifier
  Regression test for irregular inflection on has_many
  Singularize association names before camelization
  Fix spelling and proper nouns
  Optimize select_value, select_values, select_rows and dry up checking whether to exec with cache for Postgresql adapter
  Include default rails protect_from_forgery with: :exception
  ...

Conflicts:
	activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
	activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
2014-04-20 12:38:33 -07:00
Eric Chahin
93f852569e Changed the NullRelation so that when count is called with #group it will properly return an empty hash instead of zero. Fixes issue #14721
Conflicts:
	activerecord/CHANGELOG.md
2014-04-16 09:54:28 -04:00
Lauro Caetano
34945e41c2 The Association Relation should use empty? and size from Relation.
968c581ea34b5236af14805e6a77913b1cb36238 have introduced this bug #14744
on Association Relation when the method `empty?` or `size` was called.

Example:
  # Given an author that does have 3 posts, but none of them with the
  # title 'Some Title'
  Author.last.posts.where(title: 'Some Title').size
  # => 3

It was occurring, because the Association Relation had implemented these
methods based on `@association`, this way giving wrong results.

To fix it, was necessary to remove the methods `empty?` and `size` from
Association Relation. It just have to use these methods from Relation.

Example:
  # Given an author that does have 3 posts, but none of them with the
  # title 'Some Title'
  Author.last.posts.where(title: 'Some Title').size
  # => 0
  # Now it will return the correct value.

Fixes #14744.
2014-04-14 22:00:21 -03:00
Aaron Patterson
316ee25c25 Merge branch 'master' into adequaterecord
* master: (70 commits)
  [ci skip] Added link to ruby-lang.org installation.
  Use the index on hidden field
  `collection_check_boxes` respects `:index` option for the hidden filed name.
  docs, double meaning of `serialize` argument. Closes #14284.
  Just call read_attribute, no need to use `send`.
  - Fix lingering reference to `:text` instead of the newer `:plain` - Section references `form_tag` instead of the `form_for` used in the example
  again, read_attribute is public, so just call it
  read_attribute is public, so we should just call it
  Disable assest cache store in docs [ci skip]
  Make counter cache decrementation on destroy idempotent
  Write the failing test case for concurrent counter cache
  [ci skip] Use plain underscore instead of "\_".
  Update documentation to use Rails.application instead
  Add a changelog entry for #14546 [ci skip]
  Move tests for deep_dup and duplicable to object directory
  Missing 'are' in note - [ci skip]
  CollectionHelpers now accepts a readonly option
  Fix a few typos [ci skip]
  Bundle tzinfo-data on :x64_mingw (64-bit Ruby on Windows).
  don't bother with an offset if the offset is zero
  ...
2014-04-14 11:49:36 -07:00
Aaron Patterson
85f3a57a57 propogate bind values collected in arel to SQL generation 2014-04-11 16:14:51 -07:00
Rafael Mendonça França
8d11fbf679 Use assert_not 2014-04-11 15:46:49 -03:00
Rafael Mendonça França
8a08f5cb23 ✂️ 2014-04-11 15:46:04 -03:00
Simon Woker
afd4d8205e Fix error for aggregate methods with select, see issue #13648 2014-04-10 16:58:39 +00:00