activerecord 4.2.0 → 5.0.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of activerecord might be problematic. Click here for more details.

Files changed (249) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +1537 -789
  3. data/MIT-LICENSE +2 -2
  4. data/README.rdoc +7 -8
  5. data/examples/performance.rb +2 -3
  6. data/examples/simple.rb +0 -1
  7. data/lib/active_record/aggregations.rb +37 -23
  8. data/lib/active_record/association_relation.rb +16 -3
  9. data/lib/active_record/associations/alias_tracker.rb +19 -16
  10. data/lib/active_record/associations/association.rb +23 -9
  11. data/lib/active_record/associations/association_scope.rb +74 -102
  12. data/lib/active_record/associations/belongs_to_association.rb +26 -29
  13. data/lib/active_record/associations/builder/association.rb +28 -34
  14. data/lib/active_record/associations/builder/belongs_to.rb +43 -18
  15. data/lib/active_record/associations/builder/collection_association.rb +12 -20
  16. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +22 -15
  17. data/lib/active_record/associations/builder/has_many.rb +4 -4
  18. data/lib/active_record/associations/builder/has_one.rb +11 -6
  19. data/lib/active_record/associations/builder/singular_association.rb +3 -10
  20. data/lib/active_record/associations/collection_association.rb +61 -33
  21. data/lib/active_record/associations/collection_proxy.rb +81 -35
  22. data/lib/active_record/associations/foreign_association.rb +11 -0
  23. data/lib/active_record/associations/has_many_association.rb +21 -57
  24. data/lib/active_record/associations/has_many_through_association.rb +15 -45
  25. data/lib/active_record/associations/has_one_association.rb +13 -5
  26. data/lib/active_record/associations/join_dependency/join_association.rb +20 -8
  27. data/lib/active_record/associations/join_dependency.rb +37 -21
  28. data/lib/active_record/associations/preloader/association.rb +51 -53
  29. data/lib/active_record/associations/preloader/collection_association.rb +0 -6
  30. data/lib/active_record/associations/preloader/has_many_through.rb +1 -1
  31. data/lib/active_record/associations/preloader/has_one.rb +0 -8
  32. data/lib/active_record/associations/preloader/through_association.rb +27 -14
  33. data/lib/active_record/associations/preloader.rb +18 -8
  34. data/lib/active_record/associations/singular_association.rb +8 -8
  35. data/lib/active_record/associations/through_association.rb +22 -9
  36. data/lib/active_record/associations.rb +321 -212
  37. data/lib/active_record/attribute/user_provided_default.rb +28 -0
  38. data/lib/active_record/attribute.rb +79 -15
  39. data/lib/active_record/attribute_assignment.rb +20 -141
  40. data/lib/active_record/attribute_decorators.rb +6 -5
  41. data/lib/active_record/attribute_methods/before_type_cast.rb +6 -1
  42. data/lib/active_record/attribute_methods/dirty.rb +51 -81
  43. data/lib/active_record/attribute_methods/primary_key.rb +2 -2
  44. data/lib/active_record/attribute_methods/query.rb +2 -2
  45. data/lib/active_record/attribute_methods/read.rb +31 -59
  46. data/lib/active_record/attribute_methods/serialization.rb +13 -16
  47. data/lib/active_record/attribute_methods/time_zone_conversion.rb +65 -14
  48. data/lib/active_record/attribute_methods/write.rb +14 -38
  49. data/lib/active_record/attribute_methods.rb +70 -45
  50. data/lib/active_record/attribute_mutation_tracker.rb +70 -0
  51. data/lib/active_record/attribute_set/builder.rb +37 -15
  52. data/lib/active_record/attribute_set.rb +34 -3
  53. data/lib/active_record/attributes.rb +199 -73
  54. data/lib/active_record/autosave_association.rb +73 -25
  55. data/lib/active_record/base.rb +35 -27
  56. data/lib/active_record/callbacks.rb +39 -43
  57. data/lib/active_record/coders/json.rb +1 -1
  58. data/lib/active_record/coders/yaml_column.rb +20 -8
  59. data/lib/active_record/collection_cache_key.rb +40 -0
  60. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +457 -181
  61. data/lib/active_record/connection_adapters/abstract/database_limits.rb +3 -3
  62. data/lib/active_record/connection_adapters/abstract/database_statements.rb +83 -59
  63. data/lib/active_record/connection_adapters/abstract/query_cache.rb +3 -3
  64. data/lib/active_record/connection_adapters/abstract/quoting.rb +74 -9
  65. data/lib/active_record/connection_adapters/abstract/savepoints.rb +4 -4
  66. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +61 -39
  67. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +246 -185
  68. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +72 -17
  69. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +438 -136
  70. data/lib/active_record/connection_adapters/abstract/transaction.rb +53 -40
  71. data/lib/active_record/connection_adapters/abstract_adapter.rb +166 -66
  72. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +429 -335
  73. data/lib/active_record/connection_adapters/column.rb +28 -43
  74. data/lib/active_record/connection_adapters/connection_specification.rb +15 -27
  75. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +22 -0
  76. data/lib/active_record/connection_adapters/mysql/column.rb +50 -0
  77. data/lib/active_record/connection_adapters/mysql/database_statements.rb +125 -0
  78. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +70 -0
  79. data/lib/active_record/connection_adapters/mysql/quoting.rb +51 -0
  80. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +67 -0
  81. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +93 -0
  82. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +54 -0
  83. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +32 -0
  84. data/lib/active_record/connection_adapters/mysql2_adapter.rb +26 -177
  85. data/lib/active_record/connection_adapters/postgresql/column.rb +5 -10
  86. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +11 -73
  87. data/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +42 -0
  88. data/lib/active_record/connection_adapters/postgresql/oid/array.rb +27 -56
  89. data/lib/active_record/connection_adapters/postgresql/oid/bit.rb +2 -2
  90. data/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +2 -1
  91. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +3 -1
  92. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +7 -13
  93. data/lib/active_record/connection_adapters/postgresql/oid/enum.rb +3 -1
  94. data/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +3 -3
  95. data/lib/active_record/connection_adapters/postgresql/oid/json.rb +1 -26
  96. data/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +2 -2
  97. data/lib/active_record/connection_adapters/postgresql/oid/money.rb +0 -4
  98. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +4 -4
  99. data/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb +50 -0
  100. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +31 -17
  101. data/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +17 -5
  102. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +2 -2
  103. data/lib/active_record/connection_adapters/postgresql/oid/vector.rb +1 -1
  104. data/lib/active_record/connection_adapters/postgresql/oid/xml.rb +1 -1
  105. data/lib/active_record/connection_adapters/postgresql/oid.rb +1 -6
  106. data/lib/active_record/connection_adapters/postgresql/quoting.rb +26 -18
  107. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +29 -10
  108. data/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +107 -79
  109. data/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +47 -0
  110. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +248 -154
  111. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +35 -0
  112. data/lib/active_record/connection_adapters/postgresql_adapter.rb +258 -170
  113. data/lib/active_record/connection_adapters/schema_cache.rb +36 -23
  114. data/lib/active_record/connection_adapters/sql_type_metadata.rb +32 -0
  115. data/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +19 -0
  116. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +48 -0
  117. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +22 -0
  118. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +150 -209
  119. data/lib/active_record/connection_adapters/statement_pool.rb +31 -12
  120. data/lib/active_record/connection_handling.rb +38 -15
  121. data/lib/active_record/core.rb +109 -114
  122. data/lib/active_record/counter_cache.rb +14 -25
  123. data/lib/active_record/dynamic_matchers.rb +1 -20
  124. data/lib/active_record/enum.rb +115 -79
  125. data/lib/active_record/errors.rb +88 -48
  126. data/lib/active_record/explain_registry.rb +1 -1
  127. data/lib/active_record/explain_subscriber.rb +2 -2
  128. data/lib/active_record/fixture_set/file.rb +26 -5
  129. data/lib/active_record/fixtures.rb +84 -46
  130. data/lib/active_record/gem_version.rb +2 -2
  131. data/lib/active_record/inheritance.rb +32 -40
  132. data/lib/active_record/integration.rb +4 -4
  133. data/lib/active_record/internal_metadata.rb +56 -0
  134. data/lib/active_record/legacy_yaml_adapter.rb +46 -0
  135. data/lib/active_record/locale/en.yml +3 -2
  136. data/lib/active_record/locking/optimistic.rb +27 -25
  137. data/lib/active_record/locking/pessimistic.rb +1 -1
  138. data/lib/active_record/log_subscriber.rb +43 -21
  139. data/lib/active_record/migration/command_recorder.rb +59 -18
  140. data/lib/active_record/migration/compatibility.rb +126 -0
  141. data/lib/active_record/migration.rb +372 -114
  142. data/lib/active_record/model_schema.rb +128 -38
  143. data/lib/active_record/nested_attributes.rb +71 -32
  144. data/lib/active_record/no_touching.rb +1 -1
  145. data/lib/active_record/null_relation.rb +16 -8
  146. data/lib/active_record/persistence.rb +124 -80
  147. data/lib/active_record/query_cache.rb +15 -18
  148. data/lib/active_record/querying.rb +10 -9
  149. data/lib/active_record/railtie.rb +28 -19
  150. data/lib/active_record/railties/controller_runtime.rb +1 -1
  151. data/lib/active_record/railties/databases.rake +67 -51
  152. data/lib/active_record/readonly_attributes.rb +1 -1
  153. data/lib/active_record/reflection.rb +318 -139
  154. data/lib/active_record/relation/batches/batch_enumerator.rb +67 -0
  155. data/lib/active_record/relation/batches.rb +139 -34
  156. data/lib/active_record/relation/calculations.rb +80 -102
  157. data/lib/active_record/relation/delegation.rb +7 -20
  158. data/lib/active_record/relation/finder_methods.rb +167 -97
  159. data/lib/active_record/relation/from_clause.rb +32 -0
  160. data/lib/active_record/relation/merger.rb +38 -41
  161. data/lib/active_record/relation/predicate_builder/array_handler.rb +12 -16
  162. data/lib/active_record/relation/predicate_builder/association_query_handler.rb +88 -0
  163. data/lib/active_record/relation/predicate_builder/base_handler.rb +17 -0
  164. data/lib/active_record/relation/predicate_builder/basic_object_handler.rb +17 -0
  165. data/lib/active_record/relation/predicate_builder/class_handler.rb +27 -0
  166. data/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb +57 -0
  167. data/lib/active_record/relation/predicate_builder/range_handler.rb +33 -0
  168. data/lib/active_record/relation/predicate_builder/relation_handler.rb +1 -1
  169. data/lib/active_record/relation/predicate_builder.rb +124 -82
  170. data/lib/active_record/relation/query_attribute.rb +19 -0
  171. data/lib/active_record/relation/query_methods.rb +323 -257
  172. data/lib/active_record/relation/record_fetch_warning.rb +49 -0
  173. data/lib/active_record/relation/spawn_methods.rb +11 -10
  174. data/lib/active_record/relation/where_clause.rb +174 -0
  175. data/lib/active_record/relation/where_clause_factory.rb +38 -0
  176. data/lib/active_record/relation.rb +176 -115
  177. data/lib/active_record/result.rb +4 -3
  178. data/lib/active_record/runtime_registry.rb +1 -1
  179. data/lib/active_record/sanitization.rb +95 -66
  180. data/lib/active_record/schema.rb +26 -22
  181. data/lib/active_record/schema_dumper.rb +62 -38
  182. data/lib/active_record/schema_migration.rb +11 -17
  183. data/lib/active_record/scoping/default.rb +24 -9
  184. data/lib/active_record/scoping/named.rb +49 -28
  185. data/lib/active_record/scoping.rb +32 -15
  186. data/lib/active_record/secure_token.rb +38 -0
  187. data/lib/active_record/serialization.rb +2 -4
  188. data/lib/active_record/statement_cache.rb +16 -14
  189. data/lib/active_record/store.rb +8 -3
  190. data/lib/active_record/suppressor.rb +58 -0
  191. data/lib/active_record/table_metadata.rb +68 -0
  192. data/lib/active_record/tasks/database_tasks.rb +59 -42
  193. data/lib/active_record/tasks/mysql_database_tasks.rb +32 -26
  194. data/lib/active_record/tasks/postgresql_database_tasks.rb +29 -9
  195. data/lib/active_record/tasks/sqlite_database_tasks.rb +5 -1
  196. data/lib/active_record/timestamp.rb +20 -9
  197. data/lib/active_record/touch_later.rb +58 -0
  198. data/lib/active_record/transactions.rb +159 -67
  199. data/lib/active_record/type/adapter_specific_registry.rb +130 -0
  200. data/lib/active_record/type/date.rb +2 -41
  201. data/lib/active_record/type/date_time.rb +2 -38
  202. data/lib/active_record/type/hash_lookup_type_map.rb +8 -2
  203. data/lib/active_record/type/internal/abstract_json.rb +29 -0
  204. data/lib/active_record/type/internal/timezone.rb +15 -0
  205. data/lib/active_record/type/serialized.rb +21 -14
  206. data/lib/active_record/type/time.rb +10 -16
  207. data/lib/active_record/type/type_map.rb +4 -4
  208. data/lib/active_record/type.rb +66 -17
  209. data/lib/active_record/type_caster/connection.rb +29 -0
  210. data/lib/active_record/type_caster/map.rb +19 -0
  211. data/lib/active_record/type_caster.rb +7 -0
  212. data/lib/active_record/validations/absence.rb +23 -0
  213. data/lib/active_record/validations/associated.rb +10 -3
  214. data/lib/active_record/validations/length.rb +24 -0
  215. data/lib/active_record/validations/presence.rb +11 -12
  216. data/lib/active_record/validations/uniqueness.rb +29 -18
  217. data/lib/active_record/validations.rb +33 -32
  218. data/lib/active_record.rb +9 -2
  219. data/lib/rails/generators/active_record/migration/migration_generator.rb +7 -4
  220. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +8 -6
  221. data/lib/rails/generators/active_record/migration/templates/migration.rb +8 -7
  222. data/lib/rails/generators/active_record/migration.rb +7 -0
  223. data/lib/rails/generators/active_record/model/model_generator.rb +32 -15
  224. data/lib/rails/generators/active_record/model/templates/application_record.rb +5 -0
  225. data/lib/rails/generators/active_record/model/templates/model.rb +3 -0
  226. metadata +60 -34
  227. data/lib/active_record/connection_adapters/mysql_adapter.rb +0 -491
  228. data/lib/active_record/connection_adapters/postgresql/array_parser.rb +0 -93
  229. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +0 -11
  230. data/lib/active_record/connection_adapters/postgresql/oid/float.rb +0 -21
  231. data/lib/active_record/connection_adapters/postgresql/oid/infinity.rb +0 -13
  232. data/lib/active_record/connection_adapters/postgresql/oid/integer.rb +0 -11
  233. data/lib/active_record/connection_adapters/postgresql/oid/time.rb +0 -11
  234. data/lib/active_record/serializers/xml_serializer.rb +0 -193
  235. data/lib/active_record/type/big_integer.rb +0 -13
  236. data/lib/active_record/type/binary.rb +0 -50
  237. data/lib/active_record/type/boolean.rb +0 -30
  238. data/lib/active_record/type/decimal.rb +0 -40
  239. data/lib/active_record/type/decimal_without_scale.rb +0 -11
  240. data/lib/active_record/type/decorator.rb +0 -14
  241. data/lib/active_record/type/float.rb +0 -19
  242. data/lib/active_record/type/integer.rb +0 -55
  243. data/lib/active_record/type/mutable.rb +0 -16
  244. data/lib/active_record/type/numeric.rb +0 -36
  245. data/lib/active_record/type/string.rb +0 -36
  246. data/lib/active_record/type/text.rb +0 -11
  247. data/lib/active_record/type/time_value.rb +0 -38
  248. data/lib/active_record/type/unsigned_integer.rb +0 -15
  249. data/lib/active_record/type/value.rb +0 -101
