Commit Graph

1273 Commits

Author SHA1 Message Date
Yves Senn
e50fe85180 descriptive error message when fixtures contian a missing column.
Closes #21201.
2015-08-13 17:13:32 +02:00
Yves Senn
cd3983a95a Merge pull request #17885 from starbelly/patch-1
Add method to run command-line db apps

Conflicts:
	activerecord/CHANGELOG.md
2015-08-11 15:57:40 +02:00
Zachary Scott
f7ebdb1ac5 Remove XML Serialization from core.
This includes the following classes:

- ActiveModel::Serializers::Xml
- ActiveRecord::Serialization::XmlSerializer
2015-08-07 11:01:48 -04:00
Sina Siadat
25cee1f037 Add ActiveRecord::Relation#in_batches
`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
2015-08-07 10:26:38 +04:30
Sean Griffin
0cfa496697 Merge pull request #20459 2015-08-06 16:24:09 -06:00
Sean Griffin
cc10911199 Merge pull request #20884
Add #cache_key to ActiveRecord::Relation.
2015-08-01 18:04:07 -06:00
starbelly
07f8a96aa1 Add run_cmd class method to ActiveRecord::Tasks::DatabaseTasks
-   Added run_cmd() class method to dry up Kernel.system() messages within
      this namespace and avoid shell expansion by passing a list of
      arguments instead of a string

  -   Update structure_dump, structure_load, and related tests units to
      pass a list of params instead of using a string to
      avoid shell expansion
2015-08-01 16:53:25 -05:00
Yves Senn
54901acbc9 minor AR changelog edits. [ci skip] 2015-08-01 12:12:54 +02:00
Sean Griffin
119b9181ec Properly allow uniqueness validations on primary keys.
This is an alternate implementation of #20966.

[Sean Griffin & presskey]
2015-07-25 13:05:53 -06:00
Sean Griffin
d937a1175f destroy shouldn't raise when child associations fail to save
Deep down in the association internals, we're calling `destroy!` rather
than `destroy` when handling things like `dependent` or autosave
association callbacks. Unfortunately, due to the structure of the code
(e.g. it uses callbacks for everything), it's nearly impossible to pass
whether to call `destroy` or `destroy!` down to where we actually need
it.

As such, we have to do some legwork to handle this. Since the callbacks
are what actually raise the exception, we need to rescue it in
`ActiveRecord::Callbacks`, rather than `ActiveRecord::Persistence` where
it matters. (As an aside, if this code wasn't so callback heavy, it
would handling this would likely be as simple as changing `destroy` to
call `destroy!` instead of the other way around).

Since we don't want to lose the exception when `destroy!` is called (in
particular, we don't want the value of the `record` field to change to
the parent class), we have to do some additional legwork to hold onto it
where we can use it.

Again, all of this is ugly and there is definitely a better way to do
this. However, barring a much more significant re-architecting for what
I consider to be a reletively minor improvement, I'm willing to take
this small hit to the flow of this code (begrudgingly).
2015-07-24 09:13:20 -06:00
Robin Dupret
ad5c1a3934 Rename the enum_{prefix,suffix} options to _{prefix,suffix}
This makes it more clear that they are reserved keywords and also it
seems less redundant as the line already starts with the call to the
`enum` method.
2015-07-23 14:27:09 +02:00
Sameer Rahmani
d763956ed9 Extra caller details added to ActiveRecord::RecordNotFound
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
2015-07-21 19:19:14 +04:30
Roque Pinel
b184398b53 Deprecate and rename the keys for association restrict_dependent_destroy
Previously `has_one` and `has_many` associations were using the
`one` and `many` keys respectively. Both of these keys have special
meaning in I18n (they are considered to be pluralizations) so by
renaming them to `has_one` and `has_many` we make the messages more
explicit and most importantly they don't clash with linguistical
systems that need to validate translation keys (and their
pluralizations).

The `:'restrict_dependent_destroy.one'` key should be replaced with
`:'restrict_dependent_destroy.has_one'`, and
`:'restrict_dependent_destroy.many'` with
`:'restrict_dependent_destroy.has_many'`.

[Roque Pinel & Christopher Dell]
2015-07-20 23:19:43 -04:00
Roque Pinel
12b0b26df7 Fix state being carried over from previous transaction
This clears the transaction record state when the transaction finishes
with a `:committed` status.

Considering the following example where `name` is a required attribute.
Before we had `new_record?` returning `true` for a persisted record:

```ruby
  author = Author.create! name: 'foo'
  author.name = nil
  author.save        # => false
  author.new_record? # => true
