activerecord 6.0.3.4 → 6.1.2

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 (245) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +891 -695
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +3 -3
  5. data/lib/active_record.rb +7 -14
  6. data/lib/active_record/aggregations.rb +5 -5
  7. data/lib/active_record/association_relation.rb +30 -12
  8. data/lib/active_record/associations.rb +118 -11
  9. data/lib/active_record/associations/alias_tracker.rb +19 -15
  10. data/lib/active_record/associations/association.rb +44 -28
  11. data/lib/active_record/associations/association_scope.rb +19 -15
  12. data/lib/active_record/associations/belongs_to_association.rb +22 -8
  13. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +8 -3
  14. data/lib/active_record/associations/builder/association.rb +32 -5
  15. data/lib/active_record/associations/builder/belongs_to.rb +10 -7
  16. data/lib/active_record/associations/builder/collection_association.rb +5 -4
  17. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +0 -1
  18. data/lib/active_record/associations/builder/has_many.rb +6 -2
  19. data/lib/active_record/associations/builder/has_one.rb +11 -14
  20. data/lib/active_record/associations/builder/singular_association.rb +1 -1
  21. data/lib/active_record/associations/collection_association.rb +19 -6
  22. data/lib/active_record/associations/collection_proxy.rb +13 -5
  23. data/lib/active_record/associations/foreign_association.rb +13 -0
  24. data/lib/active_record/associations/has_many_association.rb +24 -2
  25. data/lib/active_record/associations/has_many_through_association.rb +10 -4
  26. data/lib/active_record/associations/has_one_association.rb +15 -1
  27. data/lib/active_record/associations/join_dependency.rb +72 -50
  28. data/lib/active_record/associations/join_dependency/join_association.rb +39 -16
  29. data/lib/active_record/associations/join_dependency/join_part.rb +3 -3
  30. data/lib/active_record/associations/preloader.rb +11 -5
  31. data/lib/active_record/associations/preloader/association.rb +51 -25
  32. data/lib/active_record/associations/preloader/through_association.rb +2 -2
  33. data/lib/active_record/associations/singular_association.rb +1 -1
  34. data/lib/active_record/associations/through_association.rb +1 -1
  35. data/lib/active_record/attribute_assignment.rb +10 -8
  36. data/lib/active_record/attribute_methods.rb +64 -54
  37. data/lib/active_record/attribute_methods/before_type_cast.rb +13 -9
  38. data/lib/active_record/attribute_methods/dirty.rb +1 -11
  39. data/lib/active_record/attribute_methods/primary_key.rb +6 -2
  40. data/lib/active_record/attribute_methods/query.rb +3 -6
  41. data/lib/active_record/attribute_methods/read.rb +8 -11
  42. data/lib/active_record/attribute_methods/serialization.rb +11 -5
  43. data/lib/active_record/attribute_methods/time_zone_conversion.rb +12 -13
  44. data/lib/active_record/attribute_methods/write.rb +12 -20
  45. data/lib/active_record/attributes.rb +33 -8
  46. data/lib/active_record/autosave_association.rb +57 -40
  47. data/lib/active_record/base.rb +2 -14
  48. data/lib/active_record/callbacks.rb +152 -22
  49. data/lib/active_record/coders/yaml_column.rb +1 -1
  50. data/lib/active_record/connection_adapters.rb +50 -0
  51. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +191 -134
  52. data/lib/active_record/connection_adapters/abstract/database_limits.rb +2 -44
  53. data/lib/active_record/connection_adapters/abstract/database_statements.rb +65 -22
  54. data/lib/active_record/connection_adapters/abstract/query_cache.rb +3 -8
  55. data/lib/active_record/connection_adapters/abstract/quoting.rb +34 -34
  56. data/lib/active_record/connection_adapters/abstract/savepoints.rb +3 -3
  57. data/lib/active_record/connection_adapters/abstract/schema_creation.rb +153 -116
  58. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +116 -27
  59. data/lib/active_record/connection_adapters/abstract/schema_dumper.rb +3 -3
  60. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +228 -83
  61. data/lib/active_record/connection_adapters/abstract/transaction.rb +80 -32
  62. data/lib/active_record/connection_adapters/abstract_adapter.rb +54 -72
  63. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +133 -96
  64. data/lib/active_record/connection_adapters/column.rb +15 -1
  65. data/lib/active_record/connection_adapters/deduplicable.rb +29 -0
  66. data/lib/active_record/connection_adapters/legacy_pool_manager.rb +31 -0
  67. data/lib/active_record/connection_adapters/mysql/database_statements.rb +23 -25
  68. data/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +1 -1
  69. data/lib/active_record/connection_adapters/mysql/quoting.rb +1 -1
  70. data/lib/active_record/connection_adapters/mysql/schema_creation.rb +32 -6
  71. data/lib/active_record/connection_adapters/mysql/schema_definitions.rb +8 -0
  72. data/lib/active_record/connection_adapters/mysql/schema_dumper.rb +5 -2
  73. data/lib/active_record/connection_adapters/mysql/schema_statements.rb +11 -7
  74. data/lib/active_record/connection_adapters/mysql/type_metadata.rb +10 -1
  75. data/lib/active_record/connection_adapters/mysql2_adapter.rb +31 -12
  76. data/lib/active_record/connection_adapters/pool_config.rb +73 -0
  77. data/lib/active_record/connection_adapters/pool_manager.rb +43 -0
  78. data/lib/active_record/connection_adapters/postgresql/column.rb +24 -1
  79. data/lib/active_record/connection_adapters/postgresql/database_statements.rb +13 -54
  80. data/lib/active_record/connection_adapters/postgresql/oid.rb +2 -0
  81. data/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +3 -5
  82. data/lib/active_record/connection_adapters/postgresql/oid/date.rb +2 -2
  83. data/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +10 -2
  84. data/lib/active_record/connection_adapters/postgresql/oid/interval.rb +49 -0
  85. data/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +2 -2
  86. data/lib/active_record/connection_adapters/postgresql/oid/macaddr.rb +25 -0
  87. data/lib/active_record/connection_adapters/postgresql/oid/point.rb +2 -2
  88. data/lib/active_record/connection_adapters/postgresql/oid/range.rb +24 -5
  89. data/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +11 -1
  90. data/lib/active_record/connection_adapters/postgresql/quoting.rb +4 -4
  91. data/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +1 -1
  92. data/lib/active_record/connection_adapters/postgresql/schema_creation.rb +5 -1
  93. data/lib/active_record/connection_adapters/postgresql/schema_statements.rb +61 -29
  94. data/lib/active_record/connection_adapters/postgresql/type_metadata.rb +8 -0
  95. data/lib/active_record/connection_adapters/postgresql_adapter.rb +73 -58
  96. data/lib/active_record/connection_adapters/schema_cache.rb +98 -15
  97. data/lib/active_record/connection_adapters/sql_type_metadata.rb +10 -0
  98. data/lib/active_record/connection_adapters/sqlite3/database_statements.rb +31 -6
  99. data/lib/active_record/connection_adapters/sqlite3/quoting.rb +1 -1
  100. data/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +5 -1
  101. data/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +37 -4
  102. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +49 -50
  103. data/lib/active_record/connection_handling.rb +218 -71
  104. data/lib/active_record/core.rb +245 -61
  105. data/lib/active_record/database_configurations.rb +124 -85
  106. data/lib/active_record/database_configurations/connection_url_resolver.rb +98 -0
  107. data/lib/active_record/database_configurations/database_config.rb +52 -9
  108. data/lib/active_record/database_configurations/hash_config.rb +54 -8
  109. data/lib/active_record/database_configurations/url_config.rb +15 -40
  110. data/lib/active_record/delegated_type.rb +209 -0
  111. data/lib/active_record/destroy_association_async_job.rb +36 -0
  112. data/lib/active_record/enum.rb +82 -38
  113. data/lib/active_record/errors.rb +47 -12
  114. data/lib/active_record/explain.rb +9 -4
  115. data/lib/active_record/explain_subscriber.rb +1 -1
  116. data/lib/active_record/fixture_set/file.rb +10 -17
  117. data/lib/active_record/fixture_set/model_metadata.rb +1 -2
  118. data/lib/active_record/fixture_set/render_context.rb +1 -1
  119. data/lib/active_record/fixture_set/table_row.rb +2 -2
  120. data/lib/active_record/fixtures.rb +58 -9
  121. data/lib/active_record/gem_version.rb +3 -3
  122. data/lib/active_record/inheritance.rb +40 -18
  123. data/lib/active_record/insert_all.rb +35 -6
  124. data/lib/active_record/integration.rb +3 -5
  125. data/lib/active_record/internal_metadata.rb +16 -7
  126. data/lib/active_record/legacy_yaml_adapter.rb +7 -3
  127. data/lib/active_record/locking/optimistic.rb +33 -17
  128. data/lib/active_record/locking/pessimistic.rb +6 -2
  129. data/lib/active_record/log_subscriber.rb +27 -8
  130. data/lib/active_record/middleware/database_selector.rb +4 -1
  131. data/lib/active_record/middleware/database_selector/resolver.rb +5 -0
  132. data/lib/active_record/middleware/database_selector/resolver/session.rb +3 -0
  133. data/lib/active_record/migration.rb +113 -83
  134. data/lib/active_record/migration/command_recorder.rb +47 -27
  135. data/lib/active_record/migration/compatibility.rb +68 -17
  136. data/lib/active_record/model_schema.rb +117 -13
  137. data/lib/active_record/nested_attributes.rb +2 -3
  138. data/lib/active_record/no_touching.rb +1 -1
  139. data/lib/active_record/persistence.rb +50 -45
  140. data/lib/active_record/query_cache.rb +15 -5
  141. data/lib/active_record/querying.rb +11 -6
  142. data/lib/active_record/railtie.rb +64 -44
  143. data/lib/active_record/railties/console_sandbox.rb +2 -4
  144. data/lib/active_record/railties/databases.rake +276 -99
  145. data/lib/active_record/readonly_attributes.rb +4 -0
  146. data/lib/active_record/reflection.rb +71 -57
  147. data/lib/active_record/relation.rb +96 -67
  148. data/lib/active_record/relation/batches.rb +38 -31
  149. data/lib/active_record/relation/batches/batch_enumerator.rb +25 -9
  150. data/lib/active_record/relation/calculations.rb +101 -44
  151. data/lib/active_record/relation/delegation.rb +2 -1
  152. data/lib/active_record/relation/finder_methods.rb +45 -15
  153. data/lib/active_record/relation/from_clause.rb +1 -1
  154. data/lib/active_record/relation/merger.rb +27 -25
  155. data/lib/active_record/relation/predicate_builder.rb +59 -38
  156. data/lib/active_record/relation/predicate_builder/array_handler.rb +8 -9
  157. data/lib/active_record/relation/predicate_builder/association_query_value.rb +4 -5
  158. data/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb +10 -6
  159. data/lib/active_record/relation/predicate_builder/relation_handler.rb +1 -1
  160. data/lib/active_record/relation/query_methods.rb +333 -195
  161. data/lib/active_record/relation/record_fetch_warning.rb +3 -3
  162. data/lib/active_record/relation/spawn_methods.rb +8 -7
  163. data/lib/active_record/relation/where_clause.rb +104 -57
  164. data/lib/active_record/result.rb +41 -33
  165. data/lib/active_record/runtime_registry.rb +2 -2
  166. data/lib/active_record/sanitization.rb +6 -17
  167. data/lib/active_record/schema_dumper.rb +34 -4
  168. data/lib/active_record/schema_migration.rb +2 -8
  169. data/lib/active_record/scoping/named.rb +6 -17
  170. data/lib/active_record/secure_token.rb +16 -8
  171. data/lib/active_record/serialization.rb +5 -3
  172. data/lib/active_record/signed_id.rb +116 -0
  173. data/lib/active_record/statement_cache.rb +20 -4
  174. data/lib/active_record/store.rb +2 -2
  175. data/lib/active_record/suppressor.rb +2 -2
  176. data/lib/active_record/table_metadata.rb +42 -51
  177. data/lib/active_record/tasks/database_tasks.rb +140 -113
  178. data/lib/active_record/tasks/mysql_database_tasks.rb +34 -35
  179. data/lib/active_record/tasks/postgresql_database_tasks.rb +24 -26
  180. data/lib/active_record/tasks/sqlite_database_tasks.rb +13 -9
  181. data/lib/active_record/test_databases.rb +5 -4
  182. data/lib/active_record/test_fixtures.rb +37 -16
  183. data/lib/active_record/timestamp.rb +4 -6
  184. data/lib/active_record/touch_later.rb +21 -21
  185. data/lib/active_record/transactions.rb +19 -66
  186. data/lib/active_record/type.rb +8 -1
  187. data/lib/active_record/type/serialized.rb +6 -2
  188. data/lib/active_record/type/time.rb +10 -0
  189. data/lib/active_record/type_caster/connection.rb +0 -1
  190. data/lib/active_record/type_caster/map.rb +8 -5
  191. data/lib/active_record/validations.rb +1 -0
  192. data/lib/active_record/validations/numericality.rb +35 -0
  193. data/lib/active_record/validations/uniqueness.rb +24 -4
  194. data/lib/arel.rb +5 -13
  195. data/lib/arel/attributes/attribute.rb +4 -0
  196. data/lib/arel/collectors/bind.rb +5 -0
  197. data/lib/arel/collectors/composite.rb +8 -0
  198. data/lib/arel/collectors/sql_string.rb +7 -0
  199. data/lib/arel/collectors/substitute_binds.rb +7 -0
  200. data/lib/arel/nodes.rb +3 -1
  201. data/lib/arel/nodes/binary.rb +82 -8
  202. data/lib/arel/nodes/bind_param.rb +8 -0
  203. data/lib/arel/nodes/casted.rb +21 -9
  204. data/lib/arel/nodes/equality.rb +6 -9
  205. data/lib/arel/nodes/grouping.rb +3 -0
  206. data/lib/arel/nodes/homogeneous_in.rb +72 -0
  207. data/lib/arel/nodes/in.rb +8 -1
  208. data/lib/arel/nodes/infix_operation.rb +13 -1
  209. data/lib/arel/nodes/join_source.rb +1 -1
  210. data/lib/arel/nodes/node.rb +7 -6
  211. data/lib/arel/nodes/ordering.rb +27 -0
  212. data/lib/arel/nodes/sql_literal.rb +3 -0
  213. data/lib/arel/nodes/table_alias.rb +7 -3
  214. data/lib/arel/nodes/unary.rb +0 -1
  215. data/lib/arel/predications.rb +12 -18
  216. data/lib/arel/select_manager.rb +1 -2
  217. data/lib/arel/table.rb +13 -5
  218. data/lib/arel/visitors.rb +0 -7
  219. data/lib/arel/visitors/dot.rb +14 -2
  220. data/lib/arel/visitors/mysql.rb +11 -1
  221. data/lib/arel/visitors/postgresql.rb +15 -4
  222. data/lib/arel/visitors/to_sql.rb +89 -78
  223. data/lib/rails/generators/active_record/migration.rb +6 -1
  224. data/lib/rails/generators/active_record/migration/migration_generator.rb +1 -0
  225. data/lib/rails/generators/active_record/migration/templates/create_table_migration.rb.tt +2 -0
  226. data/lib/rails/generators/active_record/migration/templates/migration.rb.tt +3 -3
  227. data/lib/rails/generators/active_record/model/model_generator.rb +39 -2
  228. data/lib/rails/generators/active_record/model/templates/abstract_base_class.rb.tt +7 -0
  229. metadata +25 -26
  230. data/lib/active_record/advisory_lock_base.rb +0 -18
  231. data/lib/active_record/attribute_decorators.rb +0 -88
  232. data/lib/active_record/connection_adapters/connection_specification.rb +0 -296
  233. data/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +0 -29
  234. data/lib/active_record/define_callbacks.rb +0 -22
  235. data/lib/active_record/railties/collection_cache_association_loading.rb +0 -34
  236. data/lib/active_record/relation/predicate_builder/base_handler.rb +0 -18
  237. data/lib/active_record/relation/where_clause_factory.rb +0 -33
  238. data/lib/arel/attributes.rb +0 -22
  239. data/lib/arel/visitors/depth_first.rb +0 -203
  240. data/lib/arel/visitors/ibm_db.rb +0 -34
  241. data/lib/arel/visitors/informix.rb +0 -62
  242. data/lib/arel/visitors/mssql.rb +0 -156
  243. data/lib/arel/visitors/oracle.rb +0 -158
  244. data/lib/arel/visitors/oracle12.rb +0 -65
  245. data/lib/arel/visitors/where_sql.rb +0 -22