@@ -4,32 +4,23 @@ module ActiveRecord
4
4
  extend ActiveSupport::Concern
5
5
  #:nodoc:
6
6
  ACTIONS = [:create, :destroy, :update]
7
- #:nodoc:
8
- CALLBACK_WARN_MESSAGE = "Currently, Active Record suppresses errors raised " \
9
- "within `after_rollback`/`after_commit` callbacks and only print them to " \
10
- "the logs. In the next version, these errors will no longer be suppressed. " \
11
- "Instead, the errors will propagate normally just like in other Active " \
12
- "Record callbacks.\n" \
13
- "\n" \
14
- "You can opt into the new behavior and remove this warning by setting:\n" \
15
- "\n" \
16
- " config.active_record.raise_in_transactional_callbacks = true\n\n"
17
7
 
18
8
  included do
19
9
  define_callbacks :commit, :rollback,
20
- terminator: ->(_, result) { result == false },
10
+ :before_commit,
11
+ :before_commit_without_transaction_enrollment,
12
+ :commit_without_transaction_enrollment,
13
+ :rollback_without_transaction_enrollment,
14
+ terminator: deprecated_false_terminator,
21
15
  scope: [:kind, :name]
22
-
23
- mattr_accessor :raise_in_transactional_callbacks, instance_writer: false
24
- self.raise_in_transactional_callbacks = false
25
16
  end