```
2015-07-20 09:12:01 -06:00
Sean Griffin
c0ef95a1c6 Correctly ignore mark_for_destruction without autosave
As per the docs, `mark_for_destruction` should do nothing if `autosave`
is not set to true. We normally persist associations on a record no
matter what if the record is a new record, but we were always skipping
records which were `marked_for_destruction?`.

Fixes #20882
2015-07-20 09:00:00 -06:00
Alberto F. Capel
476e3f552f Add #cache_key to ActiveRecord::Relation. 2015-07-20 01:46:03 +01:00
Stefan Kanev
0ed096ddf5 Fix counter_cache for polymorphic associations
Also removes a false positive test that depends on the fixed bug:

At this time, counter_cache does not work with polymorphic relationships
(which is a bug). The test was added to make sure that no
StaleObjectError is raised when the car is destroyed. No such error is
currently raised because the lock version is not incremented by
appending a wheel to the car.

Furthermore, `assert_difference` succeeds because `car.wheels.count`
does not check the counter cache, but the collection size. The test will
fail if it is replaced with `car.wheels_count || 0`.
2015-07-19 15:52:29 -06:00
Sean Griffin
7550f0a016 Ensure cyclic associations w/ autosave don't cause duplicate errors
This code is so fucked. Things that cause this bug not to replicate:

- Defining the validation before the association (we end up calling
  `uniq!` on the errors in the autosave validation)
- Adding `accepts_nested_attributes_for` (I have no clue why. The only
  thing it does that should affect this is adds `autosave: true` to the
  inverse reflection, and doing that manually doesn't fix this).

This solution is a hack, and I'm almost certain there's a better way to
go about it, but this shouldn't cause a huge hit on validation times,
and is the simplest way to get it done.

Fixes #20874.
2015-07-18 10:30:58 -04:00
Sean Griffin
68af636182 Ensure that ActionController::Parameters can still be passed to AR
Since nested hashes are also instances of
`ActionController::Parameters`, and we're explicitly looking to work
with a hash for nested attributes, this caused breakage in several
points.

This is the minimum viable fix for the issue (and one that I'm not
terribly fond of). I can't think of a better place to handle this at the
moment. I'd prefer to use some sort of solution that doesn't special
case AC::Parameters, but we can't use something like `to_h` or `to_a`
since `Enumerable` adds both.

While I've added a trivial test case for verifying this fix in
isolation, we really need better integration coverage to prevent
regressions like this in the future. We don't actually have a lot of
great places for integration coverage at the moment, so I'm deferring it
for now.

Fixes #20922.
2015-07-18 08:44:24 -04:00
Prem Sichanugrist
6eae366d0d Deprecate force association reload by passing true
This is to simplify the association API, as you can call `reload` on the
association proxy or the parent object to get the same result.

For collection association, you can call `#reload` on association proxy
to force a reload:

    @user.posts.reload   # Instead of @user.posts(true)

For singular association, you can call `#reload` on the parent object to
clear its association cache then call the association method:

    @user.reload.profile   # Instead of @user.profile(true)