@@ -12,12 +12,12 @@ module ActiveRecord
12
12
  # Becomes:
13
13
  #
14
14
  # #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10
15
- # @env_name="development", @spec_name="primary", @config={"database"=>"db_name"}>
15
+ # @env_name="development", @name="primary", @config={database: "db_name"}>
16
16
  #
17
17
  # ==== Options
18
18
  #
19
19
  # * <tt>:env_name</tt> - The Rails environment, i.e. "development".
20
- # * <tt>:spec_name</tt> - The specification name. In a standard two-tier
20
+ # * <tt>:name</tt> - The db config name. In a standard two-tier
21
21
  # database configuration this will default to "primary". In a multiple
22
22
  # database three-tier database configuration this corresponds to the name
23
23
  # used in the second tier, for example "primary_readonly".
@@ -25,25 +25,71 @@ module ActiveRecord
25
25
  # database adapter, name, and other important information for database
26
26
  # connections.
27
27
  class HashConfig < DatabaseConfig
28
- attr_reader :config
28
+ attr_reader :configuration_hash
29
+ def initialize(env_name, name, configuration_hash)
30
+ super(env_name, name)
31
+ @configuration_hash = configuration_hash.symbolize_keys.freeze
32
+ end
29
33
 
30
- def initialize(env_name, spec_name, config)
31
- super(env_name, spec_name)
32
- @config = config
34
+ def config
35
+ ActiveSupport::Deprecation.warn("DatabaseConfig#config will be removed in 6.2.0 in favor of DatabaseConfigurations#configuration_hash which returns a hash with symbol keys")
36
+ configuration_hash.stringify_keys
33
37
  end
