Commit Graph

7394 Commits

Author SHA1 Message Date
Rafael França
159c73ac6d Merge pull request #23954 from kamipo/fix_undefined_method_fields
Fix `NoMethodError: undefined method `fields' for nil:NilClass`
2016-03-01 15:25:54 -03:00
Rafael Mendonça França
bc57930e09 Merge pull request #23417 from sgringwe/master
Add option to error on ignored order or limit
2016-03-01 14:36:32 -03:00
Matthew Draper
541e4abb4b Merge pull request #23807 from matthewd/executor
Publish AS::Executor and AS::Reloader APIs
2016-03-02 02:56:53 +10:30
Matthew Draper
ecdc0fbc87 Merge pull request #23598 from brchristian/activerecord_second_to_last
ActiveRecord #second_to_last tests and finder methods
2016-03-02 02:28:17 +10:30
Matthew Draper
833b14c8f8 Merge pull request #22170 from samphilipd/sam/properly_deallocate_prepared_statements_outside_of_transaction
Correctly deallocate prepared statements if we fail inside a transaction
2016-03-02 02:23:11 +10:30
Matthew Draper
d3c9d808e3 Publish AS::Executor and AS::Reloader APIs
These should allow external code to run blocks of user code to do
"work", at a similar unit size to a web request, without needing to get
intimate with ActionDipatch.
2016-03-02 02:14:20 +10:30
Sean Griffin
af2c427c39 Respect through association scopes when used with polymorphic
When the `source_type` option is passed to a has_many through, the
resulting `Reflection` will be an instance of `PolymorphicReflection`
and not `ThroughReflection`, meaning that it will ignore the scopes that
it needs to apply from the through reflections. This adds an additional
delegation call to remedy this. I've been finding the reflection code
completely impenetrable lately, it could use some major love.

Fixes #22726
2016-02-29 14:50:50 -07:00
Sean Griffin
67aa8f1943 Merge pull request #18766 from yasyf/issue_17864
Honour joining model order in `has_many :through` associations when
eager loading
2016-02-29 11:20:43 -07:00
Ryuta Kamizono
a74414c330 Add a test for primary key should be not null 2016-02-29 21:31:18 +09:00
Ryuta Kamizono
3cc62a9776 Fix NoMethodError: undefined method fields' for nil:NilClass`
Currently `exec_query` raises `NoMethodError` when executing no result
queries (`INSERT`, `UPDATE`, `DELETE`, and all DDL) in mysql2 adapter.

```
irb(main):002:0> conn.execute("create table t(a int)")
   (43.3ms)  create table t(a int)
=> nil
irb(main):003:0> conn.execute("insert into t values (1)")
   (19.3ms)  insert into t values (1)
=> nil
irb(main):004:0> conn.exec_query("insert into t values (1)")
  SQL (28.6ms)  insert into t values (1)
NoMethodError: undefined method `fields' for nil:NilClass
```
2016-02-29 13:26:12 +09:00
Ryuta Kamizono
1f6da4fda6 Remove unnecessary namespaces in explain_test.rb 2016-02-29 12:33:21 +09:00
Ryuta Kamizono
8d7554e919 Fix tests failure with prepared_statements: false
Some tests does not work for unprepared statements.
Add `if ActiveRecord::Base.connection.prepared_statements` and fix a
regex for fix tests failure with `prepared_statements: false`.
2016-02-29 12:22:08 +09:00
Brian Christian
f5a9c5bd40 comment out failing .second and .third tests 2016-02-27 11:35:50 -08:00
Brian Christian
d4d1fe53a1 adding additional tests for offset and limit behavior 2016-02-27 11:10:19 -08:00
Brian Christian
761dc68d57 additional test assertions (limit and offset) 2016-02-27 11:10:19 -08:00
Brian Christian
048fd13ccd AR #second_to_last tests and finder methods 2016-02-27 11:10:19 -08:00
Arthur Neves
2abcdfd978 Remove load_paths file 2016-02-27 13:03:57 -05:00
eileencodes
ecf6dc3dfb Fix test name typo prescence -> presence 2016-02-27 11:20:03 -05:00
Ryan T. Hosford
11e7069be2 Fixes funny spelling
- marked_for_destroyal -> marked_for_destruction
2016-02-26 20:52:49 -06:00
Joe Rafaniello
0379da6abc Fix uniqueness validation with an after_create hook.
record.id_was is nil in after_create/after_save, so we should use
id in these cases.

While this logic feels incomplete, the existing update_record uses the same
logic:
2fda4e0874/activerecord/lib/active_record/relation.rb (L83)

This logic was originally added for a similar problem:
updates not working with after_create hook.

See: 482f8c15b1d699c95bfbc3d836f674a09c0d9031

Followup to #23581
Fixes #23844
2016-02-25 10:13:12 -05:00
eileencodes
73f8c16601 Ensure suppressor runs before validations
I ran into an issue where validations on a suppressed record were
causing validation errors to be thrown on a record that was never going
to be saved.

There isn't a reason to run the validations on a record that doesn't
matter.

This change moves the suppressor up the chain to be run on the `save` or
`save!` in the validations rather than in persistence. The issue with
running it when we hit persistence is that the validations are run
first, then we hit persistance, and then we hit the suppressor. The
suppressor comes first.

The change to the test was required since I added the
`validates_presence_of` validations. Adding this alone was enough to
demonstrate the issue. I added a new test to demonstrate the new
behavior is explict.
2016-02-24 14:33:22 -05:00
Ryuta Kamizono
95441c7b3b Ensure drop_table even if tests failure or interrupted
I was encountered remaining `:binary_testings` table by tests failure.
When remaining `:binary_testings` table, never reach `drop_table` due to
`create_table` in the test always fails.
2016-02-24 23:15:46 +09:00
Ryuta Kamizono
5d146f6e73 drop_table :test_text_limits as well
Follow up to 3b01785.
2016-02-24 10:39:07 +09:00
eileencodes
2c02bc0a47 Revert changes to validations from PR #18612
In order to fix issue #17621 we added a check to validations that
determined if a record should be validated. Based on the existing tests
and behavior we wanted we determined the best way to do that was by
checking if `!record.peristed? || record.changed? || record.marked_for_destruction?`

This change didn't make it into a release until now. When #23790 was
opened we realized that `valid?` and `invalid?` were broken and did not
work on persisted records because of the `!record.persisted?`.

While there is still a bug that #17621 brought up, this change was too
drastic and should not be a RC blocker. I will work on fixing this so
that we don't break `valid?` but also aren't validating parent records
through child records if that parent record is validate false. This
change removes the code changes to validate and the corresponding tests.
It adds tests for two of the bugs found since Rails 5 beta2 release.

Fixes #17621
2016-02-23 15:21:46 -05:00
Sean Griffin
96c1ada82d Merge pull request #23628 from maclover7/fix-23625
Fix issue #23625
2016-02-23 12:24:07 -07:00
Rafael França
3adc35aefa Merge pull request #23789 from wisetara/wisetara/deprecate-args-ActiveSupport__TestCase#assert_nothing_raised-for-pr
Wisetara/deprecate args active support  test case#assert nothing raised for pr
2016-02-23 13:59:49 -03:00
Rafael Mendonça França
3b017856f7 Make sure we don't change the global state in the tests
We are creating the table but not deleting after the test.
2016-02-23 12:21:53 -03:00
Ryuta Kamizono
43c2055f61 Remove needless drop_table :test_limits
A `:test_limits` table has not been created.
2016-02-23 23:54:29 +09:00
Tara Scherner de la Fuente
926a24a751 remove args from assert_nothing_raised in tests 2016-02-22 22:56:23 -08:00
Matthew Draper
d6db96663d Merge pull request #23419 from prathamesh-sonpatki/fix-showing-of-deprecation-warning-for-legacy-migrations
Correctly show deprecation warning for incompatible migrations
2016-02-23 14:59:13 +10:30
Johannes Opper
894facb196 Fix bug in JSON deserialization when column default is an empty string
When `ActiveRecord::Coders::JSON` serialization is used and the default of the column returns `''` it raises the following error:

```
JSON::ParserError: A JSON text must at least contain two octets!
```

If MySQL is running in non-strict mode, it returns an empty string as column default for a text column:

```ruby
def extract_default
  if blob_or_text_column?
    @default = null || strict ? nil : ''
  end