Passing a truthy argument to force association to reload will be removed
in Rails 5.1.
2015-07-15 14:07:45 -04:00
Jerry D'Antonio
284a9ba8ec Replaced ActiveSupport::Concurrency::Latch with concurrent-ruby.
The concurrent-ruby gem is a toolset containing many concurrency
utilities. Many of these utilities include runtime-specific
optimizations when possible. Rather than clutter the Rails codebase with
concurrency utilities separate from the core task, such tools can be
superseded by similar tools in the more specialized gem. This commit
replaces `ActiveSupport::Concurrency::Latch` with
`Concurrent::CountDownLatch`, which is functionally equivalent.
2015-07-13 15:44:21 -04:00
Dmitry Zudochkin
3d5580fa85 Update CHANGELOG.md 2015-07-07 13:03:44 +03:00
Sean Griffin
bc6ac8609c Correct through associations using scopes
The changes introduced to through associations in c80487eb were quite
interesting. Changing `relation.merge!(scope)` to `relation =
relation.merge(scope)` should in theory never cause any changes in
behavior. The subtle breakage led to a surprising conclusion.

The old code wasn't doing anything! Since `merge!` calls
`instance_exec` when given a proc, and most scopes will look something
like `has_many :foos, -> { where(foo: :bar) }`, if we're not capturing
the return value, it's a no-op. However, removing the `merge` causes
`unscope` to break.

While we're merging in the rest of the chain elsewhere, we were never
merging in `unscope` values, causing a breakage on associations where a
default scope was being unscoped in an association scope (yuk!). This is
subtly related to #20722, since it appears we were previously relying on
this mutability.

Fixes #20721.
Fixes #20727.
2015-06-30 10:00:30 -07:00
Yves Senn
2183caa24a dump_schema_after_migration applies migration tasks other than db:migrate
Closes #20743.

The task `db:_dump` now only dumps the schema if
`ActiveRecord::Base.dump_schema_after_migration` is true. This has
effects:

- `db:migrate:up`
- `db:migrate:down`
- `db:forward`
- `db:rollback`
2015-06-30 16:36:03 +02:00
Prem Sichanugrist
a4128725f5 Add reversible syntax for change_column_default
Passing `:from` and `:to` to `change_column_default` makes this command
reversible as user has defined its previous state.

So, instead of having the migration command as:

    change_column_default(:posts, :state, "draft")

They can write it as:

    change_column_default(:posts, :state, from: nil, to: "draft")
2015-06-26 16:25:13 -04:00
Yves Senn
5e75f51692 Merge pull request #20552 from jamesdabbs/belongs-to-polymorphic-force-reload
Fix `undefined method uncached` for polymorphic belongs_to #20426
2015-06-23 10:19:54 +02:00
Yves Senn
8e27fd9594 Merge pull request #20545 from dcrec1/20541
thrown ActiveRecord::AssociationTypeMismatch when assigning a wrong value for a namespaced association
2015-06-23 09:09:02 +02:00
Diego Carrion
828d0d7a77 thrown ActiveRecord::AssociationTypeMismatch when assigning a wrong value for a namespaced association
fixes #20541
2015-06-22 12:38:54 -03:00
Yves Senn
30c9aa7883 AR absence validator respects marked_for_destruction?. Closes #20449.
Associated objects that were marked for destruction are considered absent.
2015-06-22 15:45:08 +02:00
Sean Griffin
b644964b2b Include Enumerable in ActiveRecord::Relation
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]
2015-06-19 15:35:35 -06:00
Sean Griffin
7d14bd3ff5 Use Enumerable#sum on ActiveRecord::Relation when a block is given
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.
2015-06-19 10:44:43 -06:00
Yves Senn
ee066afd18 Merge pull request #19843 from marshall-lee/explain_cte_queries
Let WITH (CTE) queries be explainable

Conflicts:
	activerecord/CHANGELOG.md