26
17
 
27
18
  # = Active Record Transactions
28
19
  #
29
- # Transactions are protective blocks where SQL statements are only permanent
20
+ # \Transactions are protective blocks where SQL statements are only permanent
30
21
  # if they can all succeed as one atomic action. The classic example is a
31
22
  # transfer between two accounts where you can only have a deposit if the
32
- # withdrawal succeeded and vice versa. Transactions enforce the integrity of
23
+ # withdrawal succeeded and vice versa. \Transactions enforce the integrity of
33
24
  # the database and guard the data against program errors or database
34
25
  # break-downs. So basically you should use transaction blocks whenever you
35
26
  # have a number of statements that must be executed together or not at all.
@@ -49,20 +40,20 @@ module ActiveRecord
49
40
  #
50
41
  # == Different Active Record classes in a single transaction
51
42
  #
52
- # Though the transaction class method is called on some Active Record class,
43
+ # Though the #transaction class method is called on some Active Record class,
53
44
  # the objects within the transaction block need not all be instances of
54
45
  # that class. This is because transactions are per-database connection, not
55
46
  # per-model.
56
47
  #
57
48
  # In this example a +balance+ record is transactionally saved even
58
- # though +transaction+ is called on the +Account+ class:
49
+ # though #transaction is called on the +Account+ class:
59
50
  #
