Commit Graph

4151 Commits

Author SHA1 Message Date
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
Rafael Mendonça França
b1b21f9325 Merge pull request #13745 from nextgearcapital/master
set encoding for pipe to binary mode
2014-01-19 10:24:22 -08: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
Aaron Patterson
c1bbf1b2e4 test to ensure bad prepared statements raise a StatementInvalid exception 2014-01-17 14:08:00 -08:00
Anna Carey
0e9144dcec set encoding to binmode for pipe 2014-01-17 16:49:10 -05:00
Carlos Antonio da Silva
49223c9bc9 Extract a method to simplify setup code 2014-01-16 18:52:43 -02:00
Carlos Antonio da Silva
740cf33b5e Use minitest's skip rather than conditionals + early returns 2014-01-16 18:48:51 -02:00
Carlos Antonio da Silva
44e5551054 Move AR test classes inside the test case 2014-01-16 18:45:03 -02:00
Carlos Antonio da Silva
c9c4a427e1 Do not set up a variable used only in two tests
Just create a local variable whenever we need the record, rather than
doing an extra find for every test on the setup method.
2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
07ff3525d5 No need for instance vars on single tests 2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
da4b5e8ecb Cleanup duplicated setup of callbacks in transactions tests 2014-01-16 18:40:18 -02:00
Carlos Antonio da Silva
7b11b06e6d No need to use #send with public methods 2014-01-16 18:40:17 -02:00
Harry Brundage
177989c6c0 Make AR::Base#touch fire the after_commit and after_rollback callbacks 2014-01-16 09:05:59 -02:00
Carlos Antonio da Silva
38fcee3871 Fix test for cache_key + touched
Ensure the child can actually be touched. The `Bulb` model has no
timestamp column, thus trying to touch it would return `nil`.
2014-01-16 09:05:55 -02:00
Yves Senn
6eab530429 reset column information after fiddling with Encoding.default_internal
This solves order depndent problems in `base_test.rb`. The leaked column
information crashed test cases using the `Weird` class later on:

```
  2) Error:
BasicsTest#test_group_weirds_by_from:
SyntaxError: /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
... attribute_before_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *arg...
...                               ^
/Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
...te_before_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *args)
...                               ^
/Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:387: invalid hex escape
...e_type_cast("\x{A4CA}\x{A4DE}\x{A4A8}", *args)
...                               ^
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:385:in `module_eval'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:385:in `define_proxy_call'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:294:in `block in define_attribute_method'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:285:in `each'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:285:in `define_attribute_method'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `block in define_attribute_methods'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `each'
    /Users/senny/Projects/rails/activemodel/lib/active_model/attribute_methods.rb:252:in `define_attribute_methods'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:72:in `block in define_attribute_methods'
    /Users/senny/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/mutex_m.rb:73:in `synchronize'
    /Users/senny/.rbenv/versions/2.0.0-p353/lib/ruby/2.0.0/mutex_m.rb:73:in `mu_synchronize'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:69:in `define_attribute_methods'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_methods.rb:174:in `method_missing'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:45:in `public_send'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:45:in `_assign_attribute'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:32:in `block in assign_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:26:in `each'
    /Users/senny/Projects/rails/activerecord/lib/active_record/attribute_assignment.rb:26:in `assign_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/core.rb:458:in `init_attributes'
    /Users/senny/Projects/rails/activerecord/lib/active_record/core.rb:191:in `initialize'
    /Users/senny/Projects/rails/activerecord/lib/active_record/inheritance.rb:30:in `new'
    /Users/senny/Projects/rails/activerecord/lib/active_record/inheritance.rb:30:in `new'
    /Users/senny/Projects/rails/activerecord/lib/active_record/persistence.rb:33:in `create'
    test/cases/base_test.rb:646:in `test_group_weirds_by_from'
```
2014-01-16 09:34:49 +01:00
Yves Senn
fca8b0318e we have with_env_tz as global test helper. Remove duplicate. 2014-01-16 09:34:49 +01:00
Yves Senn
a713900839 isolate class attribute assignment in migration_test.rb
This makes the tests inside `migration_test.rb` order independent.
The assignments to `Reminder.table_name_prefix` and `Reminder.table_name_suffix`
previously leaked and had impact on following test cases.

This patch isolates the assignments on a throw-away subclass.
2014-01-16 09:33:45 +01:00
Yves Senn
f00524375d use teardown for cleanup, not setup.
This solves order dependent issues where the last test
leaked the query cache state. This resulted in the following error:

```
QueryCacheExpiryTest#test_cache_is_expired_by_habtm_delete [test/cases/query_cache_test.rb:275]:
not all expectations were satisfied
unsatisfied expectations:
- expected exactly twice, invoked once: #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x7f93e0c65838>.clear_query_cache(any_parameters)
```
2014-01-16 09:33:45 +01:00
Yves Senn
8e1735e26c tests without transactional fixtures need to cleanup afterwards.
This fixes test order issues.
2014-01-16 09:33:45 +01:00
Yves Senn
a6512cbd6c no need to return skip in tests. skip is enough. 2014-01-16 09:33:45 +01:00
Aaron Patterson
8d146c8bec rm dup code
e64a83cdbd/activerecord/test/cases/relation/merging_test.rb (L80-91)
2014-01-14 17:47:10 -08:00
Aaron Patterson
ce95fb2991 "string" isn't a valid column type for ActiveRecord
Conflicts:
	activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