34
38
 
35
39
  # Determines whether a database configuration is for a replica / readonly
36
40
  # connection. If the +replica+ key is present in the config, +replica?+ will
37
41
  # return +true+.
38
42
  def replica?
39
- config["replica"]
43
+ configuration_hash[:replica]
40
44
  end
41
45
 
42
46
  # The migrations paths for a database configuration. If the
43
47
  # +migrations_paths+ key is present in the config, +migrations_paths+
44
48
  # will return its value.
45
49
  def migrations_paths
46
- config["migrations_paths"]
50
+ configuration_hash[:migrations_paths]
51
+ end
52
+
53
+ def host
54
+ configuration_hash[:host]
55
+ end
56
+
57
+ def database
58
+ configuration_hash[:database]
59
+ end
60
+
61
+ def _database=(database) # :nodoc:
62
+ @configuration_hash = configuration_hash.merge(database: database).freeze
63
+ end
64
+
65
+ def pool
66
+ (configuration_hash[:pool] || 5).to_i
67
+ end
68
+
69
+ def checkout_timeout
70
+ (configuration_hash[:checkout_timeout] || 5).to_f
71
+ end
72
+
73
+ # +reaping_frequency+ is configurable mostly for historical reasons, but it could
74
+ # also be useful if someone wants a very low +idle_timeout+.
75
+ def reaping_frequency
76
+ configuration_hash.fetch(:reaping_frequency, 60)&.to_f
77
+ end
78
+
79
+ def idle_timeout
80
+ timeout = configuration_hash.fetch(:idle_timeout, 300).to_f
81
+ timeout if timeout > 0
82
+ end
83
+
84
+ def adapter
85
+ configuration_hash[:adapter]
86
+ end
87
+
88
+ # The path to the schema cache dump file for a database.
89
+ # If omitted, the filename will be read from ENV or a
90
+ # default will be derived.
91
+ def schema_cache_path
92
+ configuration_hash[:schema_cache_path]
47
93
  end