60
51
  # Account.transaction do
61
52
  # balance.save!
62
53
  # account.save!
63
54
  # end
64
55
  #
65
- # The +transaction+ method is also available as a model instance method.
56
+ # The #transaction method is also available as a model instance method.
66
57
  # For example, you can also do this:
67
58
  #
68
59
  # balance.transaction do
@@ -89,7 +80,8 @@ module ActiveRecord
89
80
  #
90
81
  # == +save+ and +destroy+ are automatically wrapped in a transaction
91
82
  #
92
- # Both +save+ and +destroy+ come wrapped in a transaction that ensures
83
+ # Both {#save}[rdoc-ref:Persistence#save] and
84
+ # {#destroy}[rdoc-ref:Persistence#destroy] come wrapped in a transaction that ensures
93
85
  # that whatever you do in validations or callbacks will happen under its
94
86
  # protected cover. So you can use validations to check for values that
95
87
  # the transaction depends on or you can raise exceptions in the callbacks
@@ -98,7 +90,7 @@ module ActiveRecord
98
90
  # As a consequence changes to the database are not seen outside your connection
99
91
  # until the operation is complete. For example, if you try to update the index
100
92
  # of a search engine in +after_save+ the indexer won't see the updated record.
101
- # The +after_commit+ callback is the only one that is triggered once the update
93
+ # The #after_commit callback is the only one that is triggered once the update
102
94
  # is committed. See below.
103
95
  #
104
96
  # == Exception handling and rolling back
@@ -107,11 +99,11 @@ module ActiveRecord
107
99
  # be propagated (after triggering the ROLLBACK), so you should be ready to
108
100
  # catch those in your application code.
109
101
  #
110
- # One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
102
+ # One exception is the ActiveRecord::Rollback exception, which will trigger
111
103
  # a ROLLBACK when raised, but not be re-raised by the transaction block.
112
104
  #
113
- # *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
114
- # inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
105
+ # *Warning*: one should not catch ActiveRecord::StatementInvalid exceptions
106
+ # inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an
115
107
  # error occurred at the database level, for example when a unique constraint
