Commit Graph

724 Commits

Author SHA1 Message Date
Arthur Neves
b7fcad8ff0 Fix regression on .select_* methods.
This was a common pattern:
```
query = author.posts.select(:title)
connection.select_one(query)
```

However `.select` returns a ActiveRecord::AssociationRelation, which has
the bind information, so we can use that to get the right sql query.

Also fix select_rows on postgress and sqlite3 that were not using the binds

[fixes #7538]
[fixes #12017]
[related #13731]
[related #12056]
2014-01-30 14:06:40 -05:00
Rafael Mendonça França
5977e7e4d5 Aesthetic 2014-01-29 20:48:43 -02:00
Mauricio Linhares
c9346322b1 Fixing issue with activerecord serialization not being able to dump a record after loading it from YAML - fixes #13861 2014-01-29 18:44:32 -03:00
Rafael Mendonça França
fec1028d08 Merge pull request #13201 from marcandre/find_in_batch_enumerator
`find_in_batches` now returns an `Enumerator`

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/relation/batches.rb
2014-01-29 17:53:10 -02:00
Godfrey Chan
40f0257e05 enum now raises on "dangerous" name conflicts
Dangerous name conflicts includes instance or class method conflicts
with methods defined within `ActiveRecord::Base` but not its ancestors,
as well as conflicts with methods generated by other enums on the same
class.

Fixes #13389.
2014-01-29 10:54:51 -08:00
Godfrey Chan
7e8e91c439 scope now raises on "dangerous" name conflicts
Similar to dangerous attribute methods, a scope name conflict is
dangerous if it conflicts with an existing class method defined within
`ActiveRecord::Base` but not its ancestors.

See also #13389.

*Godfrey Chan*, *Philippe Creux*
2014-01-29 10:54:51 -08:00
Mauricio Linhares
66e533f9b1 Correctly send the string given to lock! and reload(:lock) to the lock scope - fixes #13788
As per the documentation at lock!, if the :lock option is a string it should use the given SQL to generate the lock statement.
2014-01-29 12:37:00 -03:00
Tsutomu Kuroda
c1d9934447 Handle aliased attributes in AR::Relation#select, #order, etc.
With this we can write `Model#select(:aliased)`, `Model#order(:aliased)`,
`Model#reoder(aliased: :desc)`, etc.

Supplementary work to 54122067acaad39b277a5363c6d11d6804c7bf6b.
2014-01-29 09:16:46 +09:00
Rafael Mendonça França
8f17a834ae Improve the CHANGELOG entry [ci skip] 2014-01-22 13:25:12 -02:00
Kelsey Schlarman
43675f014c Calling reset on a collection association should unload the assocation
Need to define #reset on CollectionProxy.
2014-01-21 18:24:28 -08:00
Rafael Mendonça França
9383de42a2 Merge pull request #13776 from rails/dirty-enum
Implement the Dirty API with the Enum feature correctly.

Conflicts:
	activerecord/CHANGELOG.md
2014-01-21 20:37:45 -02:00
Rafael Mendonça França
b0a8ef140e has_one and belongs_to accessors don't add ORDER BY to the queries anymore.
Since Rails 4.0, we add an ORDER BY in the `first` method to ensure consistent
results among different database engines. But for singular associations this
behavior is not needed since we will have one record to return. As this
ORDER BY option can lead some performance issues we are removing it for singular
associations accessors.

Fixes #12623.
2014-01-21 14:41:52 -02:00
Yves Senn
e011258c30 prepend table name for Relation#select columns.
This fixes a bug where `select(:id)` combined with `joins()` raised:

```
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: id:
SELECT  id, authors.author_address_id
FROM "posts"
INNER JOIN "authors"
ON "authors"."id" = "posts"."author_id"
ORDER BY posts.id LIMIT 3
```

The `select_values` are still String and Symbols because other parts (mainly calculations.rb)
rely on that fact.

/cc @tenderlove
2014-01-21 17:21:20 +01:00
Rafael Mendonça França
a57a2bcf4a Make enum feature work with dirty methods
To make this possible we have to override the save_changed_attribute
hook.
2014-01-21 12:45:53 -02:00
Yves Senn
6f0aa1d64d Active Record changelog wording and formatting. [ci skip] 2014-01-21 14:35:33 +01:00
Alexander Balashov
691709dd67 Fail early with "Primary key not included in the custom select clause" in find_in_batches
Before this patch find_in_batches raises this error only on second iteration. So you will know about the problem only when you get the batch size threshold.
2014-01-21 17:27:34 +04:00
Jason Meller
cafe31a078 Ensure #second acts like #first AR finder
This commit bring the famous ordinal Array instance methods defined
in ActiveSupport into ActiveRecord as fully-fledged finders.

These finders ensure a default ascending order of the table's primary
key, and utilize the OFFSET SQL verb to locate the user's desired
record. If an offset is defined in the query, calling #second adds
to the offset to get the actual desired record.

Fixes #13743.
2014-01-20 16:58:18 -05:00
Godfrey Chan
7386ffc781 Restore ActiveRecord states after a rollback for models w/o callbacks
This fixes a regression (#13744) that was caused by 67d8bb9.

In 67d8bb9, we introduced lazy rollback for records, such that the
record's internal states and attributes are not restored immediately
after a transaction rollback, but deferred until they are first
accessed.

This optimization is only performed when the model does not have any
transactional callbacks (e.g. `after_commit` and `after_create`).

Unfortunately, the models used to test the affected codepaths all
comes with some sort of transactional callbacks. Therefore this
codepath remains largely untested until now and as a result there are
a few issues in the implementation that remains hidden until now.

First, the `sync_with_transaction_state` (or more accurately,
`update_attributes_from_transaction_state`) would perform the
synchronization prematurely before a transaction is finalized (i.e.
comitted or rolled back). As a result, when the actuall rollback
happens, the record will incorrectly assumes that its internal states
match the transaction state, and neglect to perform the restore.

Second, `update_attributes_from_transaction_state` calls `committed!`
in some cases. This in turns checks for the `destroyed?` state which
also requires synchronization with the transaction stae, which causes
an infnite recurrsion.

This fix works by deferring the synchronization until the transaction
has been finalized (addressing the first point), and also unrolled
the `committed!` and `rolledback!` logic in-place (addressing the
second point).

It should be noted that the primary purpose of the `committed!` and
`rolledback!` methods are to trigger the relevant transactional
callbacks. Since this code path is only entered when there are no
transactional callbacks on the model, this shouldn't be necessary. By
unrolling the method calls, the intention here (to restore the states
when necessary) becomes more clear.
2014-01-18 11:16:52 -08:00
Harry Brundage
177989c6c0 Make AR::Base#touch fire the after_commit and after_rollback callbacks 2014-01-16 09:05:59 -02:00
Cody Cutrer
547ed45633 sqlite >= 3.8.0 supports partial indexes 2014-01-14 08:53:32 -07:00
Ujjwal Thaakar
e8d1d84837
Don't try to get the subclass if the inheritance column doesn't exist
The `subclass_from_attrs` method is called even if the column specified by
the `inheritance_column` setting doesn't exist. This prevents setting associations
via the attributes hash if the association name clashes with the value of the setting,
typically `:type`. This worked previously in Rails 3.2.
2014-01-14 18:53:45 +05:30
Godfrey Chan
b242b2dbe7 Enum mappings are now exposed via class methods instead of constants.
Example:

    class Conversation < ActiveRecord::Base
      enum status: [ :active, :archived ]
    end

Before:

    Conversation::STATUS # => { "active" => 0, "archived" => 1 }

After:

    Conversation.statuses # => { "active" => 0, "archived" => 1 }
2014-01-14 04:00:34 -08:00
Yves Senn
66f3d5bd5a quick pass through Active Record CHANGELOG. [ci skip] 2014-01-14 09:19:37 +01:00
Chulki Lee
bea44cbaa4 Set NameError#name 2014-01-13 12:47:14 -08:00
Yves Senn
e95031f55d fix bug in becomes! when changing from base to subclass. Closes #13272. 2014-01-13 15:07:14 +01:00
schneems
6cc03675d3 Ensure Active Record connection consistency
Currently Active Record can be configured via the environment variable `DATABASE_URL` or by manually injecting a hash of values which is what Rails does, reading in `database.yml` and setting Active Record appropriately. Active Record expects to be able to use `DATABASE_URL` without the use of Rails, and we cannot rip out this functionality without deprecating. This presents a problem though when both config is set, and a `DATABASE_URL` is present. Currently the `DATABASE_URL` should "win" and none of the values in `database.yml` are used. This is somewhat unexpected to me if I were to set values such as `pool` in the `production:` group of `database.yml` they are ignored.

There are many ways that active record initiates a connection today:

- Stand Alone (without rails)
  - `rake db:<tasks>`
  - ActiveRecord.establish_connection
 
- With Rails
  - `rake db:<tasks>`
  - `rails <server> | <console>`
  - `rails dbconsole`


We should make all of these behave exactly the same way. The best way to do this is to put all of this logic in one place so it is guaranteed to be used.

Here is my prosed matrix of how this behavior should work:

```
No database.yml
No DATABASE_URL
=> Error
```

```
database.yml present
No DATABASE_URL
=> Use database.yml configuration
```

```
No database.yml
DATABASE_URL present
=> use DATABASE_URL configuration
```

```
database.yml present
DATABASE_URL present
=> Merged into `url` sub key. If both specify `url` sub key, the `database.yml` `url`
   sub key "wins". If other paramaters `adapter` or `database` are specified in YAML,
   they are discarded as the `url` sub key "wins".
```

### Implementation

Current implementation uses `ActiveRecord::Base.configurations` to resolve and merge all connection information before returning. This is achieved through a utility class: `ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig`.

To understand the exact behavior of this class, it is best to review the behavior in activerecord/test/cases/connection_adapters/connection_handler_test.rb though it should match the above proposal.
2014-01-09 16:35:37 -06:00
Robin Dupret
f4fc9e65ed Minor typos fix [ci skip] 2014-01-08 16:40:49 +01:00
Yves Senn
724509a9d5 make change_column_null reversible. Closes #13576.
Closes #13623.
2014-01-08 15:51:06 +01:00
Damien Mathieu
a334425caf create/drop test and development databases only if RAILS_ENV is nil
Closes #13625
2014-01-08 14:37:07 +01:00
Rafael Mendonça França
f12413295b Merge pull request #13355 from dylanahsmith/migration-version
activerecord: Initialize Migration with version from MigrationProxy.

Conflicts:
	activerecord/CHANGELOG.md
2014-01-07 18:44:51 -02:00
Nishant Modak
eb589fed6f Make change_table use object of current database adapter
- Earlier, change_table was creating database-agnostic object.
  - After this change, it will create correct object based on current
    database adapter.
  - This will ensure that create_table and change_table will get same objects.
  - This makes update_table_definition method public and nodoc.
  - Fixes #13577 and #13503
2014-01-07 15:57:21 +05:30
Dylan Thacker-Smith
06ace1e2b5 activerecord: Initialize Migration with version from MigrationProxy. 2014-01-06 10:46:35 -05:00
Yves Senn
f2b80a41b5 Merge pull request #13593 from oliveiraethales/store_yaml_coder
Fix: ActiveRecord::Store TypeError conversion when using YAML coder
2014-01-06 05:43:14 -08:00
Thales Oliveira
901a0c8b4a Fix: ActiveRecord::Store TypeError conversion when using YAML coder
Renaming the test accordingly to its behaviour

Adding 'Fixes' statement to changelog

Improving tests legibility & changelog

Undoing mistakenly removed empty line & further improving changelog
2014-01-06 11:36:19 -02:00
Yves Senn
535bd55fcd quick formatting pass through CHANGELOGS. [ci skip]. 2014-01-06 10:57:00 +01:00
Jon Leighton
27bcec28bf Fix mergefail in changelog
The line was duplicated
2014-01-04 09:30:01 +00:00
T.J. Schuck
72bb3fc297 Change all "can not"s to the correct "cannot". 2014-01-03 17:02:31 -05:00
Yves Senn
97e7ca48c1 Deprecate unused symbolized_base_class and symbolized_sti_name.
These methods were only used for the `IdentityMap` which was removed.
They are no longer used internally and should be removed without replacement.

As they were not `:nodoc:`'ed it's better to deprecate them before removal.
2014-01-03 16:31:20 +01:00
Jon Leighton
ff7ab3bc78 Automatically maintain test database schema
* Move check from generated helper to test_help.rb, so that all
  applications can benefit
* Rather than just raising when the test schema has pending migrations,
  try to load in the schema and only raise if there are pending
  migrations afterwards
* Opt out of the check by setting
  config.active_record.maintain_test_schema = false
* Deprecate db:test:* tasks. The test helper is now fully responsible
  for maintaining the test schema, so we don't need rake tasks for this.
  This is also a speed improvement since we're no longer reloading the
  test database on every call to "rake test".
2014-01-02 13:49:00 +00:00
Rafael Mendonça França
f141919974 Add CHANGELOG entry for #13557 [ci skip] 2014-01-01 19:08:28 -02:00
Rafael Mendonça França
b94e2dd82c Merge pull request #13550 from vipulnsward/13437-fix
Fix for #13437

Conflicts:
	activerecord/CHANGELOG.md
2014-01-01 14:14:45 -02:00
Amr Tamimi
e0ad9ae27e Add the ability to nullify the enum column 2014-01-01 01:48:15 +02:00
Vipul A M
bb17c3b210 2075f39d72 introduced a regression in includes/preloades
by calling `read_attribute` on an association when preloading takes places, instead of using loaded records in `association.target`.

tl;dr

Records are not made properly available via `read_attribute` when preloding in simultaneous,
but value of `@loaded` is already set true, and records concatenated in `association.target` on an association object.
When `@loaded` is true we return an object of `AlreadyLoaded` in preload_for. In `AlreadyLoaded` to return preloaded
records we make wrong use of `read_attribute`, instead of `target` records.

The regression is fixed by making use of the loaded records in `association.target` when the preloading takes place.

Fixes #13437
2013-12-31 02:47:37 +05:30
schneems
5b96027ef6 Allow "url" sub key in database.yml configuration
Currently a developer can pass in a YAML configuration that fully specifies connection information:

```
production:
  database: triage_production
  adapter: password
  pool: 5
```

They can also pass in a string that specifies a connection URL directly to an environment key:

```
production: postgresql://localhost/foo
```

This PR allows the use of both a connection url and specifying connection attributes via YAML through the use of the "url" sub key:

```
production:
  url: postgresql://localhost/foo
  pool: 3
```

This will allow developers to inherit Active Record options such as `pool` from `&defaults` and still use a secure connection url such as `<%= ENV['DATABASE_URL'] %>`. The URL is expanded into a hash and then merged back into the YAML hash. If there are any conflicts, the values from the connection URL are preferred. 

Talked this over with @josevalim
2013-12-30 12:21:14 -05:00
Yves Senn
2ab3bd16f9 tidy AR CHANGELOG. [ci skip] 2013-12-30 12:18:45 +01:00
Robin Dupret
ec4b44b1a4 Add a missing changelog entry for #13534 [ci skip] 2013-12-30 12:15:14 +01:00
schneems
f0311c2487 Raise NoDatabaseError when db does not exist
Building on the work of #13427 this PR adds a helpful error message to the adapters: mysql, mysql2, and sqlite3
2013-12-24 10:13:12 -05:00
José Valim
ec11807368 Deprecate use of string in establish_connection as connection lookup 2013-12-24 10:18:54 +01:00
Carlos Antonio da Silva
9e1740af9c Tidy up fix for PG extensions quoting
Always pass in the column for quote_bound_value and quote using it in
case it exists there.
2013-12-23 16:28:35 -02:00
Tadas Tamosauskas
73bba4c1e1 Serialize postgres' hstore, json and array types correctly in AR update methods.
Fixes #12261. Closes #12395.

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/cases/adapters/postgresql/array_test.rb
	activerecord/test/cases/adapters/postgresql/json_test.rb
2013-12-23 16:27:54 -02:00