48
94
  end
49
95
  end
@@ -13,14 +13,14 @@ module ActiveRecord
13
13
  # Becomes:
14
14
  #
15
15
  # #<ActiveRecord::DatabaseConfigurations::UrlConfig:0x00007fdc3238f340
16
- # @env_name="default_env", @spec_name="primary",
17
- # @config={"adapter"=>"postgresql", "database"=>"foo", "host"=>"localhost"},
16
+ # @env_name="default_env", @name="primary",
17
+ # @config={adapter: "postgresql", database: "foo", host: "localhost"},
18
18
  # @url="postgres://localhost/foo">
19
19
  #
20
20
  # ==== Options
21
21
  #
22
22
  # * <tt>:env_name</tt> - The Rails environment, ie "development".
23
- # * <tt>:spec_name</tt> - The specification name. In a standard two-tier
23
+ # * <tt>:name</tt> - The db config name. In a standard two-tier
24
24
  # database configuration this will default to "primary". In a multiple
25
25
  # database three-tier database configuration this corresponds to the name
26
26
  # used in the second tier, for example "primary_readonly".
@@ -28,49 +28,24 @@ module ActiveRecord
28
28
  # * <tt>:config</tt> - The config hash. This is the hash that contains the
29
29
  # database adapter, name, and other important information for database