116
108
  # is violated. On some database systems, such as PostgreSQL, database errors
117
109
  # inside a transaction cause the entire transaction to become unusable
@@ -137,11 +129,11 @@ module ActiveRecord
137
129
  # end
138
130
  #
139
131
  # One should restart the entire transaction if an
140
- # <tt>ActiveRecord::StatementInvalid</tt> occurred.
132
+ # ActiveRecord::StatementInvalid occurred.
141
133
  #
142
134
  # == Nested transactions
143
135
  #
144
- # +transaction+ calls can be nested. By default, this makes all database
136
+ # #transaction calls can be nested. By default, this makes all database
145
137
  # statements in the nested transaction block become part of the parent
146
138
  # transaction. For example, the following behavior may be surprising:
147
139
  #
@@ -153,7 +145,7 @@ module ActiveRecord
153
145
  # end
154
146
  # end
155
147
  #
156
- # creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
148
+ # creates both "Kotori" and "Nemu". Reason is the ActiveRecord::Rollback
157
149
  # exception in the nested block does not issue a ROLLBACK. Since these exceptions
158
150
  # are captured in transaction blocks, the parent block does not see it and the
159
151
  # real transaction is committed.
@@ -177,22 +169,22 @@ module ActiveRecord
177
169
  # writing, the only database that we're aware of that supports true nested
178
170
  # transactions, is MS-SQL. Because of this, Active Record emulates nested
179
171
  # transactions by using savepoints on MySQL and PostgreSQL. See
180
- # http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
172
+ # http://dev.mysql.com/doc/refman/5.7/en/savepoint.html
181
173
  # for more information about savepoints.
182
174
  #
183
- # === Callbacks
175
+ # === \Callbacks
184
176
  #
185
177
  # There are two types of callbacks associated with committing and rolling back transactions:
186
- # +after_commit+ and +after_rollback+.
178
+ # #after_commit and #after_rollback.
187
179
  #
188
- # +after_commit+ callbacks are called on every record saved or destroyed within a
189
- # transaction immediately after the transaction is committed. +after_rollback+ callbacks
180
+ # #after_commit callbacks are called on every record saved or destroyed within a
181
+ # transaction immediately after the transaction is committed. #after_rollback callbacks
190
182
  # are called on every record saved or destroyed within a transaction immediately after the
191
183
  # transaction or savepoint is rolled back.
192
184
  #
193
185
  # These callbacks are useful for interacting with other systems since you will be guaranteed
194
186
  # that the callback is only executed when the database is in a permanent state. For example,
195
- # +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
187
+ # #after_commit is a good spot to put in a hook to clearing a cache since clearing it from
196
188
  # within a transaction could trigger the cache to be regenerated before the database is updated.
197
189
  #
198
190
  # === Caveats
@@ -206,20 +198,24 @@ module ActiveRecord
206
198
  # automatically released. The following example demonstrates the problem:
207
199
  #
208
200
  # Model.connection.transaction do # BEGIN
209
- # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
201
+ # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
210
202
  # Model.connection.create_table(...) # active_record_1 now automatically released
211
- # end # RELEASE savepoint active_record_1
203
+ # end # RELEASE SAVEPOINT active_record_1
212
204
  # # ^^^^ BOOM! database error!
213
205
  # end
214
206
  #
215
207
  # Note that "TRUNCATE" is also a MySQL DDL statement!
216
208
  module ClassMethods
217
- # See ActiveRecord::Transactions::ClassMethods for detailed documentation.
209
+ # See the ConnectionAdapters::DatabaseStatements#transaction API docs.
218
210
  def transaction(options = {}, &block)
219
- # See the ConnectionAdapters::DatabaseStatements#transaction API docs.
220
211
  connection.transaction(options, &block)
221
212
  end
222
213
 
214
+ def before_commit(*args, &block) # :nodoc:
215
+ set_options_for_callbacks!(args)
216
+ set_callback(:before_commit, :before, *args, &block)
217
+ end
218
+
223
219
  # This callback is called after a record has been created, updated, or destroyed.
224
220
  #
225
221
  # You can specify that the callback should only be fired by a certain action with
@@ -232,32 +228,69 @@ module ActiveRecord
232
228
  # after_commit :do_foo_bar, on: [:create, :update]
233
229
  # after_commit :do_bar_baz, on: [:update, :destroy]
234
230
  #
235
- # Note that transactional fixtures do not play well with this feature. Please
236
- # use the +test_after_commit+ gem to have these hooks fired in tests.
237
231
  def after_commit(*args, &block)
238
232
  set_options_for_callbacks!(args)
239
233
  set_callback(:commit, :after, *args, &block)
240
- unless ActiveRecord::Base.raise_in_transactional_callbacks
241
- ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
242
- end
234
+ end
235
+
236
+ # Shortcut for <tt>after_commit :hook, on: :create</tt>.
237
+ def after_create_commit(*args, &block)
238
+ set_options_for_callbacks!(args, on: :create)
239
+ set_callback(:commit, :after, *args, &block)
240
+ end
241
+
242
+ # Shortcut for <tt>after_commit :hook, on: :update</tt>.
243
+ def after_update_commit(*args, &block)
244
+ set_options_for_callbacks!(args, on: :update)
245
+ set_callback(:commit, :after, *args, &block)
246
+ end
247
+
248
+ # Shortcut for <tt>after_commit :hook, on: :destroy</tt>.
249
+ def after_destroy_commit(*args, &block)
250
+ set_options_for_callbacks!(args, on: :destroy)
251
+ set_callback(:commit, :after, *args, &block)
243
252
  end