end
```

Since `''` is invalid JSON, there shouldn't be an attempt to parse it, it should be treated like nil.
ActiveRecord::Coders::JSON should behave consistently for all possible non-user-set column default values.
2016-02-22 17:59:51 +01:00
Rafael França
aa3d440871 Merge pull request #23521 from kamipo/fix_assert_in_delta_failure
Fix `assert_in_delta` test failure
2016-02-22 12:05:39 -03:00
Matthew Draper
c901fad42c Merge pull request #22748 from Azzurrio/master
Fix NoMethodError preparable for Arel::Visitors::PostgreSQL
2016-02-22 22:33:25 +10:30
Andrew White
3591a00ea6 Merge pull request #23751 from chezou/add-test-case-order-by-field
Add test cases about MySQL ORDER BY FIELD()
2016-02-22 11:50:03 +00:00
Ryuta Kamizono
b8f86ae29f The BINARY Operator is only needed for string columns
Follow up to #13040.
2016-02-22 10:03:03 +09:00
Azzurrio
babf5d1d2d Fix NoMethodError preparable for Arel::Visitors in case prepared statements is falsy 2016-02-22 01:19:34 +02:00
Ian Fleeton
e3cfbca3b2 Match test name to test (typo) 2016-02-21 21:00:49 +00:00
Matthew Draper
22c318d6cf Merge pull request #23794 from matthewd/mutation-safe-to_a
Mutating the result of Relation#to_a should not affect the relation
2016-02-21 09:13:56 +10:30
Matthew Draper
cdd45fa09d Mutating the result of Relation#to_a should not affect the relation
Clarifying this separation and enforcing relation immutability is the
culmination of the previous efforts to remove the mutator method
delegations.
2016-02-21 03:28:18 +10:30
Eileen M. Uchitelle
eb65f04fb2 Merge pull request #23793 from qazbnm456/master
fix typo
2016-02-20 09:36:04 -05:00
eileencodes
6f15b276cb Always validate record if validating a virtual attribute
Fixes #23645

When you're using an `attr_accessor` for a record instead of an
attribute in the database there's no way for the record to know if it
has `changed?` unless you tell it `attribute_will_change!("attribute")`.

The change made in 27aa4dd updated validations to check if a record was
`changed?` or `marked_for_destruction?` or not `persisted?`. It did not
take into account virtual attributes that do not affect the model's
dirty status.

The only way to fix this is to always validate the record if the
attribute does not belong to the set of attributes the record expects
(in `record.attributes`) because virtual attributes will not be in that
hash.

I think we should consider deprecating this particular behavior in the
future and requiring that the user mark the record dirty by noting that
the virtual attribute will change. Unfortunately this isn't easy because
we have no way of knowing that you did the "right thing" in your
application by marking it dirty and will get the deprecation warning
even if you are doing the correct thing.

For now this restores expected behavior when using a virtual attribute
by always validating the record, as well as adds tests for this case.

I was going to add the `!record.attributes.include?(attribute)` to the
`should_validate?` method but `uniqueness` cannot validate a virtual
attribute with nothing to hold on to the attribute. Because of this
`should_validate?` was about to become a very messy method so I decided
to split them up so we can handle it specifically for each case.
2016-02-20 09:15:39 -05:00
Lobsiinvok
b2d1de2697 fix typo 2016-02-20 17:36:49 +08:00
Aaron Patterson
2df891dccd eliminate warnings about multiple primary keys on habtm join tables
habtm join tables commonly have two id columns and it's OK to make those
two id columns a primary key.  This commit eliminates the warnings for
join tables that have this setup.

  ManageIQ/manageiq#6713
2016-02-19 15:31:56 -08:00
Michiaki Ariga
25dbfba263 Add assertions order by field with empty data
Add assertions to MySQL `ORDER BY FIELD()` with empty data.
These tests examine to sanitize `ORDER BY FIELD()` with empty data
appropriately.

```ruby
  Tag.order(['field(id, ?)', []]).to_sql
  # => SELECT "tags".* FROM "tags" ORDER BY field(id, NULL)

  Tag.order(['field(id, ?)', nil]).to_sql
  # => SELECT "tags".* FROM "tags" ORDER BY field(id, NULL)
```
2016-02-18 18:35:30 +09:00
Jon Moss
55385c8a39 Fix issue #23625
This resolves a bug where if the primary key used is not `id` (ex:
`uuid`), and has a `validates_uniqueness_of` in the model, a uniqueness error
would be raised. This is a partial revert of commit `119b9181ece399c67213543fb5227b82688b536f`, which introduced this behavior.
2016-02-18 00:32:38 -05:00
Sean Griffin
f1866e81a3 Merge pull request #22365 from phuibonhoa/phuibonhoa/polymorphic_where_multiple_types
Fixed `where` for polymorphic associations when passed an array containing different types.
2016-02-17 13:56:55 -08:00
Matthew Draper
011711ecc9 Merge pull request #23570 from rthbound/addresses-23568
Addresses #23568, Incorrect error message with accepts_nested_attributes_for / has_many & has_one
2016-02-18 07:45:22 +10:30
Prathamesh Sonpatki
e254665ac0 Show proper error message when a non-relation object is passed to AR::Relation#or
- Previously it used to show error message
    <"undefined method `limit_value' for {:title=>\"Rails\"}:Hash">

- Now it shows following error message.

    >> Post.where.not(name: 'DHH').or(name: 'Tenderlove')
    ArgumentError: You have passed Hash object to #or. Pass an ActiveRecord::Relation object instead.

- Fixes #23714.
2016-02-17 11:50:29 +05:30
Akshay
b13a00ede6 Fix semantics of test names for finish option in batches_test
- The change was added in #23099
2016-02-17 11:26:03 +05:30
Philippe Huibonhoa
359adaedd9 Fixed where for polymorphic associations when passed an array containing different types.
When passing in an array of different types of objects to `where`, it would only take into account the class of the first object in the array.

    PriceEstimate.where(estimate_of: [Treasure.find(1), Car.find(2)])
	# => SELECT "price_estimates".* FROM "price_estimates"
         WHERE ("price_estimates"."estimate_of_type" = 'Treasure' AND "price_estimates"."estimate_of_id" IN (1, 2))

This is fixed to properly look for any records matching both type and id:

    PriceEstimate.where(estimate_of: [Treasure.find(1), Car.find(2)])
    # => SELECT "price_estimates".* FROM "price_estimates"
         WHERE (("price_estimates"."estimate_of_type" = 'Treasure' AND "price_estimates"."estimate_of_id" = 1)
         OR ("price_estimates"."estimate_of_type" = 'Car' AND "price_estimates"."estimate_of_id" = 2))