30
30
  # connections.
31
- class UrlConfig < DatabaseConfig
32
- attr_reader :url, :config
31
+ class UrlConfig < HashConfig
32
+ attr_reader :url
33
33
 
34
- def initialize(env_name, spec_name, url, config = {})
35
- super(env_name, spec_name)
36
- @config = build_config(config, url)
37
- @url = url
38
- end
39
-
40
- def url_config? # :nodoc:
41
- true
42
- end
43
-
44
- # Determines whether a database configuration is for a replica / readonly
45
- # connection. If the +replica+ key is present in the config, +replica?+ will
46
- # return +true+.
47
- def replica?
48
- config["replica"]
49
- end
34
+ def initialize(env_name, name, url, configuration_hash = {})
35
+ super(env_name, name, configuration_hash)
50
36
 
51
- # The migrations paths for a database configuration. If the
52
- # +migrations_paths+ key is present in the config, +migrations_paths+
53
- # will return its value.
54
- def migrations_paths
55
- config["migrations_paths"]
37
+ @url = url
38
+ @configuration_hash = @configuration_hash.merge(build_url_hash).freeze
56
39
  end
57
40
 
58
41
  private
59
- def build_url_hash(url)
60
- if url.nil? || /^jdbc:/.match?(url)
61
- { "url" => url }
62
- else
63
- ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(url).to_hash
64
- end
65
- end
66
-
67
- def build_config(original_config, url)
68
- hash = build_url_hash(url)
69
-
70
- if original_config[env_name]
71
- original_config[env_name].merge(hash)
42
+ # Return a Hash that can be merged into the main config that represents
43
+ # the passed in url
44
+ def build_url_hash
45
+ if url.nil? || %w(jdbc: http: https:).any? { |protocol| url.start_with?(protocol) }
46
+ { url: url }
72
47
  else
73
- original_config.merge(hash)
48
+ ConnectionUrlResolver.new(url).to_hash
74
49
  end
75
50
  end
76
51
  end