244
253
 
245
254
  # This callback is called after a create, update, or destroy are rolled back.
246
255
  #
247
- # Please check the documentation of +after_commit+ for options.
256
+ # Please check the documentation of #after_commit for options.
248
257
  def after_rollback(*args, &block)
249
258
  set_options_for_callbacks!(args)
250
259
  set_callback(:rollback, :after, *args, &block)
251
- unless ActiveRecord::Base.raise_in_transactional_callbacks
252
- ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
253
- end
260
+ end
261
+
262
+ def before_commit_without_transaction_enrollment(*args, &block) # :nodoc:
263
+ set_options_for_callbacks!(args)
264
+ set_callback(:before_commit_without_transaction_enrollment, :before, *args, &block)
265
+ end
266
+
267
+ def after_commit_without_transaction_enrollment(*args, &block) # :nodoc:
268
+ set_options_for_callbacks!(args)
269
+ set_callback(:commit_without_transaction_enrollment, :after, *args, &block)
270
+ end
271
+
272
+ def after_rollback_without_transaction_enrollment(*args, &block) # :nodoc:
273
+ set_options_for_callbacks!(args)
274
+ set_callback(:rollback_without_transaction_enrollment, :after, *args, &block)
275
+ end
276
+
277
+ def raise_in_transactional_callbacks
278
+ ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.')
279
+ true
280
+ end
281
+
282
+ def raise_in_transactional_callbacks=(value)
283
+ ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.')
284
+ value
254
285
  end
255
286
 
256
287
  private
257
288
 
258
- def set_options_for_callbacks!(args)
259
- options = args.last
260
- if options.is_a?(Hash) && options[:on]
289
+ def set_options_for_callbacks!(args, enforced_options = {})
290
+ options = args.extract_options!.merge!(enforced_options)
291
+ args << options
292
+
293
+ if options[:on]
261
294
  fire_on = Array(options[:on])
262
295
  assert_valid_transaction_action(fire_on)
263
296
  options[:if] = Array(options[:if])
@@ -306,31 +339,46 @@ module ActiveRecord
306
339
  clear_transaction_record_state
307
340
  end
308
341
 
309
- # Call the +after_commit+ callbacks.
342
+ def before_committed! # :nodoc:
343
+ _run_before_commit_without_transaction_enrollment_callbacks
344
+ _run_before_commit_callbacks
345
+ end
346
+
347
+ # Call the #after_commit callbacks.
310
348
  #
311
349
  # Ensure that it is not called if the object was never persisted (failed create),
312
350
  # but call it after the commit of a destroyed object.
313
- def committed!(should_run_callbacks = true) #:nodoc:
314
- _run_commit_callbacks if should_run_callbacks && destroyed? || persisted?
351
+ def committed!(should_run_callbacks: true) #:nodoc:
352
+ if should_run_callbacks && destroyed? || persisted?
353
+ _run_commit_without_transaction_enrollment_callbacks
354
+ _run_commit_callbacks
355
+ end
315
356
  ensure
316
357
  force_clear_transaction_record_state
317
358
  end
318
359
 
319
- # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
360
+ # Call the #after_rollback callbacks. The +force_restore_state+ argument indicates if the record
320
361
  # state should be rolled back to the beginning or just to the last savepoint.
321
- def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc:
322
- _run_rollback_callbacks if should_run_callbacks
362
+ def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc:
363
+ if should_run_callbacks
364
+ _run_rollback_callbacks
365
+ _run_rollback_without_transaction_enrollment_callbacks
366
+ end
323
367
  ensure
324
368
  restore_transaction_record_state(force_restore_state)
325
369
  clear_transaction_record_state
326
370
  end
327
371
 
328
- # Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
372
+ # Add the record to the current transaction so that the #after_rollback and #after_commit callbacks
329
373
  # can be called.
330
374
  def add_to_transaction
331
- if self.class.connection.add_transaction_record(self)
332
- remember_transaction_record_state
375
+ if has_transactional_callbacks?
376
+ self.class.connection.add_transaction_record(self)
377
+ else
378
+ sync_with_transaction_state
379
+ set_transaction_state(self.class.connection.transaction_state)
333
380
  end
381
+ remember_transaction_record_state
334
382
  end
335
383
 
336
384
  # Executes +method+ within a transaction and captures its return value as a
@@ -353,6 +401,10 @@ module ActiveRecord
353
401
  raise ActiveRecord::Rollback unless status
354
402
  end
355
403
  status
404
+ ensure
405
+ if @transaction_state && @transaction_state.committed?
406
+ clear_transaction_record_state
407
+ end
356
408
  end
357
409
 
358
410
  protected
@@ -360,14 +412,12 @@ module ActiveRecord
360
412
  # Save the new record state and id of a record so it can be restored later if a transaction fails.
361
413
  def remember_transaction_record_state #:nodoc:
362
414
  @_start_transaction_state[:id] = id