2015-06-19 10:45:57 +02:00
Yves Senn
0e928de345 make remove_index :table, :column reversible.
This used to raise a `IrreversibleMigration` error (since #10437).
However since `remove_index :table, :column` is probably the most basic
use-case we should make it reversible again.

Conflicts:
	activerecord/CHANGELOG.md
2015-06-15 09:42:26 +02:00
Yves Senn
863fcfa79a quick pass over changelogs. [ci skip] 2015-06-15 09:33:27 +02:00
Sean Griffin
07b4078eb6 Don't crash when mutating attributes in a getter
If a getter has side effects on the DB, `changes_applied` will be called
twice. The second time will try and remove the changed attributes cache,
and will crash because it's already been unset. This also demonstrates
that we shouldn't assume that calling getters won't change the value of
`changed_attributes`, and we need to clear the cache if an attribute is
modified.

Fixes #20531.
2015-06-12 11:03:12 -06:00
Yves Senn
98cacae101 Merge pull request #20226 from EpicH0liday/reversible-remove-foreign-key
Make remove_foreign_key reversible

Conflicts:
	activerecord/CHANGELOG.md
2015-06-12 15:45:19 +02:00
Igor Kapkov
09bef7684a Add enum prefix/suffix option to enum definition
Fixes #17511 and #17415
2015-06-12 12:07:55 +08:00
Aster Ryan
a186663b3d Add an invert method for remove_foreign_key 2015-06-11 19:24:46 -04:00
Sean Griffin
850d313c3b Credit the author of #20515 in the previous commit
[Sean Griffin & jmondo]
2015-06-11 16:52:10 -06:00
Sean Griffin
5b35562d8e Correctly handle array columns with defaults in the schema dumper
If the subtype provides custom schema dumping behavior, we need to defer
to it. We purposely choose not to handle any values other than an array
(which technically should only ever be `nil`, but I'd rather code
defensively here).

Fixes #20515.
2015-06-11 16:50:25 -06:00
Mehmet Emin İNAÇ
7f2037a990 Add missing data types for ActiveRecord migrations 2015-06-08 10:57:03 +03:00
Sean Griffin
9f4a3fd738 Return a Point object from the PG Point type
This introduces a deprecation cycle to change the behavior of the
default point type in the PostgreSQL adapter. The old behavior will
continue to be available for the immediate future as `:legacy_point`.

The current behavior of returning an `Array` causes several problems,
the most significant of which is that we cannot differentiate between an
array of points, and a point itself in the case of a column with the
`point[]` type.

The attributes API gives us a reasonable way to have a proper
deprecation cycle for this change, so let's take advantage of it. If we
like this change, we can also add proper support for the other geometric
types (line, lseg, box, path, polygon, and circle), all of which are
just aliases for string today.

Fixes #20441
2015-06-05 09:06:45 -06:00
Yves Senn
b25436abc4 minor formatting changes in changelogs. [ci skip] 2015-05-31 11:24:36 +02:00
Sean Griffin
0ef7e73f0a Ensure symbols passed to select are always quoted
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
2015-05-30 12:35:51 -06:00
Sean Griffin
6bd2573869 Add docs and changelog entry for 73aab03 [ci skip] 2015-05-30 11:13:28 -06:00
Ryuta Kamizono
e5e3ec2085 Add CHANGELOG entry for #17654 [ci skip] 2015-05-30 09:05:52 -07:00
Vladimir Kochnev
acdb006ad0 Let WITH (CTE) queries be explainable 2015-05-28 14:10:09 +03:00
Shane Hender
87b07ef003 Give credit to extra contributor for Base.reload fix 2015-05-28 10:25:50 +01:00
Akshay Vishnoi
3932912a59 Add collation support for string and text columns in SQLite3 2015-05-28 08:40:40 +05:30
Rafael Mendonça França
d81f147003 Merge pull request #20171 from georgeclaghorn/enums-in-fixtures
Allow the use of symbols or strings to specify enum values in test fixtures
2015-05-27 23:52:37 -03:00