@@ -0,0 +1,209 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/string/inquiry"
4
+
5
+ module ActiveRecord
6
+ # == Delegated types
7
+ #
8
+ # Class hierarchies can map to relational database tables in many ways. Active Record, for example, offers
9
+ # purely abstract classes, where the superclass doesn't persist any attributes, and single-table inheritance,
10
+ # where all attributes from all levels of the hierarchy are represented in a single table. Both have their
11
+ # places, but neither are without their drawbacks.
12
+ #
13
+ # The problem with purely abstract classes is that all concrete subclasses must persist all the shared
14
+ # attributes themselves in their own tables (also known as class-table inheritance). This makes it hard to
15
+ # do queries across the hierarchy. For example, imagine you have the following hierarchy:
16
+ #
17
+ # Entry < ApplicationRecord
18
+ # Message < Entry
19
+ # Comment < Entry
20
+ #
21
+ # How do you show a feed that has both +Message+ and +Comment+ records, which can be easily paginated?
22
+ # Well, you can't! Messages are backed by a messages table and comments by a comments table. You can't
23
+ # pull from both tables at once and use a consistent OFFSET/LIMIT scheme.
24
+ #
25
+ # You can get around the pagination problem by using single-table inheritance, but now you're forced into
26
+ # a single mega table with all the attributes from all subclasses. No matter how divergent. If a Message
27
+ # has a subject, but the comment does not, well, now the comment does anyway! So STI works best when there's
28
+ # little divergence between the subclasses and their attributes.
29
+ #
30
+ # But there's a third way: Delegated types. With this approach, the "superclass" is a concrete class
31
+ # that is represented by its own table, where all the superclass attributes that are shared amongst all the
32
+ # "subclasses" are stored. And then each of the subclasses have their own individual tables for additional
33
+ # attributes that are particular to their implementation. This is similar to what's called multi-table
34
+ # inheritance in Django, but instead of actual inheritance, this approach uses delegation to form the
35
+ # hierarchy and share responsibilities.
36
+ #
37
+ # Let's look at that entry/message/comment example using delegated types:
38
+ #
39
+ # # Schema: entries[ id, account_id, creator_id, created_at, updated_at, entryable_type, entryable_id ]
40
+ # class Entry < ApplicationRecord
41
+ # belongs_to :account
42
+ # belongs_to :creator
43
+ # delegated_type :entryable, types: %w[ Message Comment ]
44
+ # end
45
+ #
46
+ # module Entryable
47
+ # extend ActiveSupport::Concern
48
+ #
49
+ # included do
50
+ # has_one :entry, as: :entryable, touch: true
51
+ # end
52
+ # end
53
+ #
54
+ # # Schema: messages[ id, subject ]
55
+ # class Message < ApplicationRecord
56
+ # include Entryable
57
+ # has_rich_text :content
58
+ # end
59
+ #
60
+ # # Schema: comments[ id, content ]
61
+ # class Comment < ApplicationRecord
62
+ # include Entryable
63
+ # end
64
+ #
65
+ # As you can see, neither +Message+ nor +Comment+ are meant to stand alone. Crucial metadata for both classes
66
+ # resides in the +Entry+ "superclass". But the +Entry+ absolutely can stand alone in terms of querying capacity
67
+ # in particular. You can now easily do things like:
68
+ #
69
+ # Account.entries.order(created_at: :desc).limit(50)
70
+ #
71
+ # Which is exactly what you want when displaying both comments and messages together. The entry itself can
72
+ # be rendered as its delegated type easily, like so:
73
+ #
74
+ # # entries/_entry.html.erb
75
+ # <%= render "entries/entryables/#{entry.entryable_name}", entry: entry %>
76
+ #
77
+ # # entries/entryables/_message.html.erb
78
+ # <div class="message">
79
+ # Posted on <%= entry.created_at %> by <%= entry.creator.name %>: <%= entry.message.content %>
80
+ # </div>
81
+ #
82
+ # # entries/entryables/_comment.html.erb
83
+ # <div class="comment">
84
+ # <%= entry.creator.name %> said: <%= entry.comment.content %>
85
+ # </div>
86
+ #
87
+ # == Sharing behavior with concerns and controllers
88
+ #
89
+ # The entry "superclass" also serves as a perfect place to put all that shared logic that applies to both
90
+ # messages and comments, and which acts primarily on the shared attributes. Imagine:
91
+ #
92
+ # class Entry < ApplicationRecord
93
+ # include Eventable, Forwardable, Redeliverable
94
+ # end
95
+ #
96
+ # Which allows you to have controllers for things like +ForwardsController+ and +RedeliverableController+
97
+ # that both act on entries, and thus provide the shared functionality to both messages and comments.
98
+ #
99
+ # == Creating new records
100
+ #
101
+ # You create a new record that uses delegated typing by creating the delegator and delegatee at the same time,
102
+ # like so:
103
+ #
104
+ # Entry.create! entryable: Comment.new(content: "Hello!"), creator: Current.user
105
+ #
106
+ # If you need more complicated composition, or you need to perform dependent validation, you should build a factory
107
+ # method or class to take care of the complicated needs. This could be as simple as:
108
+ #
109
+ # class Entry < ApplicationRecord
110
+ # def self.create_with_comment(content, creator: Current.user)
111
+ # create! entryable: Comment.new(content: content), creator: creator
112
+ # end
113
+ # end
114
+ #
115
+ # == Adding further delegation
116
+ #
117
+ # The delegated type shouldn't just answer the question of what the underlying class is called. In fact, that's
118
+ # an anti-pattern most of the time. The reason you're building this hierarchy is to take advantage of polymorphism.
119
+ # So here's a simple example of that:
120
+ #
121
+ # class Entry < ApplicationRecord
122
+ # delegated_type :entryable, types: %w[ Message Comment ]
123
+ # delegate :title, to: :entryable
124
+ # end
125
+ #
126
+ # class Message < ApplicationRecord
127
+ # def title
128
+ # subject
129
+ # end
130
+ # end
131
+ #
132
+ # class Comment < ApplicationRecord
133
+ # def title
134
+ # content.truncate(20)
135
+ # end
136
+ # end
137
+ #
138
+ # Now you can list a bunch of entries, call +Entry#title+, and polymorphism will provide you with the answer.
139
+ module DelegatedType
140
+ # Defines this as a class that'll delegate its type for the passed +role+ to the class references in +types+.
141
+ # That'll create a polymorphic +belongs_to+ relationship to that +role+, and it'll add all the delegated
142
+ # type convenience methods:
143
+ #
144
+ # class Entry < ApplicationRecord
145
+ # delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
146
+ # end
147
+ #
148
+ # Entry#entryable_class # => +Message+ or +Comment+
149
+ # Entry#entryable_name # => "message" or "comment"
150
+ # Entry.messages # => Entry.where(entryable_type: "Message")
151
+ # Entry#message? # => true when entryable_type == "Message"
152
+ # Entry#message # => returns the message record, when entryable_type == "Message", otherwise nil
153
+ # Entry#message_id # => returns entryable_id, when entryable_type == "Message", otherwise nil
154
+ # Entry.comments # => Entry.where(entryable_type: "Comment")
155
+ # Entry#comment? # => true when entryable_type == "Comment"
156
+ # Entry#comment # => returns the comment record, when entryable_type == "Comment", otherwise nil
157
+ # Entry#comment_id # => returns entryable_id, when entryable_type == "Comment", otherwise nil
158
+ #
159
+ # The +options+ are passed directly to the +belongs_to+ call, so this is where you declare +dependent+ etc.
160
+ #
161
+ # You can also declare namespaced types:
162
+ #
163
+ # class Entry < ApplicationRecord
164
+ # delegated_type :entryable, types: %w[ Message Comment Access::NoticeMessage ], dependent: :destroy
165
+ # end
166
+ #
167
+ # Entry.access_notice_messages
168
+ # entry.access_notice_message
169
+ # entry.access_notice_message?
170
+ def delegated_type(role, types:, **options)
171
+ belongs_to role, options.delete(:scope), **options.merge(polymorphic: true)
172
+ define_delegated_type_methods role, types: types
173
+ end
174
+
175
+ private
176
+ def define_delegated_type_methods(role, types:)
177
+ role_type = "#{role}_type"
178
+ role_id = "#{role}_id"
179
+
180
+ define_method "#{role}_class" do
181
+ public_send("#{role}_type").constantize
182
+ end
183
+
184
+ define_method "#{role}_name" do
185
+ public_send("#{role}_class").model_name.singular.inquiry
186
+ end
187
+
188
+ types.each do |type|
189
+ scope_name = type.tableize.gsub("/", "_")
190
+ singular = scope_name.singularize
191
+ query = "#{singular}?"
192
+
193
+ scope scope_name, -> { where(role_type => type) }
194
+
195
+ define_method query do
196
+ public_send(role_type) == type
197
+ end
198
+
199
+ define_method singular do
200
+ public_send(role) if public_send(query)
201
+ end
202
+
203
+ define_method "#{singular}_id" do
204
+ public_send(role_id) if public_send(query)
205
+ end
206
+ end
207
+ end
208
+ end
209
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ class DestroyAssociationAsyncError < StandardError
5
+ end
6
+
7
+ # Job to destroy the records associated with a destroyed record in background.
8
+ class DestroyAssociationAsyncJob < ActiveJob::Base
9
+ queue_as { ActiveRecord::Base.queues[:destroy] }
10
+
11
+ discard_on ActiveJob::DeserializationError
12
+
13
+ def perform(
14
+ owner_model_name: nil, owner_id: nil,
15
+ association_class: nil, association_ids: nil, association_primary_key_column: nil,
16
+ ensuring_owner_was_method: nil
17
+ )
18
+ association_model = association_class.constantize
19
+ owner_class = owner_model_name.constantize
20
+ owner = owner_class.find_by(owner_class.primary_key.to_sym => owner_id)
21
+
22
+ if !owner_destroyed?(owner, ensuring_owner_was_method)
23
+ raise DestroyAssociationAsyncError, "owner record not destroyed"
24
+ end
25
+
26
+ association_model.where(association_primary_key_column => association_ids).find_each do |r|
27
+ r.destroy
28
+ end
29
+ end
30
+
31
+ private
32
+ def owner_destroyed?(owner, ensuring_owner_was_method)
33
+ !owner || (ensuring_owner_was_method && owner.public_send(ensuring_owner_was_method))
34
+ end
35
+ end
36
+ end
@@ -41,13 +41,20 @@ module ActiveRecord
41
41
  # Conversation.where(status: [:active, :archived])