363
- unless @_start_transaction_state.include?(:new_record)
364
- @_start_transaction_state[:new_record] = @new_record
365
- end
366
- unless @_start_transaction_state.include?(:destroyed)
367
- @_start_transaction_state[:destroyed] = @destroyed
368
- end
415
+ @_start_transaction_state.reverse_merge!(
416
+ new_record: @new_record,
417
+ destroyed: @destroyed,
418
+ frozen?: frozen?,
419
+ )
369
420
  @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
370
- @_start_transaction_state[:frozen?] = frozen?
371
421
  end
372
422
 
373
423
  # Clear the new record state and id of a record.
@@ -387,10 +437,14 @@ module ActiveRecord
387
437
  transaction_level = (@_start_transaction_state[:level] || 0) - 1
388
438
  if transaction_level < 1 || force
389
439
  restore_state = @_start_transaction_state
390
- thaw unless restore_state[:frozen?]
440
+ thaw
391
441
  @new_record = restore_state[:new_record]
392
442
  @destroyed = restore_state[:destroyed]
393
- write_attribute(self.class.primary_key, restore_state[:id])
443
+ pk = self.class.primary_key
444
+ if pk && read_attribute(pk) != restore_state[:id]
445
+ write_attribute(pk, restore_state[:id])
446
+ end
447
+ freeze if restore_state[:frozen?]
394
448
  end
395
449
  end
396
450
  end
@@ -413,5 +467,43 @@ module ActiveRecord
413
467
  end
414
468
  end
415
469
  end
470
+
471
+ private
472
+
473
+ def set_transaction_state(state) # :nodoc:
474
+ @transaction_state = state
475
+ end
476
+
477
+ def has_transactional_callbacks? # :nodoc:
478
+ !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty?
479
+ end
480
+
481
+ # Updates the attributes on this particular Active Record object so that
482
+ # if it's associated with a transaction, then the state of the Active Record
483
+ # object will be updated to reflect the current state of the transaction
484
+ #
485
+ # The +@transaction_state+ variable stores the states of the associated
486
+ # transaction. This relies on the fact that a transaction can only be in
487
+ # one rollback or commit (otherwise a list of states would be required)
488
+ # Each Active Record object inside of a transaction carries that transaction's
489
+ # TransactionState.
490
+ #
491
+ # This method checks to see if the ActiveRecord object's state reflects
492
+ # the TransactionState, and rolls back or commits the Active Record object
493
+ # as appropriate.
494
+ #
495
+ # Since Active Record objects can be inside multiple transactions, this
496
+ # method recursively goes through the parent of the TransactionState and
497
+ # checks if the Active Record object reflects the state of the object.
498
+ def sync_with_transaction_state
499
+ update_attributes_from_transaction_state(@transaction_state)
500
+ end
501
+
502
+ def update_attributes_from_transaction_state(transaction_state)
503
+ if transaction_state && transaction_state.finalized?
504
+ restore_transaction_record_state if transaction_state.rolledback?
505
+ clear_transaction_record_state
506
+ end
507
+ end
416
508
  end
417
509
  end
