Commit Graph

1302 Commits

Author SHA1 Message Date
Yves Senn
591a0bb87f Merge pull request #20574 from repinel/fix-db-fixtures-load
Allow fixtures YAML files to set the model class in the file itself

Conflicts:
	activerecord/CHANGELOG.md
2015-09-30 11:06:41 +02:00
Sean Griffin
37661bfc81 validates_acceptance_of shouldn't require a database connection
The implementation of `attribute_method?` on Active Record requires
establishing a database connection and querying the schema. As a general
rule, we don't want to require database connections for any class macro,
as the class should be able to be loaded without a database (e.g. for
things like compiling assets).

Instead of eagerly defining these methods, we do it lazily the first
time they are accessed via `method_missing`. This should not cause any
performance hits, as it will only hit `method_missing` once for the
entire class.
2015-09-25 07:54:38 -06:00
Jean Boussier
4ccdd4122d Implement ActiveRecord::Base.ignored_columns 2015-09-24 11:04:44 -04:00
Sean Griffin
4a375a83de Merge pull request #21550 from didacte/unscope-associations
ActiveRecord: use association's `unscope` when preloading
2015-09-24 08:50:22 -06:00
Sean Griffin
66337b62ad Merge pull request #20317
AR: take precision into count when assigning a value to timestamp
attribute
2015-09-23 09:01:38 -06:00
Bogdan Gusiev
d03f519665 Fixed taking precision into count when assigning a value to timestamp attribute
Timestamp column can have less precision than ruby timestamp
In result in how big a fraction of a second can be stored in the
database.

  m = Model.create!
  m.created_at.usec == m.reload.created_at.usec
    # => false
    # due to different seconds precision in Time.now and database column

If the precision is low enough, (mysql default is 0, so it is always low
enough by default) the value changes when model is reloaded from the
database. This patch fixes that issue ensuring that any timestamp
assigned as an attribute is converted to column precision under the
attribute.
2015-09-23 13:29:08 +03:00
Yves Senn
152b85f06c introduce conn.data_source_exists? and conn.data_sources.
These new methods are used from the Active Record model layer to
determine which relations are viable to back a model. These new methods
allow us to change `conn.tables` in the future to only return tables and
no views. Same for `conn.table_exists?`.

The goal is to provide the following introspection methods on the
connection:

* `tables`
* `table_exists?`
* `views`
* `view_exists?`
* `data_sources` (views + tables)
* `data_source_exists?` (views + tables)
2015-09-22 19:48:44 +02:00
Yves Senn
3931cec9cd Merge pull request #20569 from theSteveMitchell/master
Check mysql structure_load for errors
2015-09-22 11:10:58 +02: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
Jeremy Daer
26aa1b58b0 Merge pull request #17696 from kamipo/unsigned_integer_support
Add `unsigned` support for numeric data types in MySQL
2015-09-19 17:44:57 -07:00
Jeremy Daer
7286677050 Merge pull request #21609 from kamipo/do_not_dump_view_as_table
Do not dump a view as a table in sqlite3, mysql and mysql2 adapters
2015-09-19 15:56:01 -07:00
Ryuta Kamizono
ab12859947 Correctly dump composite primary key
Example:

    create_table :barcodes, primary_key: ["region", "code"] do |t|
      t.string :region
      t.integer :code
    end
2015-09-20 06:43:00 +09:00
Ryuta Kamizono
dfeb3ee78a Add unsigned types for numeric data types in MySQL
In the case of using `unsigned` as the type:

    create_table :foos do |t|
      t.unsigned_integer :unsigned_integer
      t.unsigned_bigint  :unsigned_bigint
      t.unsigned_float   :unsigned_float
      t.unsigned_decimal :unsigned_decimal, precision: 10, scale: 2
    end
2015-09-18 20:22:32 +09:00
Ryuta Kamizono
f3772f729c Add unsigned support for numeric data types in MySQL
Example:

    create_table :foos do |t|
      t.integer :unsigned_integer, unsigned: true
      t.bigint  :unsigned_bigint,  unsigned: true
      t.float   :unsigned_float,   unsigned: true
      t.decimal :unsigned_decimal, unsigned: true, precision: 10, scale: 2
    end