42
42
  # Conversation.where.not(status: :active)
43
43
  #
44
- # You can set the default value from the database declaration, like:
44
+ # Defining scopes can be disabled by setting +:_scopes+ to +false+.
45
45
  #
46
- # create_table :conversations do |t|
47
- # t.column :status, :integer, default: 0
46
+ # class Conversation < ActiveRecord::Base
47
+ # enum status: [ :active, :archived ], _scopes: false
48
+ # end
49
+ #
50
+ # You can set the default enum value by setting +:_default+, like:
51
+ #
52
+ # class Conversation < ActiveRecord::Base
53
+ # enum status: [ :active, :archived ], _default: "active"
48
54
  # end
49
55
  #
50
- # Good practice is to let the first declared status be the default.
56
+ # conversation = Conversation.new
57
+ # conversation.status # => "active"
51
58
  #
52
59
  # Finally, it's also possible to explicitly map the relation between attribute and
53
60
  # database integer with a hash:
@@ -117,28 +124,31 @@ module ActiveRecord
117
124
  end
118
125
 
119
126
  def cast(value)
120
- return if value.blank?
121
-
122
127
  if mapping.has_key?(value)
123
128
  value.to_s
124
129
  elsif mapping.has_value?(value)
125
130
  mapping.key(value)
131
+ elsif value.blank?
132
+ nil
126
133
  else
127
134
  assert_valid_value(value)
128
135
  end
129
136
  end
130
137
 
131
138
  def deserialize(value)
132
- return if value.nil?
133
139
  mapping.key(subtype.deserialize(value))
134
140
  end
135
141
 
142
+ def serializable?(value)
143
+ (value.blank? || mapping.has_key?(value) || mapping.has_value?(value)) && super
144
+ end
145
+
136
146
  def serialize(value)
137
147
  mapping.fetch(value, value)
138
148
  end
139
149
 
140
150
  def assert_valid_value(value)
141
- unless value.blank? || mapping.has_key?(value) || mapping.has_value?(value)
151
+ unless serializable?(value)
142
152
  raise ArgumentError, "'#{value}' is not a valid #{name}"
143
153
  end
144
154
  end
@@ -148,10 +158,13 @@ module ActiveRecord
148
158
  end
149
159
 
150
160
  def enum(definitions)
151
- klass = self
152
161
  enum_prefix = definitions.delete(:_prefix)
153
162
  enum_suffix = definitions.delete(:_suffix)
154
163
  enum_scopes = definitions.delete(:_scopes)
164
+
165
+ default = {}
166
+ default[:default] = definitions.delete(:_default) if definitions.key?(:_default)
167
+
155
168
  definitions.each do |name, values|
156
169
  assert_valid_enum_definition_values(values)