@@ -0,0 +1,130 @@
1
+ require 'active_model/type/registry'
2
+
3
+ module ActiveRecord
4
+ # :stopdoc:
5
+ module Type
6
+ class AdapterSpecificRegistry < ActiveModel::Type::Registry
7
+ def add_modifier(options, klass, **args)
8
+ registrations << DecorationRegistration.new(options, klass, **args)
9
+ end
10
+
11
+ private
12
+
13
+ def registration_klass
14
+ Registration
15
+ end
16
+
17
+ def find_registration(symbol, *args)
18
+ registrations
19
+ .select { |registration| registration.matches?(symbol, *args) }
20
+ .max
21
+ end
22
+ end
23
+
24
+ class Registration
25
+ def initialize(name, block, adapter: nil, override: nil)
26
+ @name = name
27
+ @block = block
28
+ @adapter = adapter
29
+ @override = override
30
+ end
31
+
32
+ def call(_registry, *args, adapter: nil, **kwargs)
33
+ if kwargs.any? # https://bugs.ruby-lang.org/issues/10856
34
+ block.call(*args, **kwargs)
35
+ else
36
+ block.call(*args)
37
+ end
38
+ end
39
+
40
+ def matches?(type_name, *args, **kwargs)
41
+ type_name == name && matches_adapter?(**kwargs)
42
+ end
43
+
44
+ def <=>(other)
45
+ if conflicts_with?(other)
46
+ raise TypeConflictError.new("Type #{name} was registered for all
47
+ adapters, but shadows a native type with
48
+ the same name for #{other.adapter}".squish)
49
+ end
50
+ priority <=> other.priority
51
+ end
52
+
53
+ protected
54
+
55
+ attr_reader :name, :block, :adapter, :override
56
+
57
+ def priority
58
+ result = 0
59
+ if adapter
60
+ result |= 1
61
+ end
62
+ if override
63
+ result |= 2
64
+ end
65
+ result
66
+ end
67
+
68
+ def priority_except_adapter
69
+ priority & 0b111111100
70
+ end
71
+
72
+ private
73
+
74
+ def matches_adapter?(adapter: nil, **)
75
+ (self.adapter.nil? || adapter == self.adapter)
76
+ end
77
+
78
+ def conflicts_with?(other)
79
+ same_priority_except_adapter?(other) &&
80
+ has_adapter_conflict?(other)
81
+ end
82
+
83
+ def same_priority_except_adapter?(other)
84
+ priority_except_adapter == other.priority_except_adapter
85
+ end
86
+
87
+ def has_adapter_conflict?(other)
88
+ (override.nil? && other.adapter) ||
89
+ (adapter && other.override.nil?)
90
+ end
91
+ end
92
+
93
+ class DecorationRegistration < Registration
94
+ def initialize(options, klass, adapter: nil)
95
+ @options = options
96
+ @klass = klass
97
+ @adapter = adapter
98
+ end
99
+
100
+ def call(registry, *args, **kwargs)
101
+ subtype = registry.lookup(*args, **kwargs.except(*options.keys))
102
+ klass.new(subtype)
103
+ end
104
+
105
+ def matches?(*args, **kwargs)
106
+ matches_adapter?(**kwargs) && matches_options?(**kwargs)
107
+ end
108
+
109
+ def priority
110
+ super | 4
111
+ end
112
+
113
+ protected
114
+
115
+ attr_reader :options, :klass
116
+
117
+ private
118
+
119
+ def matches_options?(**kwargs)
120
+ options.all? do |key, value|
121
+ kwargs[key] == value
122
+ end
123
+ end
124
+ end
125
+ end
126
+
127
+ class TypeConflictError < StandardError
128
+ end
129
+ # :startdoc:
130
+ end
@@ -1,46 +1,7 @@
1
1
  module ActiveRecord
2
2
  module Type
3
- class Date < Value # :nodoc:
4
- def type
5
- :date
6
- end
7
-
8
- def klass
9
- ::Date
10
- end
11
-
12
- def type_cast_for_schema(value)
13
- "'#{value.to_s(:db)}'"
14
- end
15
-
16
- private
17
-
18
- def cast_value(value)
19
- if value.is_a?(::String)
20
- return if value.empty?
21
- fast_string_to_date(value) || fallback_string_to_date(value)
22
- elsif value.respond_to?(:to_date)
23
- value.to_date
24
- else
25
- value
26
- end
27
- end
28
-
29
- def fast_string_to_date(string)
30
- if string =~ ConnectionAdapters::Column::Format::ISO_DATE
31
- new_date $1.to_i, $2.to_i, $3.to_i
32
- end
33
- end
34
-
35
- def fallback_string_to_date(string)
36
- new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
37
- end
38
-
39
- def new_date(year, mon, mday)
40
- if year && year != 0
41
- ::Date.new(year, mon, mday) rescue nil
42
- end
43
- end
3
+ class Date < ActiveModel::Type::Date
4
+ include Internal::Timezone
44
5
  end
45
6
  end
46
7
  end
@@ -1,43 +1,7 @@
1
1
  module ActiveRecord
2
2
  module Type
3
- class DateTime < Value # :nodoc:
4
- include TimeValue
5
-
6
- def type
7
- :datetime
8
- end
9
-
10
- def type_cast_for_database(value)
11
- zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
12
-
13
- if value.acts_like?(:time)
14
- value.send(zone_conversion_method)
15
- else
16
- super
17
- end
18
- end
19
-
20
- private
21
-
22
- def cast_value(string)
23
- return string unless string.is_a?(::String)
24
- return if string.empty?
25
-
26
- fast_string_to_time(string) || fallback_string_to_time(string)
27
- end
28
-
29
- # '0.123456' -> 123456
30
- # '1.123456' -> 123456
31
- def microseconds(time)
32
- time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
33
- end
34
-
35
- def fallback_string_to_time(string)
36
- time_hash = ::Date._parse(string)
37
- time_hash[:sec_fraction] = microseconds(time_hash)
38
-
39
- new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset))
40
- end
3
+ class DateTime < ActiveModel::Type::DateTime
4
+ include Internal::Timezone
41
5
  end
42
6
  end
43
7
  end
@@ -1,12 +1,18 @@
1
1
  module ActiveRecord
2
2
  module Type
3
3
  class HashLookupTypeMap < TypeMap # :nodoc:
4
- delegate :key?, to: :@mapping
5
-
6
4
  def alias_type(type, alias_type)
7
5
  register_type(type) { |_, *args| lookup(alias_type, *args) }
8
6
  end
9
7
 
8
+ def key?(key)
9
+ @mapping.key?(key)
10
+ end
11
+
12
+ def keys
13
+ @mapping.keys
14
+ end
15
+
10
16
  private
11
17
 
12
18
  def perform_fetch(type, *args, &block)
@@ -0,0 +1,29 @@
1
+ module ActiveRecord
2
+ module Type
3
+ module Internal # :nodoc:
4
+ class AbstractJson < ActiveModel::Type::Value # :nodoc:
5
+ include ActiveModel::Type::Helpers::Mutable
6
+
7
+ def type
8
+ :json
9
+ end
10
+
11
+ def deserialize(value)
12
+ if value.is_a?(::String)
13
+ ::ActiveSupport::JSON.decode(value) rescue nil
14
+ else
15
+ value
16
+ end
17
+ end
18
+
19
+ def serialize(value)
20
+ ::ActiveSupport::JSON.encode(value)
21
+ end
22
+
23
+ def accessor
24
+ ActiveRecord::Store::StringKeyedHashAccessor
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end