2015-09-18 20:22:32 +09:00
Yves Senn
9feda8f211 Merge pull request #21581 from ronakjangir47/restrict_with_error
`restrict_with_error` message will now respect owner’s human name
2015-09-17 16:30:10 +02:00
Ryuta Kamizono
dcd39949f8 Add #views and #view_exists? methods on connection adapters 2015-09-13 21:02:43 +09:00
Roque Pinel
2acec46577 Allow fixtures YAML files to set the model class in the file itself
Currently, `set_fixture_class` is only available using the
`TestFixtures` concern and it is ignored for `rake db:fixtures:load`.
Using the correct model class, it is possible for the fixture load
to also load the associations from the YAML files (e.g., `:belongs_to`
and `:has_many`).
2015-09-11 14:29:06 -04:00
Matthew Draper
8c34d106ca Correct query for PostgreSQL 8.2
Generic cast-to-text was only added in 8.3.
2015-09-08 04:32:38 +09:30
Yves Senn
8e155b0a9a Merge pull request #21527 from rngtng/fix-migrator-path-setup
Use global migrations_path configuration in Migrator
2015-09-07 16:23:42 +02:00
Tobias Bielohlawek
73726340c3 Allow global migrations_path configuration with using value from database_tasks instead of Migrator 2015-09-07 16:05:21 +02:00
Yves Senn
488afd5cc3 changelog, minor formatting changes. 2015-09-07 15:52:02 +02:00
Matthew Draper
0962527953 Merge pull request #21317 from greysteil/support-postgres-drop-index-concurrently
Support dropping indexes concurrently in Postgres
2015-09-07 00:15:11 +09:30
Wojciech Wnętrzak
c82c5f8ffd Deprecate passing conditions to AR::Relation destroy_all and delete_all methods 2015-09-06 16:14:16 +02:00
Grey Baker
ce17e232a1 Support dropping indexes concurrently in Postgres
See http://www.postgresql.org/docs/9.4/static/sql-dropindex.html
for more details.
2015-09-05 17:04:03 +01:00
Yves Senn
35df925b47 pg, create_schema, drop_schema and rename_table quote schema name.
Closes #21418.

Previously schema names were not quoted. This leads to issues when a
schema names contains a ".". Methods in `schema_statements.rb` should
quote user input.
2015-08-28 15:59:37 +02:00
Yves Senn
dd118dcc45 PostgreSQL, add :if_exists to #drop_schema. 2015-08-28 11:35:12 +02:00
Agis-
19b168e611 Only nullify persisted has_one target associations
Since after 87d1aba3c `dependent: :destroy` callbacks on has_one
assocations run *after* destroy, it is possible that a nullification is
attempted on an already destroyed target:

    class Car < ActiveRecord::Base
      has_one :engine, dependent: :nullify
    end

    class Engine < ActiveRecord::Base
      belongs_to :car, dependent: :destroy
    end

    > car = Car.create!
    > engine = Engine.create!(car: car)
    > engine.destroy! # => ActiveRecord::ActiveRecordError: cannot update a
    >   destroyed record

In the above case, `engine.destroy!` deletes `engine` and *then* triggers the
deletion of `car`, which in turn triggers a nullification of `engine.car_id`.
However, `engine` is already destroyed at that point.

Fixes #21223.
2015-08-24 11:49:43 +03:00
Yves Senn
50e4afff20 uniqueness validation raises error for persisted record without pk.
Closes #21304.

While we can validate uniqueness for record without primary key on
creation, there is no way to exclude the current record when
updating. (The update itself will need a primary key to work correctly).
2015-08-20 12:07:02 +02:00
Ryuta Kamizono
89d5d1cafb Add a native JSON data type support in MySQL
As of MySQL 5.7.8, MySQL supports a native JSON data type.

Example:

    create_table :json_data_type do |t|
      t.json :settings
    end
2015-08-18 16:13:00 +09:00
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