2014-01-14 14:01:10 -08:00
Yves Senn
b23330745b don't establish a new connection when testing with sqlite3_mem.
This fixes broken `rake test_sqlite3_mem` suite for Active Record.
The problem is that that the old database with the schema is lost
when establishing a new connection. Upon reconnting we are left
with a blank database and tests down the line start failing.
2014-01-14 18:03:31 +01: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
f6ca00bd43 Merge pull request #13669 from chulkilee/name-error-name
Set NameError#name
2014-01-14 00:12:54 -08:00
Aaron Patterson
f1764a2de1 unscope should remove bind values associated with the where 2014-01-13 16:15:20 -08:00
Aaron Patterson
d220e8add9 recover from test runs that leave the database in a bad state 2014-01-13 15:02:28 -08: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
Yves Senn
792c66f868 use enum labels as form values. Achieved by _before_type_cast.
Closes #13650, #13672

This is an alternate implementation to solve #13650. Currently form fields
contain the enum value (eg. "1"). This breaks because the setter `enum=`
expects the label (eg. "active").

ActiveRecord::Enum allows you to use labels in your application but store numbers.
We should make sure that all parts after AR are dealing with labels and not the
underlying mapping to a number.

This patch defines `_before_type_cast` on every enum column to return the label.
This method is later used to fetch the value to display in form fields.

I deliberately copied the implementation of the enum getter instead of delegating to it.
This allows you to overwrite the getter and for example return a `Value Object` but have it
still work for form fields.
2014-01-11 12:57:09 +01:00
Prathamesh Sonpatki
e633cdb34a Restore DATABASE_URL even if it's nil in connection_handler test
- We have to restore DATABASE_URL to its previous state irrespective of
  previous value is nil or not
2014-01-10 10:06:19 +05:30
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
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
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
Matthias Zirnstein
bf556880f2 Remove method redefined warnings for test suite
has_many definitions with "name" as singular and as plural e.g.
  has_many :welcome_posts_with_comment
  has_many :welcome_posts_with_comments

Ruby mentions it with:

lib/active_record/associations/builder/collection_association.rb:65:
  warning: method redefined; discarding old welcome_posts_with_comment_ids
lib/active_record/associations/builder/collection_association.rb:65:
  warning: previous definition of welcome_posts_with_comment_ids was here
lib/active_record/associations/builder/collection_association.rb:75:
  warning: method redefined; discarding old welcome_posts_with_comment_ids=
lib/active_record/associations/builder/collection_association.rb:75:
  warning: previous definition of welcome_posts_with_comment_ids= was here
2014-01-05 18:18:07 +01:00
T.J. Schuck
72bb3fc297 Change all "can not"s to the correct "cannot". 2014-01-03 17:02:31 -05:00
Rafael Mendonça França
19b2188e6c Merge pull request #10134 from derikson/collection_proxy_select_with_multiple_args
Change CollectionProxy#select to take the same arguments as ActiveRecord::select
2014-01-03 13:03:19 -08:00
Godfrey Chan
788bb40e38 Building new records with enum scopes now works as expected
Previously, this would give an `ArgumentError`:

   class Issue < ActiveRecord::Base
     enum :status, [:open, :finished]
   end

   Issue.open.build # => ArgumentError: '0' is not a valid status
   Issue.open.create # => ArgumentError: '0' is not a valid status

PR #13542 muted the error, but the issue remains. This commit fixes
the issue by allowing the enum value to be written directly via the
setter:

   Issue.new.status = 0 # This now sets status to :open

Assigning a value directly via the setter like this is not part of the
documented public API, so users should not rely on this behavior.

Closes #13530.
2014-01-03 09:31:01 -08:00
Rafael Mendonça França
358abe4524 Merge pull request #13542 from robin850/issue-13530
Fix enum writers when using integers
2014-01-01 19:17:59 -02: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
a28f1c2793 Merge pull request #13557 from gmarik/patch-1
Use `Array#wrap` instead `Array()`
2014-01-01 19:04:29 -02:00
Robin Dupret
7aebcb67b0 Fix the enums writer methods
Previously, the writer methods would simply check whether the passed
argument was the symbol representing the integer value of an enum field.
Therefore, it was not possible to specify the numeric value itself but
the dynamically defined scopes generate where clauses relying on this
kind of values so a chained call to a method like `find_or_initialize_by`
would trigger an `ArgumentError`.

Reference #13530
2014-01-01 17:57:34 +01:00
Rafael Mendonça França
da0463cf5e Improve the tests to not call assert_nothing_raised 2014-01-01 14:15:01 -02:00