Commit Graph

539 Commits

Author SHA1 Message Date
Ryuta Kamizono 823f9e0a89
Merge pull request #33844 from kamipo/too_many_eager_load_ids
Eager loading/preloading should be worked regardless of large number of records
2018-09-13 21:30:19 +09:00
Yasuo Honda d54d0c9575 Use utf8mb4 character set by default for MySQL database (#33608)
* Use utf8mb4 character set by default

`utf8mb4` character set supports supplementary characters including emoji.
`utf8` character set with 3-Byte encoding is not enough to support them.

There was a downside of 4-Byte length character set with MySQL 5.5 and 5.6:

"ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes"
for Rails string data type which is mapped to varchar(255) type.

MySQL 5.7 supports 3072 byte key prefix length by default.

* Remove `DEFAULT COLLATE` from Active Record unit test databases

There should be no "one size fits all" collation in MySQL 5.7.
Let MySQL server choose the default collation for Active Record
unit test databases.

Users can choose their best collation for their databases
by setting `options[:collation]` based on their requirements.

* InnoDB FULLTEXT indexes support since MySQL 5.6
it does not have to use MyISAM storage engine whose maximum key length is 1000 bytes.
Using MyISAM storag engine with utf8mb4 character set would cause
"Specified key was too long; max key length is 1000 bytes"

https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html

* References

"10.9.1 The utf8mb4 Character Set (4-Byte UTF-8 Unicode Encoding)"
https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb4.html

"10.9.2 The utf8mb3 Character Set (3-Byte UTF-8 Unicode Encoding)"
https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8.html

"14.8.1.7 Limits on InnoDB Tables"
https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html
> If innodb_large_prefix is enabled (the default), the index key prefix limit is 3072 bytes
> for InnoDB tables that use DYNAMIC or COMPRESSED row format.

* CI against MySQL 5.7

Followed this instruction and changed root password to empty string.
https://docs.travis-ci.com/user/database-setup/#MySQL-57

* The recommended minimum version of MySQL is 5.7.9
to support utf8mb4 character set and `innodb_default_row_format`

MySQL 5.7.9 introduces `innodb_default_row_format` to support 3072 byte length index by default.
Users do not have to change MySQL database configuration to support Rails string type.

https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_default_row_format

https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html
> If innodb_large_prefix is enabled (the default),
> the index key prefix limit is 3072 bytes for InnoDB tables that use DYNAMIC or COMPRESSED row format.

* The recommended minimum version of MariaDB is 10.2.2
MariaDB 10.2.2 is the first version of MariaDB supporting `innodb_default_row_format`
Also MariaDB says "MySQL 5.7 is compatible with MariaDB 10.2".

- innodb_default_row_format
https://mariadb.com/kb/en/library/xtradbinnodb-server-system-variables/#innodb_default_row_format

- "MariaDB versus MySQL - Compatibility"
https://mariadb.com/kb/en/library/mariadb-vs-mysql-compatibility/
> MySQL 5.7 is compatible with MariaDB 10.2

- "Supported Character Sets and Collations"
https://mariadb.com/kb/en/library/supported-character-sets-and-collations/
2018-09-11 13:03:34 -07:00
Ryuta Kamizono a50eacb03c Eager loading/preloading should be worked regardless of large number of records
Since 213796f, bind params are used for IN clause if enabled prepared
statements.

Unfortunately, most adapter modules have a limitation for # of bind
params (mysql2 65535, pg 65535, sqlite3 250000). So if eager loading
large number of records at once, that query couldn't be sent to the
database.

Since eager loading/preloading queries are auto-generated by Active
Record itself, so it should be worked regardless of large number of
records like as before.

Fixes #33702.
2018-09-12 01:11:38 +09:00
kenjiszk 15e04b4ef8 add mysql and sqlite3 default test
[Gannon McGibbon + Kenji Suzuki]
2018-09-01 22:09:01 -04:00
Larry Reid 332e7601a9 Fix circular `autosave: true`
Use a variable local to the `save_collection_association` method in
`activerecord/lib/active_record/autosave_association.rb`, instead of an
instance variable.

Prior to this PR, when there was a circular series of `autosave: true`
associations, the callback for a `has_many` association was run while
another instance of the same callback on the same association hadn't
finished running. When control returned to the first instance of the
callback, the instance variable had changed, and subsequent associated
records weren't saved correctly. Specifically, the ID field for the
`belongs_to` corresponding to the `has_many` was `nil`.

Remove unnecessary test and comments.

Fixes #28080.
2018-07-23 14:53:27 -07:00
Ryuta Kamizono 6f58b2cfc9 Enable `Layout/EmptyLinesAroundBlockBody` to reduce review cost in the future
We sometimes ask "✂️ extra blank lines" to a contributor in reviews like
https://github.com/rails/rails/pull/33337#discussion_r201509738.

It is preferable to deal automatically without depending on manpower.
2018-07-12 21:29:48 +09:00
Ryuta Kamizono f7c5a8ce26 Subsecond precision is not supported until MySQL 5.6.4 2018-07-09 04:27:35 +09:00
Nikolay Kondratyev 64078e0886
Fix default value for mysql time types with specified precision
The TIME, DATETIME, and TIMESTAMP types [have supported](https://mariadb.com/kb/en/library/microseconds-in-mariadb/)
a fractional seconds precision from 0 to 6.

Default values from time columns with specified precision is read
as `current_timestamp(n)` from information schema.

rake `db:schema:dump` produces `schema.rb` **without** default values for time columns with the specified precision:

    t.datetime "last_message_at", precision: 6, null: false

rake `db:schema:dump` produces `schema.rb` **with** default values for time columns with the specified precision:

    t.datetime "last_message_at", precision: 6, default: -> { "current_timestamp(6)" }, null: false
2018-07-04 10:45:02 +05:00
Ryuta Kamizono cad0b7d91d Fix `touch` option to behave consistently with `Persistence#touch` method
`touch` option was added to `increment!` (#27660) and `update_counters`
(#26995). But that option behaves inconsistently with
`Persistence#touch` method.

If `touch` option is passed attribute names, it won't update
update_at/on attributes unlike `Persistence#touch` method.

Due to changed from `Persistence#touch` to `increment!` with `touch`
option, #31405 has a regression that `counter_cache` with `touch` option
which is passed attribute names won't update update_at/on attributes.

I think that the inconsistency is not intended. To get back consistency,
ensure that `touch` option updates update_at/on attributes.
2018-06-18 19:08:41 +09:00
Yukio Mizuta e0bc5b4da1 Update prefix and allow suffix options for store accessors 2018-06-12 07:10:09 -07:00
Ryuta Kamizono f2151c3b3c Using existing models for building multiple has_one through tests
Follow up of #32514.
2018-04-22 04:16:44 +09:00
Sam DeCesare 99910dddf2 Fix .new with multiple through associations
This fixes a bug with building an object that has multiple
`has_many :through` associations through the same object.
Previously, when building the object via .new, the intermediate
object would be created instead of just being built.

Here's an example:
Given a GameBoard, that has_one Owner and Collection through Game.
The following line would cause a game object to be created in the
database.

    GameBoard.new(owner: some_owner, collection: some_collection)

Whereas, if passing only one of those associations into `.new` would
cause the Game object to be built and not created in the database.

Now the above code will only build the Game object, and not save it.
2018-04-09 18:49:52 -07:00
Rafael França 3c1a8ee7d7
Merge pull request #30956 from CJStadler/with-lock-changed-deprecation
Fix deprecation warnings from with_lock
2018-03-28 13:11:01 -04:00
Tan Huynh 3f297be72b Add custom prefix to ActiveRecord::Store accessors
Add a prefix option to ActiveRecord::Store.store_accessor and
ActiveRecord::Store.store. This option allows stores to have identical keys
with different accessors.
2018-03-23 08:01:46 +07:00
fatkodima 471bec310d Fix multiline expression indexes for postgresql (#31621) 2018-03-16 01:19:40 -04:00
bogdanvlviv ce03e7d991
Fix occurrences Fixnum|Bignum
Related to d4eb0dc89e (r27830891)
2018-03-04 20:44:30 +02:00
Ryuta Kamizono fb86ecd604 Make `reflection.klass` raise if `polymorphic?` not to be misused
This is an alternative of #31877 to fix #31876 caused by #28808.

This issue was caused by a combination of several loose implementation.

* finding automatic inverse association of polymorphic without context (caused by #28808)
* returning `klass` even if `polymorphic?` (exists before #28808)
* loose verification by `valid_inverse_reflection?` (exists before #28808)

This makes `klass` raise if `polymorphic?` not to be misused.
This issue will not happen unless polymorphic `klass` is misused.

Fixes #31876.
Closes #31877.
2018-02-19 00:11:29 +09:00
Eugene Kenny 3e71bc4b04 Don't update counter cache when through record was not destroyed
When removing a record from a has many through association, the counter
cache was being updated even if the through record halted the callback
chain and prevented itself from being destroyed.
2018-01-14 20:46:19 +00:00
bogdanvlviv 6ddba9b46c
Fix conflicts `counter_cache` with `touch: true` by optimistic locking.
```
  # create_table :posts do |t|
  #   t.integer :comments_count, default: 0
  #   t.integer :lock_version
  #   t.timestamps
  # end
  class Post < ApplicationRecord
  end

  # create_table :comments do |t|
  #   t.belongs_to :post
  # end
  class Comment < ApplicationRecord
    belongs_to :post, touch: true, counter_cache: true
  end
  ```

  Before:
  ```
  post = Post.create!
  # => begin transaction
       INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
       VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
       commit transaction

  comment = Comment.create!(post: post)
  # => begin transaction
       INSERT INTO "comments" ("post_id") VALUES (1)

       UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1,
       "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1

       UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330',
       "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0
       rollback transaction
  # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post.

  Comment.take.destroy!
  # => begin transaction
       DELETE FROM "comments" WHERE "comments"."id" = 1

       UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1,
       "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1

       UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901',
       "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0
       rollback transaction
  # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post.
  ```

  After:
  ```
  post = Post.create!
  # => begin transaction
       INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
       VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
       commit transaction

  comment = Comment.create!(post: post)
  # => begin transaction
       INSERT INTO "comments" ("post_id") VALUES (1)

       UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1,
       "lock_version" = COALESCE("lock_version", 0) + 1,
       "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1
       commit transaction

  comment.destroy!
  # => begin transaction
       DELETE FROM "comments" WHERE "comments"."id" = 1

       UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1,
       "lock_version" = COALESCE("lock_version", 0) + 1,
       "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1
       commit transaction
  ```

  Fixes #31199.
2017-12-12 00:32:50 +02:00
Ryuta Kamizono 01fb0907b2 Refactor `length`, `order`, and `opclass` index options dumping 2017-12-03 05:01:41 +09:00
Ryuta Kamizono e3a2956646 Ensure `apply_join_dependency` for `collection_cache_key` if eager-loading is needed
Fixes #30315.
2017-11-06 03:34:15 +09:00
Ryuta Kamizono a516dfd4b4 Fix CI failure due to reference type mismatch
`Firm.id` is a bigint if mysql2 adapter is used, but `firm_id` is an
integer. It will cause an out of range error.

https://travis-ci.org/rails/rails/jobs/264112814#L776
https://travis-ci.org/rails/rails/jobs/264112835#L919
2017-08-14 17:27:54 +09:00
Ryuta Kamizono 8f5e888617 Specify `table.name` only when `scope.table` and `table` are different (#29058)
Fixes #29045.
2017-08-11 14:37:43 -04:00
Kir Shatrov 831be98f9a Use frozen-string-literal in ActiveRecord 2017-07-19 22:27:07 +03:00
Ryuta Kamizono d13f54d50a Fix unscoping `default_scope` in STI associations
Since 5c71000, it has lost to be able to unscope `default_scope` in STI
associations. This change will use `.empty_scope?` instead of
`.values.empty?` to regard as an empty scope if only have
`type_condition`.
2017-07-19 00:50:40 +09:00
Matthew Draper 87b3e226d6 Revert "Merge pull request #29540 from kirs/rubocop-frozen-string"
This reverts commit 3420a14590, reversing
changes made to afb66a5a59.
2017-07-02 02:15:17 +09:30
Kir Shatrov cfade1ec7e Enforce frozen string in Rubocop 2017-07-01 02:11:03 +03:00
Ryuta Kamizono bf3f201000 Fix `ids_reader` to respect case sensitive primary key
```ruby
  car = Car.create!(name: "Tofaş")

  # Before
  car.bulb_ids # => SELECT "bulbs".ID FROM "bulbs" WHERE "bulbs"."name" = $1 AND "bulbs"."car_id" = $2  [["name", "defaulty"], ["car_id", 3]]

  # After
  car.bulb_ids # => SELECT "bulbs"."ID" FROM "bulbs" WHERE "bulbs"."name" = $1 AND "bulbs"."car_id" = $2  [["name", "defaulty"], ["car_id", 3]]
```
2017-06-28 21:59:28 +09:00
Ryuta Kamizono 135437cbb6 Ensure that using correct alias tracker
Covering #27994 in tests.

Closes #27994.
2017-06-25 21:55:38 +09:00
bogdanvlviv 4d1264cb5a
Fix ActiveRecord::Persistence#touch with locking
`ActiveRecord::Persistence#touch` does not work well when optimistic
locking enabled and `locking_column`, without default value, is null in
the database.
2017-06-21 00:46:23 +03:00
Ryuta Kamizono 5409e5e31b Use nullable `id` column instead of a primary key
`id` column in `subscribers` was added as a primary key for ignorable in
INSERT. But it caused `NotNullViolation` for oracle-enhanced adapter.

https://github.com/rsim/oracle-enhanced/issues/1357

I changed the column to nullable to address the issue.
2017-06-16 09:47:57 +09:00
Ryuta Kamizono 9b8c7796a9 Avoid overwriting the methods of `AttributeMethods::PrimaryKey`
Currently the methods of `AttributeMethods::PrimaryKey` are overwritten
by `define_attribute_methods`. It will be broken if a table that
customized primary key has non primary key id column.
It should not be overwritten if a table has any primary key.

Fixes #29350.
2017-06-07 11:11:08 +09:00
Isaac Betesh b17fa0c353
Don't attempt to create a new record that was already created.
Fixes #24032
2017-04-20 19:45:58 -04:00
Matthew Draper 7384771dd0 Use a query that's compatible with PostgreSQL 9.2
Also, explicitly apply the order: generate_subscripts is unlikely to
start returning values out of order, but we should still be clear about
what we want.
2017-04-12 23:38:57 +09:30
Ryuta Kamizono 505526335b Correctly dump native timestamp types for MySQL
The native timestamp type in MySQL is different from datetime type.
Internal representation of the timestamp type is UNIX time, This means
that timestamp columns are affected by time zone.

```
> SET time_zone = '+00:00';
Query OK, 0 rows affected (0.00 sec)

> INSERT INTO time_with_zone(ts,dt) VALUES (NOW(),NOW());
Query OK, 1 row affected (0.02 sec)

> SELECT * FROM time_with_zone;
+---------------------+---------------------+
| ts                  | dt                  |
+---------------------+---------------------+
| 2016-02-07 22:11:44 | 2016-02-07 22:11:44 |
+---------------------+---------------------+
1 row in set (0.00 sec)

> SET time_zone = '-08:00';
Query OK, 0 rows affected (0.00 sec)

> SELECT * FROM time_with_zone;
+---------------------+---------------------+
| ts                  | dt                  |
+---------------------+---------------------+
| 2016-02-07 14:11:44 | 2016-02-07 22:11:44 |
+---------------------+---------------------+
1 row in set (0.00 sec)
```
2017-02-23 12:51:49 +09:00
Rafael Mendonça França b9bee5e895
Fix rubocop violations 2017-02-13 14:00:05 -03:00
Ryuta Kamizono 6d37cd918d Omit redundant `using: :btree` for schema dumping 2017-02-13 23:12:04 +09:00
Ryuta Kamizono c6b4b4a52c
Schema dumping support for PostgreSQL oid type
Closes #27980
2017-02-12 20:00:08 -07:00
Ryuta Kamizono 42ed16a987
Schema dumping support for PostgreSQL interval type
Closes #27979
2017-02-12 19:52:58 -07:00
namusyaka 3df9117abc Fix inspection behavior when the :id column is not primary key 2017-02-09 01:57:50 +09:00
Ryuta Kamizono 14db455156 `primary_key` and `references` columns should be identical type
Follow up to #26266.

The default type of `primary_key` and `references` were changed to
`bigint` since #26266. But legacy migration and sqlite3 adapter should
keep its previous behavior.
2017-02-07 14:21:18 +09:00
Ryuta Kamizono 111ccc832b Chain scope constraints should respect own table alias
Fixes #27666.
2017-02-01 06:27:23 +09:00
Ryuta Kamizono 24f264e9ca SQLite: Foreign Key Support
https://www.sqlite.org/foreignkeys.html
2017-01-17 08:20:10 +09:00
Ryuta Kamizono b0923e4ca2 Should work foreign key in test schema without `if supports_foreign_keys?` statement
If an adapter does not support foreign key feature, should be noop.

https://github.com/rails/rails/blob/v5.0.0.rc1/activerecord/test/cases/migration/foreign_key_test.rb#L288-L294
https://github.com/rails/rails/blob/v5.0.0.rc1/activerecord/test/cases/migration/references_foreign_key_test.rb#L208-L214
2017-01-17 08:19:38 +09:00
Ryuta Kamizono 9abf606a79 Should not update children when the parent creation with no reason
This issue was introduced with d849f42 to solve #19782. However, we can
solve #19782 without causing the issue. It is enough to save only when
necessary.

Fixes #27338.
2016-12-29 16:24:57 +09:00
Julia Lopez 5e46f4ccb4 fix #create_fixtures when equal table names in different databases 2016-12-21 11:09:29 +01:00
Pavel Pravosud 3e452b1204 Make pg adapter use bigserial for pk by default 2016-12-05 11:40:32 -08:00
Jon McCartie b92ae61069 Change MySQL and Postgresql to use Bigint primary keys 2016-12-05 11:34:35 -08:00
Yaw Boakye b915b11cca
For `PostgreSQL >= 9.4` use `gen_random_uuid()`
Since 9.4, PostgreSQL recommends using `pgcrypto`'s `gen_random_uuid()`
to generate version 4 UUIDs instead of the functions in the `uuid-ossp`
extension.

These changes uses the appropriate UUID function depending on the
underlying PostgreSQL server's version, while maintaining
`uuid_generate_v4()` in older migrations.
2016-11-22 22:11:18 +00:00
yui-knk 4360ecf7df Remove a confusing comment
These comment sometimes explain a face which does not match
the face.
2016-10-31 10:27:01 +09:00
yui-knk 7808a90990 Fix the order of `create_table` to match a comment about `:inverse_of` options
In ActiveRecord test :men, :faces, :interests and :zines tables are
used for `:inverse_of` test cases, not `:wheels`.
2016-10-31 10:26:09 +09:00
bogdanvlviv 22a822e581 Fixed: Optimistic locking does not work well with null in the database 2016-10-21 19:06:02 +03:00
Ryuta Kamizono 5025fd3a99 Dump index options to pretty format
```ruby
  # Before
  t.index ["firm_id", "type", "rating"], name: "company_index", order: {"rating"=>:desc}, using: :btree

  # After
  t.index ["firm_id", "type", "rating"], name: "company_index", order: { rating: :desc }, using: :btree
```
2016-10-10 11:53:22 +09:00
Yosuke Kabuto 6009107caf Add tests for ActiveRecord::Enum#enum when suffix specified
Make name of attribute medium instead of normal
2016-09-12 08:52:02 +09:00
Rafael Mendonça França 55f9b8129a
Add three new rubocop rules
Style/SpaceBeforeBlockBraces
Style/SpaceInsideBlockBraces
Style/SpaceInsideHashLiteralBraces

Fix all violations in the repository.
2016-08-16 04:30:11 -03:00
Xavier Noria 9617db2078 applies new string literal convention in activerecord/test
The current code base is not uniform. After some discussion,
we have chosen to go with double quotes by default.
2016-08-06 18:26:53 +02:00
Rafael França 70ec7feaec Merge pull request #25767 from kamipo/association_name_is_the_same_as_join_table_name
Correctly return `associated_table` when `associated_with?` is true
2016-07-27 23:23:05 -03:00
Xavier Noria 99cf755800 systematic revision of =~ usage in AR
Where appropriatei, prefer the more concise Regexp#match?,
String#include?, String#start_with?, or String#end_with?
2016-07-23 20:22:20 +02:00
Ryuta Kamizono b7d229d1fa Correctly return `associated_table` when `associated_with?` is true
`AssociationQueryHandler` requires `association` initialized
`TableMetadata` even if `table_name == arel_table.name`.

Fixes #25689.
2016-07-10 11:42:51 +09:00
Ryuta Kamizono 7b7b7c5ce6 Extract foreign key action from `information_schema`
Fixes #25300.
2016-06-07 06:26:49 +09:00
Ryuta Kamizono edc2b77187
Add Expression Indexes and Operator Classes support for PostgreSQL
Example:

    create_table :users do |t|
      t.string :name
      t.index 'lower(name) varchar_pattern_ops'
    end

Fixes #19090.
Fixes #21765.
Fixes #21819.
Fixes #24359.

Signed-off-by: Jeremy Daer <jeremydaer@gmail.com>
2016-04-24 14:56:29 -07:00
Ryuta Kamizono a80e944e18 Remove unused `table_with_autoincrement` table 2016-04-19 17:17:19 +09:00
Ladislav Smola cb4f6875b6 Fix undefined method `owners' for NullPreloader:Class
* Fix undefined method `owners' for NullPreloader:Class

Fixing undefined method `owners' for
ActiveRecord::Associations::Preloader::NullPreloader:Class

* Use Ruby 1.9 hash format

Use Ruby 1.9 hash format

#24192

[Rafael Mendonça França + Ladislav Smola]
2016-04-06 00:46:55 -03:00
Ryuta Kamizono 3b910de771 Remove `except` helper for test schema 2016-03-30 06:49:04 +09:00
Rafael França eefcc78f7a Merge pull request #23797 from kamipo/case_sensitive_comparison_for_non_string_column
The BINARY Operator is only needed for string columns
2016-03-11 19:10:29 -03:00
Mehmet Emin İNAÇ 0784dccc4f Execute default_scope defined by abstract class within the scope of subclass 2016-03-08 14:56:00 +02:00
Sean Griffin 96c1ada82d Merge pull request #23628 from maclover7/fix-23625
Fix issue #23625
2016-02-23 12:24:07 -07: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
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
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
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 d0054b4908 Fix `bigint?` for Enum columns in MySQL
Follow up to #22896.
2016-01-31 01:07:02 +09:00
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
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
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
Kasper Timm Hansen 1aa1cec777 Revert "Merge pull request #20835 from glittershark/if-and-unless-in-secure-token"
This reverts commit 224eddfc0e, reversing
changes made to 9d681fc74c.

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
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
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
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 2f373dd916 Fix `unsigned?` and `blob_or_text_column?` for Enum columns in MySQL 2016-01-04 14:46:59 +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
Yves Senn 0f82f661b7 tests, pluralize singular table name.
This solves the following error:

     ActiveRecord::StatementInvalid: Could not find table 'guitars'

It seems that the table structure of the `Guitar` model has not been
necessary until now. Due to the wrong table name the model was not
correctly linked to the table.
2015-12-02 16:02:01 +01:00
yui-knk 817c1825c1 Except keys of `build_record`'s argument from `create_scope` in initialize_attributes
If argument of `build_record` has key and value which is same as
default value of database, we should also except the key from
`create_scope` in `initialize_attributes`.
Because at first `build_record` initialize record object with argument
of `build_record`, then assign attributes derived from Association's scope.
In this case `record.changed` does not include the key, which value is
same as default value of database, so we should add the key to except list.

Fix #21893.
2015-11-16 23:15:45 +09:00
Sean Griffin f7d0a3ba7e Merge pull request #18548 from sebjacobs/support-bidirectional-destroy-dependencies
Add support for bidirectional destroy dependencies
2015-10-28 12:24:07 -06:00
Sean Griffin 118232aef4 Merge pull request #19686 from tsun1215/index_errors
Errors can be indexed with nested attributes

Close #8638
2015-10-26 16:05:16 -06:00
Sean Griffin 5c32f41d52 Fix merge conflicts for #19938
This is a separate commit, as it is not just a changelog conflict. Want
to point out the changes in the code
2015-10-20 16:57:47 -06:00
Sean Griffin 72fba7db41 Merge pull request #21932 from kamipo/add_stored_procedure_test_in_mysql2
Add stored procedure test in mysql2
2015-10-20 14:02:23 -06:00
Ryuta Kamizono d39b6f77fc Add stored procedure test in mysql2 2015-10-15 13:18:21 +09:00
Ryuta Kamizono f8438ae336 Fix to correctly schema dump the `tinyblob`
Currently `tinyblob` is dumped to `t.binary "tiny_blob", limit: 255`.
But `t.binary ... limit: 255` is generating SQL to `varchar(255)`.
It is incorrect. This commit fixes this problem.
2015-10-15 05:38:43 +09:00
eileencodes ee824c8858 Fix regression in inverse_of on through associations
`inverse_of` on through associations was accidently removed/caused to
stop working in commit f8d2899 which was part of a refactoring on
`ThroughReflection`.

To fix we moved `inverse_of` and `check_validity_of_inverse!` to the
`AbstractReflection` so it's available to the `ThroughReflection`
without having to dup any methods. We then need to delegate `inverse_name`
method in `ThroughReflection`. `inverse_name` can't be moved to
`AbstractReflection` without moving methods that set the instance
variable `@automatic_inverse_of`.

This adds a test that ensures that `inverse_of` on a `ThroughReflection`
returns the correct class name, and the correct record for the inverse
relationship.

Fixes #21692
2015-09-26 16:26:56 -04:00
Jean Boussier 4ccdd4122d Implement ActiveRecord::Base.ignored_columns 2015-09-24 11:04:44 -04:00
Sean Griffin 2c7d0d42ac 0 precision is not the same as no precision
And we are passing them as separate types in the query, which means 0
precision is still not supported by older versions of MySQL. I also
missed a handful of other cases where they need to be conditionally
applied.
2015-09-23 09:15:59 -06:00
Sean Griffin f696494aed Don't attempt to specify datetime precision unless supported
Specifically, versions of MySQL prior to 5.6 do not support this, which
is what's used on Travis by default. The method `mysql_56?` appeared to
only ever be used to conditionally apply subsecond precision, so I've
generalized it and used it more liberally.

This should fix the test failures caused by #20317
2015-09-23 09:09:50 -06:00
Bogdan Gusiev d03f519665 Fixed taking precision into count when assigning a value to timestamp attribute
Timestamp column can have less precision than ruby timestamp
In result in how big a fraction of a second can be stored in the
database.

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

If the precision is low enough, (mysql default is 0, so it is always low
enough by default) the value changes when model is reloaded from the
database. This patch fixes that issue ensuring that any timestamp
assigned as an attribute is converted to column precision under the
attribute.
2015-09-23 13:29:08 +03:00
Sean Griffin 9cc324a3f1 Ensure aliased attributes passed to `select` are quoted if using `from`
Fixes #21488

[Sean Griffin & johanlunds]
2015-09-21 11:14:32 -06:00
Akira Matsuda c971bc0568 ✂️ empty line at the top of files 2015-09-21 01:27:33 +09:00
Agis- 19b168e611 Only nullify persisted has_one target associations
Since after 87d1aba3c `dependent: :destroy` callbacks on has_one
assocations run *after* destroy, it is possible that a nullification is
attempted on an already destroyed target:

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

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

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

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

Fixes #21223.
2015-08-24 11:49:43 +03:00
Rafael Mendonça França 0168ce10a3 Merge pull request #19683 from tristang/require-option-for-counter-cache
Require explicit counter_cache option for has_many
2015-08-13 17:51:07 -03:00
Rafael Mendonça França dc3230b156 Skip statement cache on through association reader
If the through class has default scopes we should skip the statement
cache.

Closes #20745.
2015-08-12 21:17:30 -03:00
Matt Hanlon 5ec9e9349e use correct DB connection for generated HABTM table 2015-08-07 12:33:09 -07:00
Stefan Kanev 0ed096ddf5 Fix counter_cache for polymorphic associations
Also removes a false positive test that depends on the fixed bug:

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

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

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

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

Fixes #20874.
2015-07-18 10:30:58 -04:00
David Heinemeier Hansson 5f5e6d9249 Add pending test for the great-grandparent touching bug from #19324 2015-06-25 14:23:06 +02:00
Igor Kapkov 09bef7684a Add enum prefix/suffix option to enum definition
Fixes #17511 and #17415
2015-06-12 12:07:55 +08:00
Sean Griffin 5b35562d8e Correctly handle array columns with defaults in the schema dumper
If the subtype provides custom schema dumping behavior, we need to defer
to it. We purposely choose not to handle any values other than an array
(which technically should only ever be `nil`, but I'd rather code
defensively here).

Fixes #20515.
2015-06-11 16:50:25 -06:00
Victor Costan 2b2f41fd97 Fix crash when loading fixture with belongs_to association defined in abstract base class. 2015-06-04 12:38:00 -04:00
Mehmet Emin İNAÇ df94dabb37 Fix for activerecord join dependency instantiate bug
use only object_id instead parent class and parent id

test cases

assert_equal

use table name in references

fix minor problems
2015-05-04 18:06:06 +03:00
Ryuta Kamizono 6c8ec48ba3 Move PostgreSQL specific schema to postgresql_specific_schema.rb 2015-05-03 21:13:13 +09:00
Michael Probber 21e448b5a5 Errors can be indexed with nested attributes
`has_many` can now take `index_errors: true` as an
option.  When this is enabled, errors for nested models will be
returned alongside an index, as opposed to just the nested model name.
This option can also be enabled (or disabled) globally through
`ActiveRecord::Base.index_nested_attribute_errors`

E.X.

```ruby
class Guitar < ActiveRecord::Base
  has_many :tuning_pegs
  accepts_nested_attributes_for :tuning_pegs
end

class TuningPeg < ActiveRecord::Base
  belongs_to :guitar
  validates_numericality_of :pitch
end
```

 - Old style
 - `guitar.errors["tuning_pegs.pitch"] = ["is not a number"]`

 - New style (if defined globally, or set in has_many_relationship)
 - `guitar.errors["tuning_pegs[1].pitch"] = ["is not a number"]`

[Michael Probber, Terence Sun]
2015-04-17 14:11:16 -04:00
Tristan Gamilis 5435230451 Add tests for associations without counter_cache
Assert that counter_cache behaviour is not used on belongs_to or
has_many associations if the option is not given explicitly.
2015-04-09 14:53:34 +10:00
Jeremy Kemper bd51bbc028 Merge pull request #17574 from kamipo/charset_collation_options
Add charset and collation options support for MySQL string and text columns.
2015-04-07 09:40:16 -07:00
wallerjake 9bc4eb7ee1 Delegate limit to subtype
As described here https://github.com/rails/rails/issues/19420. When
using the Postgres BigInt[] field type the big int value was not being
translated into schema.rb. This caused the field to become just a
regular integer field when building off of schema.rb. This fix will
address this by delegating the limit from the subtype to the Array type.

https://github.com/rails/rails/issues/19420
2015-03-21 19:32:41 -05:00
eileencodes 51660f0191 Fix leaky chain on polymorphic association
If there was a polymorphic hm:t association with a scope AND second
non-scoped hm:t association on a model the polymorphic scope would leak
through into the call for the non-polymorhic hm:t association.

This would only break if `hotel.drink_designers` was called before
`hotel.recipes`. If `hotel.recipes` was called first there would be
no problem with the SQL.

Before (employable_type should not be here):
```
SELECT COUNT(*) FROM "drink_designers" INNER JOIN "chefs" ON
"drink_designers"."id" = "chefs"."employable_id" INNER JOIN
"departments" ON "chefs"."department_id" = "departments"."id" WHERE
"departments"."hotel_id" = ? AND "chefs"."employable_type" = ?
[["hotel_id", 1], ["employable_type", "DrinkDesigner"]]
```

After:
```
SELECT COUNT(*) FROM "recipes" INNER JOIN "chefs" ON "recipes"."chef_id"
= "chefs"."id" INNER JOIN "departments" ON "chefs"."department_id" =
"departments"."id" WHERE "departments"."hotel_id" = ?  [["hotel_id", 1]]
```

From the SQL you can see that `employable_type` was leaking through when
calling recipes. The solution is to dup the chain of the polymorphic
association so it doesn't get cached. Additionally, this follows
`scope_chain` which dup's the `source_reflection`'s `scope_chain`.

This required another model/table/relationship because the leak only
happens on a hm:t polymorphic that's called before another hm:t on the
same model.

I am specifically testing the SQL here instead of the number of records
becasue the test could pass if there was 1 drink designer recipe for the
drink designer chef even though the `employable_type` was leaking through.
This needs to specifically check that `employable_type` is not in the SQL
statement.
2015-03-15 10:39:42 -04:00
Ryuta Kamizono 0aa83f3b88 Add `:charset` and `:collation` options support for MySQL string and text columns
Example:

    create_table :foos do |t|
      t.string :string_utf8_bin, charset: 'utf8', collation: 'utf8_bin'
      t.text   :text_ascii,      charset: 'ascii'
    end
2015-03-06 18:56:19 +09:00
Yves Senn 3f4964299a tests, favor `drop_table` and `:if_exists` over raw SQL.
We've replaced most querues using DROP TABLE in our tests already.
This patch replaces the last couple calls.
2015-03-02 17:43:01 +01:00
Rafael Mendonça França 5c5d9417ca Merge pull request #17297 from rebyn/fix/17161-remove-objs-from-has_many-updates-fields
Add specs for adding-to/clear has_many collections’s behavior on `updated_at`
2015-02-25 19:59:31 -03:00
Ryuta Kamizono 531063543b Remove unused table
`postgresql_xml_data_type` table is used from nowhere.
2015-02-25 01:19:59 +09:00
Michael Ryan b9a1e9a4b2 Add `ActiveRecord::Base.suppress` 2015-02-18 18:30:05 -05:00
Ryuta Kamizono af64c82411 Prefer `drop_table if_exists: true` over raw SQL
Lowercase raw SQL has been replaced by 07b659c already. This commit
replaces everything else of raw SQL.
2015-02-18 20:58:45 +09:00
Vipul A M 6eced6a1fe Removed magic comments # encoding: utf-8 , since its default from ruby 2.0 onwards. 2015-02-03 20:51:40 +05:30
Aaron Patterson c79220368e Merge pull request #18512 from vipulnsward/18492-fixtures-with-sti
Fix STI for fixtures from multi-files
2015-01-31 18:03:45 -08:00
Sean Griffin 56a3d5ec91 Don't redefine autosave association callbacks in nested attrs
These callbacks will already have been defined when the association was
built. The check against `reflection.autosave` happens at call time, not
at define time, so simply modifying the reflection is sufficient.

Fixes #18704
2015-01-28 09:53:38 -07:00
Seb Jacobs d5bf649a53 Add support for bidirectional destroy dependencies
Prior to this commit if you defined a bidirectional relationship
between two models with destroy dependencies on both sides, a call to
`destroy` would result in an infinite callback loop.

Take the following relationship.

    class Content < ActiveRecord::Base
      has_one :content_position, dependent: :destroy
    end

    class ContentPosition < ActiveRecord::Base
      belongs_to :content, dependent: :destroy
    end

Calling `Content#destroy` or `ContentPosition#destroy` would result in
an infinite callback loop.

This commit changes the behaviour of `ActiveRecord::Callbacks#destroy`
so that it guards against subsequent callbacks.

Thanks to @zetter for demonstrating the issue with failing tests[1].

[1] rails#13609
2015-01-16 11:41:43 +00:00
Vipul A M 4ae59ebee8 Fixes #18492
- Add check for not deleting previously created fixtures, to overcome sti fixtures from multiple files
- Added fixtures and fixtures test to verify the same

- Fixed wrong fixtures duplicating data insertion in same table
2015-01-14 21:36:58 +05:30
Ray Zane ac41f6a5d7 Add firebird support to test suite 2015-01-05 13:34:59 -03:00
robertomiranda 5a58ba3366 Add has_secure_token to Active Record
Update SecureToken Docs

Add Changelog entry for has_secure_token [ci skip]
2015-01-04 11:31:37 -05:00
Ryuta Kamizono ae419af666 Allow precision option for MySQL datetimes. 2015-01-02 22:30:07 +09:00
Ulisses Almeida + Kassio Borges 075c81feec Add foreign_type option for polymorphic has_one and has_many.
To be possible to use a custom column name to save/read the polymorphic
associated type in a has_many or has_one polymorphic association, now users
can use the option :foreign_type to inform in what column the associated object
type will be saved.
2014-12-08 18:13:15 -02:00
Yves Senn 780269c732 pg tests, get rid of global schema `schema_1`. 2014-12-02 12:08:52 +01:00
Yves Senn 90e396ce65 pg tests, move uniqueness validation test to array tests. 2014-12-02 11:53:18 +01:00
Yves Senn b8ec014b2d tests, extract pg number tests into separate file. 2014-12-02 11:46:08 +01:00
Yves Senn af7c6e493c tests, move schema shorthand assertions into pg specific tests. 2014-12-02 11:35:53 +01:00
Yves Senn bcf5b281a8 tests, move pg geometric tests out of `base_test`. 2014-12-02 11:00:19 +01:00
Yves Senn bec9e83359 tests, favor public API over inspecting columns where possible.
This is a follow up to 07786c5e75
and cd2596f55e
2014-12-01 16:57:48 +01:00
Sammy Larbi f43f56e16e Ensure HABTM relationships produce valid class names (Fixes #17119) 2014-11-09 11:56:07 -06:00
Ted O'Meara 9007b789e1 Added SchemaDumper support for tables with jsonb columns. 2014-11-04 12:55:07 -05:00
Sean Griffin 10f75af933 Use bind values for joined tables in where statements
In practical terms, this allows serialized columns and tz aware columns
to be used in wheres that go through joins, where they previously would
not behave correctly. Internally, this removes 1/3 of the cases where we
rely on Arel to perform type casting for us.

There were two non-obvious changes required for this. `update_all` on
relation was merging its bind values with arel's in the wrong order.
Additionally, through associations were assuming there would be no bind
parameters in the preloader (presumably because the where would always
be part of a join)

[Melanie Gilman & Sean Griffin]
2014-11-01 15:39:51 -06:00
Tu Hoang 9f48e75ad7 Add specs for adding-to/clear has_many collections’s behavior on `updated_at`
There are behaviors mentioned in #17161 that:

1. are not documented properly, and
2. don't have specs

This commit addresses the spec absence. For has_many collections,

1. addition (<<) should update the associated object's updated_at (if any)
2. .clear, depending on options[:dependent], calls delete_all, destroy_all, or nullifies the associated object(s)' foreign key.
2014-10-30 22:25:01 +07:00
Sean Griffin 21f081c0ca 💣
We were relying on hash inequality in tests
2014-10-28 17:43:58 -06:00
Akira Matsuda da2f61947d Dynamically modified schema and association would not be correctly reset
This fixes <"SQLite3::SQLException: no such column: legacy_things.person_id: SELECT \"legacy_things\".* FROM \"legacy_things\" WHERE \"legacy_things\".\"person_id\" = ?">
in OptimisticLockingTest#test_lock_destroy
2014-09-06 23:28:18 +09:00
Abdelkader Boudih 0ab9301f2a Added enable_extension! to helper 2014-09-05 21:20:17 +00:00
Agis- 431f8e0119 Only merge scopes with zero arity in has_many through
with dynamic conditions.

Fixes #16128

This bug was introduced in c35e438620
so it's present from 4.1.2-rc1 and after.

c35e438620
merges any relation scopes passed as proc objects to the relation,
but does *not* take into account the arity of the lambda.

To reproduce: https://gist.github.com/Agis-/5f1f0d664d2cd08dfb9b
2014-08-20 08:25:58 +03:00
Sean Griffin ea3ba34506 Change the default `null` value for timestamps
As per discussion, this changes the model generators to specify
`null: false` for timestamp columns. A warning is now emitted if
`timestamps` is called without a `null` option specified, so we can
safely change the behavior when no option is specified in Rails 5.
2014-08-12 14:40:11 -06:00
Yves Senn 3eca062160 use foreign key DSL in our tests. 2014-07-16 10:06:55 +02:00
Yasuo Honda fc46804258 Address ORA-00972: identifier is too long when tested with Oracle
by using shorter attribute names.
2014-07-14 21:54:17 +09:00
Godfrey Chan 6787507883 Re-enable foriegn key tests on MySQL
This reverts commit e84799d, e31104c and e6ca8e2
2014-07-05 11:50:55 -07:00
Philippe Creux e31104c102 MySQL doesn't work with foreign keys
This was previously fixed in e84799d but broken in 3f596f8. This commit
reintroduced the conditional that prevents the foreign keys from being
added to MySQL databases.
2014-06-27 17:36:43 -07:00
Philippe Creux 0418633919 Fix test with add_foreign_key DSL in 9d21ef9 2014-06-27 15:38:45 -07:00
Rafael Mendonça França 3f596f8ad3 Do not change the global state of the test suite 2014-06-27 17:32:38 -03:00
Yves Senn 8768305f20 fk: use random digest names
The name of the foreign key is not relevant from a users perspective.
Using random names resolves the urge to rename the foreign key when the
respective table or column is renamed.
2014-06-26 22:03:49 +02:00
Sean Griffin d730e374ca Deprecate automatic counter caches on has_many :through
Reliant on https://github.com/rails/rails/pull/15747 but pulled to a
separate PR to reduce noise. `has_many :through` associations have the
undocumented behavior of automatically detecting counter caches.
However, the way in which it does so is inconsistent with counter caches
everywhere else, and doesn't actually work consistently.

As with normal `has_many` associations, the user should specify the
counter cache on the `belongs_to`, if they'd like it updated.
2014-06-26 07:24:34 -06:00
Rafael Mendonça França 76d6ec2a9a Fix has_and_belongs_to_many in a namespaced model pointing to a non namespaced model
Now the following case will work fine

    class Tag < ActiveRecord::Base
    end

    class Publisher::Article < ActiveRecord::Base
      has_and_belongs_to_many :tags
    end

Fixes #15761
2014-06-19 14:59:48 -03:00
Rafael Mendonça França 4c0a1021e5 Merge pull request #15343 from dontfidget/fix_polymorphic_automatic_inverse_of
prevent bad automatic inverse_of association
2014-06-13 18:19:18 -03:00
Andrew S. Brown 9feadc11a7 use name specified by 'as' for automatic inverse association to avoid reflecting on wrong association 2014-06-10 21:46:12 -07:00
Rafael Mendonça França dddbccb25a Timestamp values should be present on callbacks
This reverts commit dd3ea17191 and add a
regression test.

Fixes #15418
2014-06-09 17:27:32 -03:00
Yves Senn 9e86428d23 pg, preserve money type when dumping schema and extract money default. 2014-06-03 17:54:25 +02:00
Yves Senn 51f247107f test pg, move bit string type tests into `bit_string_test.rb`. 2014-06-03 16:02:18 +02:00
Sean Griffin 5aa1f5d399 Allow specifying a default value in overloaded properties 2014-05-30 08:51:58 -07:00
Sean Griffin 65c33009ba Add a public API to allow users to specify column types
As a result of all of the refactoring that's been done, it's now
possible for us to define a public API to allow users to specify
behavior. This is an initial implementation so that I can work off of it
in smaller pieces for additional features/refactorings.

The current behavior will continue to stay the same, though I'd like to
refactor towards the automatic schema detection being built off of this
API, and add the ability to opt out of automatic schema detection.

Use cases:

- We can deprecate a lot of the edge cases around types, now that there
  is an alternate path for users who wish to maintain the same behavior.
- I intend to refactor serialized columns to be built on top of this
  API.
- Gem and library maintainers are able to interact with `ActiveRecord`
  at a slightly lower level in a more stable way.
- Interesting ability to reverse the work flow of adding to the schema.
  Model can become the single source of truth for the structure. We can
  compare that to what the database says the schema is, diff them, and
  generate a migration.
2014-05-26 15:26:38 -07:00
Godfrey Chan 2d73f5ae2f Fixed serialization for records with an attribute named `format`.
* * *

This bug can be triggered when serializing record R (the instance) of type C
(the class), provided that the following conditions are met:

1. The name of one or more columns/attributes on C/R matches an existing private
   method on C (e.g. those defined by `Kernel`, such as `format`).

2. The attribute methods have not yet been generated on C.

In this case, the matching private methods will be called by the serialization
code (with no arguments) and their return values will be serialized instead. If
the method requires one or more arguments, it will result in an `ArgumentError`.

This regression is introduced in d1316bb.

* * *

Attribute methods (e.g. `#name` and `#format`, assuming the class has columns
named `name` and `format` in its database table) are lazily defined. Instead of
defining them when a the class is defined (e.g. in the `inherited` hook on
`ActiveRecord::Base`), this operation is deferred until they are first accessed.

The reason behind this is that is defining those methods requires knowing what
columns are defined on the database table, which usually requires a round-trip
to the database. Deferring their definition until the last-possible moment helps
reducing unnessary work, especially in development mode where classes are
redefined and throw away between requests.

Typically, when an attribute is first accessed (e.g. `a_book.format`), it will
fire the `method_missing` hook on the class, which triggers the definition of
the attribute methods. This even works for methods like `format`, because
calling a private method with an explicit receiver will also trigger that hook.

Unfortunately, `read_attribute_for_serialization` is simply an alias to `send`,
which does not respect method visibility. As a result, when serializing a record
with those conflicting attributes, the `method_missing` is not fired, and as a
result the attribute methods are not defined one would expected.

Before d1316bb, this is negated by the fact that calling the `run_callbacks`
method will also trigger a call to `respond_to?`, which is another trigger point
for the class to define its attribute methods. Therefore, when Active Record
tries to run the `after_find` callbacks, it will also define all the attribute
methods thus masking the problem.

* * *

The proper fix for this problem is probably to restrict `read_attribute_for_serialization`
to call public methods only (i.e. alias `read_attribute_for_serialization` to
`public_send` instead of `send`). This however would be quite risky to change
in a patch release and would probably require a full deprecation cycle.

Another approach would be to override `read_attribute_for_serialization` inside
Active Record to force the definition of attribute methods:

   def read_attribute_for_serialization(attribute)
     self.class.define_attribute_methods
     send(attribute)
   end

Unfortunately, this is quite likely going to cause a performance degradation.

This patch therefore restores the behaviour from the 4-0-stable branch by
explicitly forcing the class to define its attribute methods in a similar spot
(when records are initialized). This should not cause any extra roundtrips to
the database because the `@columns` should already be cached on the class.

Fixes #15188.
2014-05-22 14:35:04 -07:00
Rafael Mendonça França 6931bed1b4 Revert "Merge pull request #14544 from jefflai2/named_scope_sti"
This reverts commit 9a1abedcde, reversing
changes made to c72d6c91a7.

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/models/comment.rb

This change break integration with activerecord-deprecated_finders so
I'm reverting until we find a way to make it work with this gem.
2014-05-21 12:15:57 -03:00
Lauro Caetano 4debc86bd3 Fix polymorphic eager load with foreign_key as String.
The foreign_key could be `String` and just doing `owners_map[owner_key]`
could return `nil`.
To prevent this bug, we should `to_s` both keys if their types are
different.

Fixes #14734.
2014-05-20 23:26:51 -03:00
Rafael Mendonça França 9a1abedcde Merge pull request #14544 from jefflai2/named_scope_sti
Fixes Issue #13466.

Conflicts:
	activerecord/CHANGELOG.md
2014-05-20 21:35:58 -03:00
Sean Griffin 8df8334327 Remove dead test code for unsupported adapters 2014-05-17 13:24:25 -06:00
Kassio Borges 8f6e5986ac Fix how to compute class name on habtm namespaced.
Thank's for @laurocaetano for the help with tests. 😃

Fixes #14709
2014-05-13 11:26:46 -03:00
Jefferson Lai 9c3afdc327 Fixes Issue #13466.
Changed the call to a scope block to be evaluated with instance_eval.
The result is that ScopeRegistry can use the actual class instead of base_class when
caching scopes so queries made by classes with a common ancestor won't leak scopes.
2014-04-23 17:21:45 -07:00
Rafael Mendonça França 085ce4f141 Merge branch 'master' into rm-uuid-fixtures
Conflicts:
	activerecord/CHANGELOG.md
	activesupport/CHANGELOG.md
2014-04-10 15:34:55 -03:00
Rafael Mendonça França 8d1c703727 Merge pull request #14579 from senny/pg/remove_string_limit
PostgreSQL, remove varchar limit.

Conflicts:
	activerecord/CHANGELOG.md
2014-04-04 19:51:35 -03:00
Rafael Mendonça França 57c7d5cb80 Fix the test defining the models in the right place 2014-04-04 19:44:17 -03:00
Rafael Mendonça França 54d8c81fef Merge pull request #12016 from roderickvd/uuid_fixes
Auto-generate stable fixture UUIDs on PostgreSQL

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/lib/active_record/fixtures.rb
	activerecord/test/cases/adapters/postgresql/uuid_test.rb
	activesupport/CHANGELOG.md
2014-04-04 12:52:49 -03:00
Yves Senn f4226c3ab6 PostgreSQL and SQLite, remove varchar limit. [Vladimir Sazhin & Toms Mikoss & Yves Senn]
There is no reason for the PG adapter to have a default limit of 255 on :string
columns. See this snippet from the PG docs:

    Tip: There is no performance difference among these three types, apart
    from increased storage space when using the blank-padded type, and a
    few extra CPU cycles to check the length when storing into a
    length-constrained column. While character(n) has performance
    advantages in some other database systems, there is no such advantage
    in PostgreSQL; in fact character(n) is usually the slowest of the
    three because of its additional storage costs. In most situations text
    or character varying should be used instead.
2014-04-04 10:35:26 +02:00
Lauro Caetano db5d26c9d7 Fix error when using `with_options` with lambda.
It was causing error when using `with_options` passing a lambda as its
last argument.

    class User < ActiveRecord::Base
      with_options dependent: :destroy do |assoc|
        assoc.has_many :profiles, -> { where(active: true) }
      end
    end

It was happening because the `option_merger` was taking the last
argument and checking if it was a Hash. This breaks the HasMany usage,
because its last argument can be a Hash or a Proc.

As the behavior described in this test:
https://github.com/rails/rails/blob/master/activesupport/test/option_merger_test.rb#L69
the method will only accept the lambda, this way it will keep the expected behavior. See 9eaa0a34
2014-04-03 10:26:37 -03:00
Arthur Neves 5a934e6787
Test microsecond on mysql 5.6 2014-03-12 09:06:12 -04:00
lsylvester b3e0da3062 register OID for PostgreSQL citex datatype [Troy Kruthoff & Lachlan Sylvester]
citext makes it possible to use AR Hash finders for case-insensitive matching as sql UPPER/LOWER functions are not needed.
2014-03-11 08:14:03 +11:00
Godfrey Chan 41554319f8 Fixed STI classes not defining an attribute method if there is a
conflicting private method defined on its ancestors.

The problem is that `method_defined_within?(name, klass, superklass)`
only works correclty when `klass` and `superklass` are both `Class`es.

If both `klass` and `superklass` are both `Class`es, they share the
same inheritance chain, so if a method is defined on `klass` but not
`superklass`, this method must be introduced at some point between
`klass` and `superklass`.

This does not work when `superklass` is a `Module`. A `Module`'s
inheritance chain contains just itself. So if a method is defined on
`klass` but not on `superklass`, the method could still be defined
somewhere upstream, e.g. in `Object`.

This fix works by avoiding calling `method_defined_within?` with a
module while still fufilling the requirement (checking that the
method is defined withing `superclass` but not is not a generated
attribute method).

4d8ee288 is likely an attempted partial fix for this problem. This
unrolls that fix and properly check the `superclass` as intended.

Fixes #11569.
2014-02-23 11:00:55 -08:00
Rafael Mendonça França a0520fceff Add more tests for the dirty feature for enums 2014-01-21 12:45:58 -02: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
Roderick van Domburg 9330631888 Auto-generate stable fixture UUIDs on PostgreSQL.
Fixes: #11524
2014-01-07 19:05:50 +01: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
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
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
Yves Senn c4044b2f8a extract PG range tests from datatype_test.rb into range_test.rb 2013-12-13 14:17:21 +01:00
Lauro Caetano 23ce3e5fde Prevent invalid code when using dynamic finders with Ruby's reserved words.
The dynamic finder was creating the method signature with the parameters name,
which may have reserved words and this way creating invalid Ruby code.

Closes: #13261

    Example:

        # Before
        Dog.find_by_alias('dog name')

        # Was creating this method
        def self.find_by_alias(alias, options = {})

        # After
        Dog.find_by_alias('dog name')

        # Will create this method
        def self.find_by_alias(_alias, options = {})
2013-12-11 01:00:32 -02:00
Yasuo Honda 75bb2bbebb Do not create synonym named subjects
because it is only used in
`activerecord/test/cases/adapters/oracle/synonym_test.rb`

See rails/rails#13054
2013-11-27 23:43:51 +01:00
Pablo Torres 6f788b1d91 Use 1.9 Hash syntax consistently 2013-11-05 08:13:37 -05:00
Carlos Antonio da Silva 28dea539e1 Convert schema file to ruby 1.9 style hash 2013-11-04 13:32:17 -02:00
Carlos Antonio da Silva a7f3c6944d Style fixes on test schema file 2013-11-04 13:32:17 -02:00
Yury Korolev 7caa09c5e1 Explicit mapping for enum 2013-11-02 17:48:16 -07:00
David Heinemeier Hansson db41eb8a6e Added ActiveRecord::Base#enum for declaring enum attributes where the values map to integers in the database, but can be queried by name 2013-11-02 12:01:31 -07:00
Neeraj Singh cd9592959f scope_chain should not be mutated for other reflections
Currently `scope_chain` uses same array for building different
`scope_chain` for different associations. During processing
these arrays are sometimes mutated and because of in-place
mutation the changed `scope_chain` impacts other reflections.

Fix is to dup the value before adding to the `scope_chain`.

Fixes #3882.
2013-10-14 11:59:59 -04:00
Vipul A M 1457589301 Remove sqlite specific`supports_autoincrement?` which always defaults to true 2013-08-10 22:21:25 +05:30
Rafael Mendonça França 48e3c462a2 Use the proper encoding comment on the file 2013-08-06 10:37:50 -03:00
Aaron Patterson 904bfad00d adding a weird test case 2013-08-06 20:58:27 +09:00
Takehiro Adachi 0123c39f41 Add test to AR's counter_cache_test.rb
According to
https://github.com/rails/rails/blob/b601399b72ab56cc01368f02615af99f45d1
4f02/activerecord/lib/active_record/counter_cache.rb#L14, u can pass
more then one association to the `reset_counters` method.
2013-05-18 17:12:46 +09:00
Erik Peterson 661365e7ce Correctly parse bigint defaults in PostgreSQL 2013-04-05 09:37:08 -04:00
masarakki eab657b267 fix detect column type of enum
enum includes text or blob or ... hooked by wrong regex
2013-04-01 17:09:20 +09:00
Ken Mazaika 9600e0b029 Add support for FULLTEXT and SPATIAL indexes using the :type flag for MySQL. 2013-03-27 23:35:54 -04:00
Ken Mazaika a89e9f70b2 Dump the 'using' options for a SQL index into the schema. 2013-03-27 22:38:53 -04:00
Ian Young 66679c8ecd Update other counter caches on destroy 2013-03-20 13:43:07 -07:00