157
170
  # statuses = { }
@@ -167,57 +180,82 @@ module ActiveRecord
167
180
  detect_enum_conflict!(name, "#{name}=")
168
181
 
169
182
  attr = attribute_alias?(name) ? attribute_alias(name) : name
170
- decorate_attribute_type(attr, :enum) do |subtype|
183
+
184
+ decorate_attribute_type(attr, **default) do |subtype|
171
185
  EnumType.new(attr, enum_values, subtype)
172
186
  end
173
187
 
188
+ value_method_names = []
174
189
  _enum_methods_module.module_eval do
190
+ prefix = if enum_prefix == true
191
+ "#{name}_"
192
+ elsif enum_prefix
193
+ "#{enum_prefix}_"
194
+ end
195
+
196
+ suffix = if enum_suffix == true
197
+ "_#{name}"
198
+ elsif enum_suffix
199
+ "_#{enum_suffix}"
200
+ end
201
+
175
202
  pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
176
203
  pairs.each do |label, value|
177
- if enum_prefix == true
178
- prefix = "#{name}_"
179
- elsif enum_prefix
180
- prefix = "#{enum_prefix}_"
181
- end
182
- if enum_suffix == true
183
- suffix = "_#{name}"
184
- elsif enum_suffix
185
- suffix = "_#{enum_suffix}"
186
- end
187
-
188
- value_method_name = "#{prefix}#{label}#{suffix}"
189
204
  enum_values[label] = value
190
205
  label = label.to_s
191
206
 
192
- # def active?() status == "active" end
207
+ value_method_name = "#{prefix}#{label}#{suffix}"
208
+ value_method_names << value_method_name
209
+ define_enum_methods(name, value_method_name, value, enum_scopes)
210
+
211
+ method_friendly_label = label.gsub(/[\W&&[:ascii:]]+/, "_")
212
+ value_method_alias = "#{prefix}#{method_friendly_label}#{suffix}"
213
+
214
+ if value_method_alias != value_method_name && !value_method_names.include?(value_method_alias)
215
+ value_method_names << value_method_alias
216
+ define_enum_methods(name, value_method_alias, value, enum_scopes)
217
+ end
218
+ end
219
+ end
220
+ detect_negative_enum_conditions!(value_method_names) if enum_scopes != false
221
+ enum_values.freeze
222
+ end
223
+ end
224
+
225
+ private
226
+ class EnumMethods < Module # :nodoc:
227
+ def initialize(klass)
228
+ @klass = klass
229
+ end
230
+
231
+ private
232
+ attr_reader :klass
233
+
234
+ def define_enum_methods(name, value_method_name, value, enum_scopes)
235
+ # def active?() status_for_database == 0 end
193
236
  klass.send(:detect_enum_conflict!, name, "#{value_method_name}?")
194
- define_method("#{value_method_name}?") { self[attr] == label }
237
+ define_method("#{value_method_name}?") { public_send(:"#{name}_for_database") == value }
195
238
 
196
239
  # def active!() update!(status: 0) end
197
240
  klass.send(:detect_enum_conflict!, name, "#{value_method_name}!")
198
- define_method("#{value_method_name}!") { update!(attr => value) }
241
+ define_method("#{value_method_name}!") { update!(name => value) }
199
242
 
200
243
  # scope :active, -> { where(status: 0) }
201
244
  # scope :not_active, -> { where.not(status: 0) }
202
245
  if enum_scopes != false
203
- klass.send(:detect_negative_condition!, value_method_name)
204
-
205
246
  klass.send(:detect_enum_conflict!, name, value_method_name, true)
206
- klass.scope value_method_name, -> { where(attr => value) }
247
+ klass.scope value_method_name, -> { where(name => value) }
207
248
 
208
249
  klass.send(:detect_enum_conflict!, name, "not_#{value_method_name}", true)
209
- klass.scope "not_#{value_method_name}", -> { where.not(attr => value) }
250
+ klass.scope "not_#{value_method_name}", -> { where.not(name => value) }
210
251
  end
211
252
  end
212
- end
213
- enum_values.freeze
214
253
  end
215
- end
254
+ private_constant :EnumMethods
216
255
 
217
- private
218
256
  def _enum_methods_module
219
257
  @_enum_methods_module ||= begin
220
- mod = Module.new
258
+ mod = EnumMethods.new(self)
221
259
  include mod
222
260
  mod
223
261
  end
@@ -264,10 +302,16 @@ module ActiveRecord
264
302
  }
265
303
  end
266
304
 
267
- def detect_negative_condition!(method_name)
268
- if method_name.start_with?("not_") && logger
269
- logger.warn "An enum element in #{self.name} uses the prefix 'not_'." \
270
- " This will cause a conflict with auto generated negative scopes."
305
+ def detect_negative_enum_conditions!(method_names)
306
+ return unless logger
307
+
308
+ method_names.select { |m| m.start_with?("not_") }.each do |potential_not|
309
+ inverted_form = potential_not.sub("not_", "")
310
+ if method_names.include?(inverted_form)
311
+ logger.warn "Enum element '#{potential_not}' in #{self.name} uses the prefix 'not_'." \
312
+ " This has caused a conflict with auto generated negative scopes." \
313
+ " Avoid using enum elements starting with 'not' where the positive form is also an element."
314
+ end
271
315
  end
272
316
  end
273
317
  end