2016-02-16 10:41:26 -08:00
David Genord II
72eee06b88 Test parent local_stored_attributes isn't modified
Saw the `merge!` and had to prove to myself that the parent model's local_stored_attributes was not being changed when stored_attributes is called on a child model. Proved to be working as expected but this test is probably still useful to keep around.
2016-02-16 11:42:04 -05:00
Yves Senn
84c18246bc Merge pull request #23614 from georgemillo/foreign_key
Let t.foreign_key use the same `to_table` twice

Conflicts:
	activerecord/CHANGELOG.md
2016-02-16 11:54:49 +01:00
George Millo
aedde2a33d Let t.foreign_key use the same to_table twice
Previously if you used `t.foreign_key` twice within the same
`create_table` block using the same `to_table`, all statements except
the final one would fail silently. For example, the following code:

    def change
      create_table :flights do |t|
        t.integer :from_id, index: true, null: false
        t.integer :to_id,   index: true, null: false

        t.foreign_key :airports, column: :from_id
        t.foreign_key :airports, column: :to_id
      end
    end

Would only create one foreign key, on the column `from_id`.

This commit allows multiple foreign keys to the same table to be created
within one `create_table` block.
2016-02-15 16:04:34 -07:00
Eileen M. Uchitelle
7ee2002008 Merge pull request #23377 from bogdan/last-with-sql
Fix AR::Relation#last bugs instroduced in 7705fc
2016-02-13 09:45:04 -05:00
Ryuta Kamizono
1335959135 Fix grammar a to an [ci skip] 2016-02-13 20:44:44 +09:00
Bogdan Gusiev
b679916143 Make ActiveRecord::Relation#last to reverse SQL order
instead of loading the relation into memory
2016-02-13 10:32:51 +02:00
Ryuta Kamizono
811a4fa8eb Avoid a string value truncation in uniqueness validation
In MySQL, PostgreSQL, Oracle and SQLServer, a value over the limit
cannot be inserted or updated (See #23522).

In SQLite3, a value is inserted or updated regardless of the limit.

We should avoid a string value truncation in uniqueness validation.
2016-02-12 23:57:15 +09:00
Prathamesh Sonpatki
33b0dbe407 Fix random failures of tests on Travis
- Tests on Travis are randomly failing because schema_migrations table
  does not exist in teardown block.
- Also checked that all other places where we have used
  `ActiveRecord::SchemaMigration.delete_all` we have rescued it, so used
  it here also. This failure was not specifically related to the test
  added in this PR but to overall compatibility migration tests, so
  adding as separate commit.
2016-02-12 19:46:03 +05:30
Prathamesh Sonpatki
5d643d365e Correctly show deprecation warning for incompatible migrations 2016-02-12 13:45:41 +05:30
Sean Griffin
6fedc7d56a Merge pull request #18109 from k0kubun/unscoped-joins
Allow `joins` to be unscoped

Fixes #13775
2016-02-11 11:33:30 -07:00
Sean Griffin
848f70e184 Merge pull request #23581 from diego-silva/uniqueness-validator-pk-fix
UniquenessValidator exclude itself when PK changed
2016-02-11 10:36:20 -07:00
Brian Christian
e8aeda2ab3 rename to 'second_to_last' and 'third_to_last' 2016-02-10 10:10:38 -08:00
Brian Christian
c74045cf07 allow Array.penultimate and Array.antepenultiate access methods 2016-02-09 16:02:08 -08:00
Diego Silva
f1daa2be52 UniquenessValidator exclude itself when PK changed
When changing the PK for a record which has a uniqueness validation on
some other attribute, Active Record should exclude itself from the
validation based on the PK value stored on the DB (id_was) instead of
its new value (id).
2016-02-09 21:28:21 -02:00
Ryan T. Hosford
91c13624be Addresses #23568
- Corrects an incorrect exception message when using accepts_nested_attributes_for
  - Removes rescue/reraise behavior introduced in #19077
  - Adds has_many & has_one, nested_attributes test case specifying the message that
    should be conveyed with an exception raised because one of the nested attributes provided is unknown
2016-02-09 08:01:29 -06:00
Vijay Dev
bef16522db Merge branch 'master' of github.com:rails/docrails 2016-02-07 07:14:50 +00:00
Ryuta Kamizono
6efd02e230 Add ActiveRecord::ValueTooLong exception class 2016-02-06 23:26:53 +09:00
Ryuta Kamizono
71366209d5 Fix assert_in_delta test failure
`assert_in_delta` in `timestamp_test.rb` causes an intermittent test
failure. It looks like that caused by subseconds truncation in MySQL 5.5.

Example:

```
  1) Failure:
  TimestampTest#test_touching_many_attributes_updates_them [/home/travis/build/rails/rails/activerecord/test/cases/timestamp_test.rb:125]:
  Expected |2016-02-06 09:22:10 +0000 - 2016-02-06 09:22:09 UTC| (1.000837185) to be <= 1.
```
2016-02-06 23:15:22 +09:00
yui-knk
3ee7bc87b1 [ci skip] Good bye SQLite2
Follow up of c9feea6c9a
2016-02-06 14:01:07 +09:00
Sean Griffin
d666a5a5cf Revert "Dump indexes in create_table instead of add_index"
This reverts commit 99801c6a7b69eb4b006a55de17ada78f3a0fa4c1.

Ultimately it doesn't matter whether `add_index` or `t.index` are used
in the schema dumper in any meaningful way. There are gems out there
which hook into the old behavior for things like indexing materialized
views. Since the reverted commit doesn't seem to add much benefit,
there's no reason for us to break these gems.
2016-02-05 13:33:48 -07:00
Jeremy Baker
96fdbd3be3 Remove accidental additional test 2016-02-04 11:13:05 -08:00
Jeremy Baker
d871696b4a Add a resolver test for the missing scheme 2016-02-04 10:59:52 -08:00
Akira Matsuda
250c0d08c4 Typos in AR tests 2016-02-04 17:24:00 +09:00
Sean Griffin
9df3083926 Merge pull request #23458 from kamipo/activerecord_supports_mysql_5.0_and_up
Active Record supports MySQL >= 5.0
2016-02-03 19:12:20 -07:00
Matthew Draper
eeaf6ee284 Merge pull request #23457 from matthewd/arel-attribute
Defer Arel attribute lookup to the model class
2016-02-04 09:43:21 +10:30
Ryuta Kamizono
c7f8019bff Active Record supports MySQL >= 5.0
Currently some features uses `information_schema` (e.g. foreign key
support). `information_schema` introduced since MySQL 5.0.
2016-02-04 07:08:33 +09:00
Matthew Draper
cdc112e3ea Defer Arel attribute lookup to the model class
This still isn't as separated as I'd like, but it at least moves most of
the burden of alias mapping in one place.
2016-02-04 08:02:45 +10:30
Akira Matsuda
887eaa8689 Typos in AR tests 2016-02-03 22:08:13 +09:00
Arthur Neves
bcd0c8cfc2 Merge pull request #20997 from himesh-r/issue-20995
Changed id-writer to save join table records based on association
primary key #20995.
2016-02-02 23:37:31 -05:00
Himesh
9c9fb19b9e Changed id-writer to save join table records based on association primary key #20995
Changed id-writer to save join table records based on association primary key
2016-02-02 23:36:31 -05:00
Scott Ringwelski
08a7481183 Add initial support for allowing an error on order or limit of queries being ignored in batches
add some documentation and add 4 tests regarding error vs. warning behavior

fix a typo when referring to the message

go back to default in tests so that ordering is not important. use a constant instead of method. fix assert_nothing_raised call. use self.klass to allow per class configuration

remove logger warn assets as that is tested elsewhere. pass error_on_ignore through find_each and find_in_batches also.

add blocks to the finds so that the code is actually executed

put the setting back to default in an ensure

Add a changelog entry
2016-02-02 15:05:16 -08:00
Sean Griffin
5bb26008ce Avoid infinite recursion when bad values are passed to tz aware fields
We had previously updated this to attempt to map over whatever was
passed in, so that additional types like range and array could benefit
from this behavior without the time zone converter having to deal with
every known type.

However, the default behavior of a type is to just yield the given value
to `map`, which means that if we don't actually know how to handle a
value, we'll just recurse infinitely. Since both uses of `map` in this
case occur in cases where we know receiving the same object will
recurse, we can just break on reference equality.

Fixes #23241.
2016-02-02 09:17:45 -07:00
Rafael França
7710d7f432 Merge pull request #23331 from amatsuda/valid_scope_name
Warn if a named scope is overwriting an existing scope or method
2016-02-02 05:00:15 -02:00
Jeremy Daer
633969f159 Merge pull request #23407 from jeremy/corrupt-before-commit
Fix corrupt transaction state caused by `before_commit` exceptions
2016-02-01 14:26:12 -07:00
Jeremy Daer
8fd123f7eb Fix corrupt transaction state caused by before_commit exceptions
When a `before_commit` callback raises, the database is rolled back but
AR's record of the current transaction is not, leaving the connection in
a perpetually broken state that affects all future users of the
connection: subsequent requests, jobs, etc. They'll think a transaction
is active when none is, so they won't BEGIN on their own. This manifests
as missing `after_commit` callbacks and broken ROLLBACKs.

This happens because `before_commit` callbacks fire before the current
transaction is popped from the stack, but the exception-handling path
they hit assumes that the current transaction was already popped. So the
database ROLLBACK is issued, but the transaction stack is left intact.

Common cause: deadlocked `#touch`, which is now implemented with
`before_commit` callbacks.

What's next:
* We shouldn't allow active transaction state when checking in or out
  from the connection pool. Verify that conns are clean.
* Closer review of txn manager sad paths. Are we missing other spots
  where we'd end up with incorrect txn state? What's the worst that can
  happen if txn state drifts? How can we guarantee it doesn't and
  contain the fallout if it does?

Thanks for @tomafro for expert diagnosis!
2016-02-01 14:12:49 -07:00
Sean Griffin
0cbcae59dd Revert "Merge pull request #16400 from bogdan/last-with-sql"
This reverts commit 9f3730a516f30beb0050caea9539f8d6b808e58a, reversing
changes made to 2637fb75d82e1c69333855abd58c2470994995d3.

There are additional issues with this commit that need to be addressed
before this change is ready (see #23377). This is a temporary revert in
order for us to have more time to address the issues with that PR,
without blocking the release of beta2.
2016-02-01 14:03:12 -07:00
Yasuo Honda
407e0ab5e5 Rename active_record_internal_metadatas to ar_internal_metadata
for those who already migrated to Rails 5.0.0 beta
2016-02-01 15:52:30 +00:00
Yasuo Honda
a374af8b57 Shorten ActiveRecord::InternalMetadata.table_name to ar_internal_metadata
to support Oracle database which only supports 30 byte identifier length
2016-02-01 15:41:37 +00:00
Akira Matsuda
407baa2b4c tabenai (typo) 2016-02-01 16:19:12 +09:00
Ryuta Kamizono
57604cf24c Avoid extra show variables in migration
`initialize_schema_migrations_table` is called in every migrations.

https://github.com/rails/rails/blob/v5.0.0.beta1/activerecord/lib/active_record/migration.rb#L1080
https://github.com/rails/rails/blob/v5.0.0.beta1/activerecord/lib/active_record/schema.rb#L51

This means that extra `show variables` is called regardless of the
existence of `schema_migrations` table.

This change is to avoid extra `show variables` if `schema_migrations`
table exists.
2016-02-01 13:05:47 +09:00
Rafael França
2f8ba24ec6 Merge pull request #23359 from kamipo/make_to_primary_key
Make to primary key instead of an unique index for internal tables
2016-02-01 01:53:57 -02:00
Ryuta Kamizono
f3eccd942a Remove duplicated composite primary key tests 2016-02-01 11:20:30 +09:00
Rafael França
43dff0a7b1 Merge pull request #23372 from kamipo/use_index_in_create_in_test_schema
Use `t.index` in `create_table` instead of `add_index` in test schema
2016-02-01 00:01:50 -02:00
Rafael França
c9daa2690a Merge pull request #23374 from prathamesh-sonpatki/migration-compatiblity-tests
Added test for backward compatibility of null constraints on timestamp columns
2016-01-31 23:59:29 -02:00
Akira Matsuda
87e2f7e336 🙊 ⚠️ 2016-02-01 10:35:19 +09:00
Prathamesh Sonpatki
6e2302ee59 Added test for backward compatibility of null constraints on timestamp columns 2016-01-31 15:02:46 +05:30
Ryuta Kamizono
8e083e1502 Use t.index in create_table instead of add_index in test schema
For reduce bootstrap queries in tests.
2016-01-31 17:36:04 +09:00
Ryuta Kamizono
ff16a39922 Make to primary key instead of an unique index for internal tables 2016-01-31 03:26:57 +09:00
Takashi Kokubun
12e9e38d9a Allow joins to be unscoped 2016-01-31 02:30:09 +09:00
Rafael França
a59212709c Merge pull request #23345 from yui-knk/warning_when_composite_primary_key_is_detected
Warn if `AR.primary_key` is called for a table who has composite prim…
2016-01-30 12:21:52 -05:00
Rafael França
b789f6dff4 Merge pull request #23355 from kamipo/fix_bigint_for_enum_columns
Fix `bigint?` for Enum columns in MySQL
2016-01-30 12:19:00 -05:00
Ryuta Kamizono
d0054b4908 Fix bigint? for Enum columns in MySQL
Follow up to #22896.
2016-01-31 01:07:02 +09:00
yui-knk
e05d828b1f There is no need to define test if a connection does not support primary_key 2016-01-31 00:01:26 +09:00
yui-knk
444c4d05fe Warn if AR.primary_key is called for a table who has composite primary key
If `AR.primary_key` is called for a table who has composite primary key,
the method returns `nil`. This behavior sometimes generates invalid SQL.
The first time developers notice to invalid SQL is when they execute
SQL. This commit enables developers to know they are doing something
dangerous as soon as possible.
2016-01-30 16:47:51 +09:00
Bogdan Gusiev
7705fcf0b6 Reworked ActiveRecord::Relation#last to always use SQL
instead of loading relation
2016-01-28 17:45:53 +02:00
Akira Matsuda
2812af720e Suppress ⚠️s 2016-01-28 22:30:52 +09:00
Akira Matsuda
60b8ab710d scope needs the second argument 2016-01-28 22:29:55 +09:00
Akira Matsuda
dc925119a3 Revert "Remove valid_scope_name? check - use ruby"
This reverts commit f6db31ec16e42ee7713029f7120f0b011d1ddc6c.

Reason:
Scope names can very easily conflict, particularly when sharing Concerns
within the team, or using multiple gems that extend AR models.

It is true that Ruby has the ability to detect this with the -w option, but the
reality is that we are depending on too many gems that do not care about Ruby
warnings, therefore it might not be a realistic solution to turn this switch on
in our real-world apps.
2016-01-28 18:37:39 +09:00
James Wen
867a9cbbb8 Improve clarity of error message for missing includes and eager_load
relations
2016-01-28 00:41:26 -05:00
Sean Griffin
74bee8353b Merge pull request #18928 from bogdan/unreversable-order
Raise AR::IrreversibleOrderError when #reverse_order can not do it's job
2016-01-27 23:26:34 -05:00
Sean Griffin
77383fc1e4 Do not use default attributes for STI when instantiating a subclass
The commit which originally added this behavior did not consider that
doing `Subclass.new` does not actually populate the `type` field in the
attributes (though perhaps it should). We simply need to not use the
defaults for STI related things unless we are instantiating the base
class.

Fixes #23285.
2016-01-27 13:26:20 -05:00
Bogdan Gusiev
14efb42a90 Introduce ActiveRecord::IrreversibleOrderError
Raises when #reverse_order can not process SQL order instead of making
invalid SQL before this patch
2016-01-27 12:53:51 +02:00
Aaron Patterson
6dfab475ca Merge branch '5-0-beta-sec'
* 5-0-beta-sec:
  bumping version
  fix version update task to deal with .beta1.1
  Eliminate instance level writers for class accessors
  allow :file to be outside rails root, but anything else must be inside the rails view directory
  Don't short-circuit reject_if proc
  stop caching mime types globally
  use secure string comparisons for basic auth username / password
2016-01-25 11:25:11 -08:00
Richard Schneeman
4962b44755 Merge pull request #23161 from schneems/schneems/fix-mysql-internalmetadata
[close #23009] Limit key length
2016-01-25 08:54:44 -06:00
Vipul A M
0eef20af66 When verifying size of relation, also verify count is ok. 2016-01-25 13:41:21 +05:30
Rafael França
5119171d39 Merge pull request #23221 from vipulnsward/23209-fix-missin_source_type
Add missing source_type if provided on hmt which belongs to an sti re…
2016-01-24 13:08:32 -05:00
Prathamesh Sonpatki
29cf0dd9f4 Fix AR::Relation#cache_key to remove select scope added by user
- We don't need the select scope added by user as we only want to max
  timestamp and size of the collection. So we already know which columns
  to select.
- Additionally having user defined columns in select scope blows the cache_key
  method with PostGreSQL because it needs all `selected` columns in the group_by
  clause or aggregate function.
- Fixes #23038.
2016-01-24 22:36:13 +05:30
Vipul A M
b334bc93c6 Add missing source_type if provided on hmt which belongs to an sti record
Fixes #23209
2016-01-24 22:25:12 +05:30
Kasper Timm Hansen
8c1f248c58 Merge pull request #23081 from prathamesh-sonpatki/fix-cache-key-for-queries-with-offset
Fix ActiveRecord::Relation#cache_key for relations with no results
2016-01-24 16:24:31 +01:00
Prathamesh Sonpatki
909818b93b Pare back default index option for the migration generator
- Using `references` or `belongs_to` in migrations will always add index
  for the referenced column by default, without adding `index:true` option
  to generated migration file.
- Users can opt out of this by passing `index: false`.
- Legacy migrations won't be affected by this change. They will continue
  to run as they were before.
- Fixes #18146
2016-01-24 18:48:15 +05:30
Sean Griffin
67c1719012 Use the database type to deserialize enum
This fixes incorrect assumptions made by e991c7b that we can assume the
DB is already casting the value for us. The enum type needs additional
information to perform casting, and needs a subtype.

I've opted not to call `super` in `cast`, as we have a known set of
types which we accept there, and the subtype likely doesn't accept them
(symbol -> integer doesn't make sense)

Close #23190
2016-01-23 08:44:16 -07:00
Andrew White
0fde6f554b Don't short-circuit reject_if proc
When updating an associated record via nested attribute hashes the
reject_if proc could be bypassed if the _destroy flag was set in the
attribute hash and allow_destroy was set to false.

The fix is to only short-circuit if the _destroy flag is set and the
option allow_destroy is set to true. It also fixes an issue where
a new record wasn't created if _destroy was set and the option
allow_destroy was set to false.

CVE-2015-7577
2016-01-22 15:00:50 -08:00
Prathamesh Sonpatki
66023eccb6 Fix ActiveRecord::Relation#cache_key for relations with no results
- When relations return no result or 0 result then cache_key should
  handle it gracefully instead of blowing up trying to access
  `result[:size]` and `result[:timestamp]`.
- Fixes #23063.
2016-01-22 11:19:10 +05:30
Matthew Draper
a688c0317d Merge pull request #23080 from prathamesh-sonpatki/fix-cache-key-for-loaded-empty-collection
Fix ActiveRecord::Relation#cache_key for loaded empty collection
2016-01-22 16:07:59 +10:30
schneems
8897e05ea3 [close #23009] Limit key length
Mysql has a weird bug where it cannot index a string column of utf8mb4 if it is over a certain character limit. To get compatibility with msql we can add a limit to the key column. 191 characters is a very long key, it seems reasonable to limit across all adapters since using a longer key wouldn't be supported in mysql.

Thanks to @kamipo for the original PR and the test refactoring.

Conversation: https://github.com/rails/rails/pull/23009#issuecomment-171416629
2016-01-21 13:19:33 -06:00
Prathamesh Sonpatki
e55ba530c1 Fix test failure on PostgreSQL by sorting the result before comparison 2016-01-19 22:45:25 +05:30
Yves Senn
3ea4476942 run type column through attribtues API type casting.
Closes #21986.

This makes it possible to write custom types that define a different
mapping for STI columns.
2016-01-19 17:31:16 +01:00
Vipul A M
da26934313 Changed options for find_each and variants to have options start/finish instead of start_at/end_at based on comments
at https://github.com/rails/rails/pull/12257#issuecomment-74688344
2016-01-18 12:40:30 +05:30
Prathamesh Sonpatki
8126925447 Fix ActiveRecord::Relation#cache_key for loaded empty collection
- Before this patch if we try to find cache_key of a loaded but empty
  collection it used to give error because of trying to call `updated_at`
  on `nil` value generated by
  `collection.max_by(&timestamp_column).public_send(timestamp_column)`.
- This commit fixes above error by checking if size is greater than zero
  or not.
2016-01-16 12:47:26 +05:30
Rafael França
de2259791c Merge pull request #20005 from kamipo/default_expression_support
Add `:expression` option support on the schema default
2016-01-16 04:18:21 -02:00
Rafael França
efe346f23a Merge pull request #23067 from kamipo/sql_for_insert_returns_values_for_passing_to_exec_insert
`sql_for_insert` returns values for passing to `exec_insert`
2016-01-16 03:42:55 -02:00
Ryuta Kamizono
89653edaf6 sql_for_insert returns values for passing to exec_insert 2016-01-15 20:52:36 +09:00
schneems
a95a554c7e Fix intermittent test failures
😳
2016-01-14 15:33:14 -06:00
schneems
4fc3074403 Revert "Revert "Set environment even when no migration runs""
This reverts commit 11e85b91731ca6125ee1db33553f984549a3bc2b.
2016-01-14 15:09:18 -06:00
Sean Griffin
11e85b9173 Revert "Set environment even when no migration runs" 2016-01-14 13:59:10 -07:00
Kasper Timm Hansen
1aa1cec777 Revert "Merge pull request #20835 from glittershark/if-and-unless-in-secure-token"
This reverts commit 224eddfc0eeff6555ae88691306e61c7a9e8b758, reversing
changes made to 9d681fc74c6251d5f2b93fa9576c9b2113116680.

When merging the pull request, I misunderstood `has_secure_token` as declaring a model
has a token from birth and through the rest of its lifetime.

Therefore, supporting conditional creation doesn't make sense. You should never mark a
model as having a secure token if there's a time when it shouldn't have it on creation.
2016-01-14 21:52:03 +01:00
Sean Griffin
434ec23714 Merge pull request #23048 from kamipo/substitute_at_is_no_longer_used
`substitute_at` is no longer used
2016-01-14 13:43:04 -07:00
Sean Griffin
f138bea5da Properly include the from clause when merging relations
The code that set the from clause was removed in
bdc5141652770fd227455681cde1f9899f55b0b9. I did not give any reason for
doing so. My assumption was that I intended to change it to use the
clause objects, but forgot. We appeared to not have test coverage for
this case.

Fixes #22996
2016-01-14 13:36:30 -07:00
Richard Schneeman
5854de3885 Merge pull request #23017 from schneems/schneems/migration-sets-environment-value
Set environment even when no migration runs
2016-01-14 13:07:35 -06:00
Ryuta Kamizono
a557ab00f5 substitute_at is no longer used
Arel handles substitution for bind parameters by now.
2016-01-14 09:59:26 +09:00
Ryuta Kamizono
744552f72d Fix extract default with CURRENT_TIMESTUMP 2016-01-13 22:03:56 +09:00
Ryuta Kamizono
5fd30ac52d Add expression support on the schema default
Example:

    create_table :posts do |t|
      t.datetime :published_at, default: -> { 'NOW()' }
    end
2016-01-13 22:03:56 +09:00
Yves Senn
ede2343031 fix regression when loading fixture files with symbol keys.
Closes #22584.
2016-01-13 10:11:54 +01:00
Rafael Mendonça França
f466cd7fc4 Improve error message for #or when it is structurally incompatible
When you are using scopes and you chaining these scopes it is hard to
know which are the values that are incompatible. This way you can read
the message and know for which values you need to look for.

[Herminio Torres]
2016-01-13 01:13:18 -02:00
Sean Griffin
b64b754510 Revert "Change WhereClause#merge to same named columns on diff tables"
This reverts commit 5d41cb3bfd6b19833261622ce5d339b1e580bd8b.

This implementation does not properly handle cases involving predicates
which are not associated with a bind param. I have the fix in mind, but
don't have time to implement just yet. It will be more similar to #22823
than not.
2016-01-12 15:48:00 -07:00
Sean Griffin
5d41cb3bfd Change WhereClause#merge to same named columns on diff tables
While the predicates are an arel equality node where the left side is a
full arel attribute, the binds just have the name of the column and
nothing else. This means that while splitting the predicates can include
the table as a factor, the binds cannot. It's entirely possible that we
might be able to have the bind params carry a bit more information (I
don't believe the name is used for anything but logging), and that is
probably a worthwhile change to make in the future.

However the simplest (and likely slightly faster) solution is to simply
use the indices of the conflicts in both cases. This means that we only
have to compute the collision space once, instead of twice even though
we're doing an additional array iteration. Regardless, this method isn't
a performance hotspot.

Close #22823.

[Ben Woosley & Sean Griffin]
2016-01-12 14:38:25 -07:00
Matthew Draper
5c6d365383 Skip the STI condition when evaluating a default scope
Given a default_scope on a parent of the current class, where that
parent is not the base class, the parent's STI condition would become
attached to the evaluated default scope, and then override the child's
own STI condition.

Instead, we can treat the STI condition as though it is a default scope,
and skip it in this situation: the scope will be merged into the base
relation, which already contains the correct STI condition.

Fixes #22426.
2016-01-12 05:43:58 +10:30
Matthew Draper
8ce0175d50 Active scopes apply to child classes, though not parents/siblings
While the commit message (and changelog example) in
5e0b555b453ea2ca36986c111512627d806101e7 talked about sibling classes,
the added test had a child ignore its parent's scoping, which seems less
reasonable.
2016-01-12 05:43:58 +10:30
schneems
4d60e93174 Set environment even when no migration runs
This PR addresses the issue described in https://github.com/rails/rails/pull/22967#issuecomment-170251635. If the database is non empty and has no new migrations than `db:migrate` will not set the environment. This PR works by always setting the environment value on successful `up` migration regardless of whether or not a migration was actually executed.
2016-01-11 11:58:12 -06:00
schneems
a703999c62 Clean up duplicate migration logic 2016-01-11 11:27:32 -06:00
Ryuta Kamizono
560bf1c939 Extract MySQL::TypeMetadata class to connection_adapters/mysql/type_metadata.rb 2016-01-11 05:03:31 +09:00
Ryuta Kamizono
83026cb15d Extract MySQL::Column class to connection_adapters/mysql/column.rb 2016-01-11 04:54:03 +09:00
Kasper Timm Hansen
492d203986 Split out token if tests to trigger before_create.
When running passing condition assertions in the same test the user had already
been saved at that point.

Split out so we have a not yet persisted user.

Rename condition tests to improve clarity a bit.
2016-01-09 23:33:57 +01:00
Kasper Timm Hansen
62abae9172 Add conditional_token to users.
Fix the NoMethodErrors introduced in 224eddf, when adding conditional token creation.

The model declarations but the column wasn't added to the schema.
2016-01-09 22:31:13 +01:00
Griffin Smith
21c0a1f301 Support :if and :unless in has_secure_token
Pass through :if and :unless options from has_secure_token to the
generated before_create callback
2016-01-09 14:49:00 -05:00
Sean Griffin
34ac8a1e98 Merge pull request #22976 from schneems/schneems/schema-migration-primary-key
Get update_attributes working with SchemaMigration
2016-01-08 17:44:26 -07:00
Sean Griffin
302e92359c Refactor tz aware types, add support for PG ranges
This is an alternate implementation to #22875, that generalizes a lot of
the logic that type decorators are going to need, in order to have them
work with arrays, ranges, etc. The types have the ability to map over a
value, with the default implementation being to just yield that given
value. Array and Range give more appropriate definitions.

This does not automatically make ranges time zone aware, as they need to
be added to the `time_zone_aware` types config, but we could certainly
make that change if we feel it is appropriate. I do think this would be
a breaking change however, and should at least have a deprecation cycle.

Closes #22875.

/cc @matthewd
2016-01-08 14:11:45 -07:00
Sean Griffin
c1a1595740 Merge pull request #22967 from schneems/schneems/generic-metadata
Prevent destructive action on production database
2016-01-08 13:42:48 -07:00
schneems
57155064d1 Get update_attributes working with SchemaMigration
You cannot use `update_attributes` on models that do not have a primary key. Since SchemaMigration versions are guaranteed to be unique (they have a unique index on them) we can safely use them as a primary key.
2016-01-08 14:29:31 -06:00
schneems
d70c68d76a Fixing tests and re-locating error checking. 2016-01-08 14:05:20 -06:00
schneems
de2cb20117 Use hash like syntax for InternalMetadata
Discussion: https://github.com/rails/rails/pull/22967#discussion_r49137035
2016-01-08 09:27:25 -06:00
schneems
900bfd94a9 Prevent destructive action on production database
This PR introduces a key/value type store to Active Record that can be used for storing internal values. It is an alternative implementation to #21237 cc @sgrif @matthewd.

It is possible to run your tests against your production database by accident right now. While infrequently, but as an anecdotal data point, Heroku receives a non-trivial number of requests for a database restore due to this happening. In these cases the loss can be large.

To prevent against running tests against production we can store the "environment" version that was used when migrating the database in a new internal table. Before executing tests we can see if the database is a listed in `protected_environments` and abort. There is a manual escape valve to force this check from happening with environment variable `DISABLE_DATABASE_ENVIRONMENT_CHECK=1`.
2016-01-07 18:01:05 -06:00
Lachlan Sylvester
76dc41abdb fix remove_index for postgresql when running legacy migrations 2016-01-06 19:20:11 +11:00
Rafael Mendonça França
059820c09a Merge pull request #21688 from kamipo/add_text_and_blob_shorthand_methods
Add short-hand methods for text and blob types in MySQL
2016-01-06 03:21:14 -02:00
Rafael França
91ceac3728 Merge pull request #22920 from kamipo/fix_connection_create
Fix `connection#create` in PG adapter
2016-01-05 22:39:50 -02:00
Ryuta Kamizono
4d4239f980 Add short-hand methods for text and blob types in MySQL
In Pg and Sqlite3, `:text` and `:binary` have variable unlimited length.
But in MySQL, these have limited length for each types (ref #21591, #21619).
This change adds short-hand methods for each text and blob types.

Example:

    create_table :foos do |t|
      t.tinyblob   :tiny_blob
      t.mediumblob :medium_blob
      t.longblob   :long_blob
      t.tinytext   :tiny_text
      t.mediumtext :medium_text
      t.longtext   :long_text
    end
2016-01-05 10:36:37 +09:00
Ryuta Kamizono
326b12ae52 Fix connection#create in PG adapter
Originally `connection#create` had aliased to `connection#insert` in PG
adapter. But it was broken by #7447. Re-alias `create` to `insert` for
fixing it.
2016-01-05 10:02:29 +09:00
Rafael França
35dd9e9f2a Merge pull request #22896 from kamipo/fix_unsigned_and_blob_or_text_column
Fix `unsigned?` and `blob_or_text_column` for Enum columns in MySQL
2016-01-04 21:14:50 -02:00
Sean Griffin
c2181fbcb7 Merge pull request #22550 from tamird/record-fetch-warning-allocate-less
activerecord: allocate fewer objects
2016-01-04 15:15:55 -07:00
Arthur Nogueira Neves
5ba6999637 Merge pull request #22821 from shosti/set-null-transaction
Allow add_to_transaction with null transaction
2016-01-04 13:37:49 -05:00
Tamir Duberstein
0aa5150f9f activerecord: reuse immutable objects 2016-01-04 12:09:37 -05:00
Ryuta Kamizono
2f373dd916 Fix unsigned? and blob_or_text_column? for Enum columns in MySQL 2016-01-04 14:46:59 +09:00
Ryuta Kamizono
48e2faaa11 Remove FIXME comments about the Arel::Nodes::Quoted [ci skip]
The `Arel::Nodes::Quoted` was removed already.
Follow up to f916aa247bddba0c58c50822886bc29e8556df76.
2016-01-03 00:57:23 +09:00
Fumiaki MATSUSHIMA
2f68456187 Remove unnecessary enable,disable_extension on tests
uuid-ossp extension is alreadly enabled on test schema.
And `disable_extension!('uuid-ossp', connection)` can be a cause of test failure.
`ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  function uuid_generate_v1() does not exist`
will happen depending on the execution order.
2016-01-02 00:30:30 +09:00
Rafael França
f2cd0eaa94 Merge pull request #22105 from morgoth/fix-errors-details-on-autosave-associations
Fixed setting errors details on autosaved associations
2015-12-31 04:18:16 -02:00
Rafael França
3affdc1a35 Merge pull request #22241 from kamipo/add_columns_for_distinct_for_mysql57
Add `columns_for_distinct` for MySQL 5.7 with ONLY_FULL_GROUP_BY
2015-12-30 13:02:14 -02:00
Rafael França
4f8bdfb40f Merge pull request #22447 from kamipo/fix_test_to_null_agnostic_way
Fix `test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct` to NULL-agnostic way
2015-12-30 12:57:44 -02:00
Rafael França
6381d08078 Merge pull request #22803 from kamipo/improve_select_one_in_mysql2_adapter
Improve `select_one` in `Mysql2Adapter`
2015-12-30 00:15:39 -02:00
Emanuel Evans
95254e4f12
Allow add_to_transaction with null transaction
Fixes https://github.com/rails/rails/issues/22819
2015-12-28 14:28:19 -08:00
Yves Senn
0d2675f84f Merge pull request #22053 from Empact/first-loaded
Fix #first(limit) to take advantage of #loaded? records if available
2015-12-28 09:34:35 +01:00
Yves Senn
4b1f67a11a tests, don't connect to mysql when running sqlite3 tests.
This resolves the following error:

```
Error:
TestAdapterWithInvalidConnection#test_inspect_on_Model_class_does_not_raise:
TypeError: superclass mismatch for class Mysql2Adapter
    /Users/senny/Projects/rails/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb:35:in `<module:ConnectionAdapters>'
    /Users/senny/Projects/rails/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb:34:in `<module:ActiveRecord>'
    /Users/senny/Projects/rails/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb:6:in `<top (required)>'
    /Users/senny/Projects/rails/activesupport/lib/active_support/dependencies.rb:302:in `require'
    /Users/senny/Projects/rails/activesupport/lib/active_support/dependencies.rb:302:in `block in require'
    /Users/senny/Projects/rails/activesupport/lib/active_support/dependencies.rb:268:in `load_dependency'
    /Users/senny/Projects/rails/activesupport/lib/active_support/dependencies.rb:302:in `require'
    /Users/senny/Projects/rails/activerecord/lib/active_record/connection_adapters/connection_specification.rb:174:in `spec'
    /Users/senny/Projects/rails/activerecord/lib/active_record/connection_handling.rb:50:in `establish_connection'
    /Users/senny/Projects/rails/activerecord/test/cases/invalid_connection_test.rb:12:in `setup'
```
2015-12-28 09:00:38 +01:00
Ryuta Kamizono
bf79aa4fc1 Improve select_one in Mysql2Adapter
Avoid instanciate `ActiveRecord::Result` and calling
`ActiveRecord::Result#hash_rows` for the performance.
2015-12-27 23:12:41 +09:00
Ben Woosley
b42c3255bf Fix first(limit) to take advantage of loaded? records if available
I realized that `first(2)`, etc. was unnecessarily querying for the
records when they were already preloaded. This was because
`find_nth_with_limit` can not know which `@records` to return because
it conflates the `offset` and `index` into a single variable, while
the `@records` only needs the `index` itself to select the proper
record.

Because `find_nth` and `find_nth_with_limit` are public methods, I
instead introduced a private method `find_nth_with_limit_and_offset`
which is called internally and handles the `loaded?` checking.

Once the `offset` argument is removed from `find_nth`,
`find_nth_with_limit_and_offset` can be collapsed into
`find_nth_with_limit`, with `offset` always equal to `offset_index`.
2015-12-24 09:03:28 -08:00
Ryuta Kamizono
06ba969cf5 Fix varbinary with default ''
A `(?:var)?binary` with default '' is a correct definition.
Remove `missing_default_forged_as_empty_string?` method for fixing this
issue because this method is a workaround for older mysql legacy adapter
(19c99ac, f7015336).
2015-12-24 23:05:17 +09:00
Carl P. Corliss
629efb6057 Fixes LoggerSilence#silence threadsafety
- uses instance defined level if no custom local log level defined
- Keeps track of local log level per [ thread + object-instance ]
- prevents memory leakage by removing local level hash key/value on #silence method exit
- avoids the use of Thread local variables
2015-12-23 12:57:33 -05:00
Ryuta Kamizono
d0be40cad1 Add columns_for_distinct for MySQL 5.7 with ONLY_FULL_GROUP_BY
In MySQL 5.7.5 and up, ONLY_FULL_GROUP_BY affects handling of queries
that use DISTINCT and ORDER BY. It requires the ORDER BY columns in the
select list for distinct queries, and requires that the ORDER BY include
the distinct column.

See https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
2015-12-23 22:47:44 +09:00
Stephen Blackstone
fdb0234434 Add support for passing flags to MySQL2 adapter by array 2015-12-22 02:47:29 -05:00
Yves Senn
b06f6a1d8c Revert "Merge pull request #22486 from methyl/fix-includes-for-groupped-association"
This reverts commit 537ac7d6ade61e95f2b70685ff2236b7de965bab, reversing
changes made to 9c9c54abe08d86967efd3dcac1d65158a0ff74ea.

Reason:
The way we preload associations will change the meaning of GROUP BY
operations. This is illustrated in the SQL generated by the added
test (failing on PG):

Association Load:
D, [2015-12-21T12:26:07.169920 #26969] DEBUG -- :   Post Load (0.7ms)  SELECT "posts".* FROM "posts" LEFT JOIN comments ON comments.post_id = posts.id WHERE "posts"."author_id" = $1 GROUP BY posts.id ORDER BY SUM(comments.tags_count)  [["author_id", 1]]

Preload:
D, [2015-12-21T12:26:07.128305 #26969] DEBUG -- :   Post Load (1.3ms)  SELECT "posts".* FROM "posts" LEFT JOIN comments ON comments.post_id = posts.id WHERE "posts"."author_id" IN (1, 2, 3) GROUP BY posts.id ORDER BY SUM(comments.tags_count)
2015-12-21 12:31:52 +01:00
Yves Senn
537ac7d6ad Merge pull request #22486 from methyl/fix-includes-for-groupped-association
Pass group values when including association

Conflicts:
	activerecord/CHANGELOG.md
2015-12-21 10:10:07 +01:00
Ryuta Kamizono
af9878d640 Remove legacy mysql adapter
Follow up to #22642.
2015-12-21 08:46:55 +09:00
Ryuta Kamizono
d9ca8e20ff Remove unused test/schema/mysql_specific_schema.rb
Follow up to #22642.
2015-12-19 18:05:55 +09:00
Ryuta Kamizono
a093afd8ce Fix test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct to NULL-agnostic way
The sort order of NULL depends on the RDBS implementation. This commit
is to fix the test to NULL-agnostic way.

Example:

    ```
    activerecord_unittest=# SELECT  DISTINCT "posts"."id", author_addresses_authors.id AS alias_0 FROM "posts" LEFT OUTER JOIN "authors" ON "authors"."id" = "posts"."author_id" LEFT OUTER JOIN "author_addresses" ON "author_addresses"."id" = "authors"."author_address_id" LEFT OUTER JOIN "categorizations" ON "categorizations"."category_id" = "posts"."id" LEFT OUTER JOIN "authors" "authors_posts" ON "authors_posts"."id" = "categorizations"."author_id" LEFT OUTER JOIN "author_addresses" "author_addresses_authors" ON "author_addresses_authors"."id" = "authors_posts"."author_address_id" ORDER BY author_addresses_authors.id DESC;
     id | alias_0
    ----+---------
      1 |
      2 |
      3 |
      4 |
      5 |
      6 |
      7 |
      8 |
      9 |
     10 |
     11 |
      1 |       1
    (12 rows)
    ```

    ```
    root@localhost [activerecord_unittest] > SELECT  DISTINCT `posts`.`id`, author_addresses_authors.id AS alias_0 FROM `posts` LEFT OUTER JOIN `authors` ON `authors`.`id` = `posts`.`author_id` LEFT OUTER JOIN `author_addresses` ON `author_addresses`.`id` = `authors`.`author_address_id` LEFT OUTER JOIN `categorizations` ON `categorizations`.`category_id` = `posts`.`id` LEFT OUTER JOIN `authors` `authors_posts` ON `authors_posts`.`id` = `categorizations`.`author_id` LEFT OUTER JOIN `author_addresses` `author_addresses_authors` ON `author_addresses_authors`.`id` = `authors_posts`.`author_address_id` ORDER BY author_addresses_authors.id DESC;
    +----+---------+
    | id | alias_0 |
    +----+---------+
    |  1 |       1 |
    |  3 |    NULL |
    |  1 |    NULL |
    |  2 |    NULL |
    |  4 |    NULL |
    |  5 |    NULL |
    |  6 |    NULL |
    |  7 |    NULL |
    |  8 |    NULL |
    |  9 |    NULL |
    | 10 |    NULL |
    | 11 |    NULL |
    +----+---------+
    12 rows in set (0.00 sec)
    ```
2015-12-19 17:38:42 +09:00
Aaron Patterson
914a45b5fe Merge pull request #19423 from yuroyoro/fix_performance_regression_of_preloading_has_many_through_relation
Fix #12537 performance regression when preloading has_many_through association
2015-12-18 18:46:14 -08:00
Grey Baker
cda0c1f6a7 Handle specified schemas when removing a Postgres index 2015-12-18 10:07:10 +00:00
Matthew Draper
2750b1b417 Merge pull request #22653 from matthewd/find_array_ordered
ActiveRecord::Base#find(array) returning result in the same order as the array passed
2015-12-18 16:42:30 +10:30
Matthew Draper
503255d21b These limits are now implicit 2015-12-18 16:21:21 +10:30
Matthew Draper
04309aee82 Implement limit & offset for ourselves
We know the query will return exactly one row for each entry in the
`ids` array, so we can do all the limit/offset calculations on that
array, in advance.

I also split our new ordered-ids behaviour out of the existing
`find_some` method: especially with this change, the conditionals were
overwhelming the actual logic.
2015-12-18 15:54:04 +10:30
Matthew Draper
e0e918609f Merge pull request #20815 from byroot/do-not-include-column-limit-if-it-is-default
Do not include column limit in schema.rb if it matches the default
2015-12-18 14:52:05 +10:30
Matthew Draper
da6713fd03 Merge pull request #22623 from greysteil/support-passing-schema-name-to-indexes
Support passing the schema name prefix to `conenction.indexes`
2015-12-18 14:17:50 +10:30
Matthew Draper
c316ce9ba4 Merge pull request #19456 from greysteil/index-exists-behaviour
Ignore index name in `index_exists?` when not passed a name to check for
2015-12-18 14:13:46 +10:30