sskirby-activerecord 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. data/CHANGELOG.md +6749 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.rdoc +222 -0
  4. data/examples/associations.png +0 -0
  5. data/examples/performance.rb +177 -0
  6. data/examples/simple.rb +14 -0
  7. data/lib/active_record.rb +147 -0
  8. data/lib/active_record/aggregations.rb +255 -0
  9. data/lib/active_record/associations.rb +1604 -0
  10. data/lib/active_record/associations/alias_tracker.rb +79 -0
  11. data/lib/active_record/associations/association.rb +239 -0
  12. data/lib/active_record/associations/association_scope.rb +119 -0
  13. data/lib/active_record/associations/belongs_to_association.rb +79 -0
  14. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +34 -0
  15. data/lib/active_record/associations/builder/association.rb +55 -0
  16. data/lib/active_record/associations/builder/belongs_to.rb +85 -0
  17. data/lib/active_record/associations/builder/collection_association.rb +75 -0
  18. data/lib/active_record/associations/builder/has_and_belongs_to_many.rb +57 -0
  19. data/lib/active_record/associations/builder/has_many.rb +71 -0
  20. data/lib/active_record/associations/builder/has_one.rb +62 -0
  21. data/lib/active_record/associations/builder/singular_association.rb +32 -0
  22. data/lib/active_record/associations/collection_association.rb +574 -0
  23. data/lib/active_record/associations/collection_proxy.rb +132 -0
  24. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +62 -0
  25. data/lib/active_record/associations/has_many_association.rb +108 -0
  26. data/lib/active_record/associations/has_many_through_association.rb +180 -0
  27. data/lib/active_record/associations/has_one_association.rb +73 -0
  28. data/lib/active_record/associations/has_one_through_association.rb +36 -0
  29. data/lib/active_record/associations/join_dependency.rb +214 -0
  30. data/lib/active_record/associations/join_dependency/join_association.rb +154 -0
  31. data/lib/active_record/associations/join_dependency/join_base.rb +24 -0
  32. data/lib/active_record/associations/join_dependency/join_part.rb +78 -0
  33. data/lib/active_record/associations/join_helper.rb +55 -0
  34. data/lib/active_record/associations/preloader.rb +177 -0
  35. data/lib/active_record/associations/preloader/association.rb +127 -0
  36. data/lib/active_record/associations/preloader/belongs_to.rb +17 -0
  37. data/lib/active_record/associations/preloader/collection_association.rb +24 -0
  38. data/lib/active_record/associations/preloader/has_and_belongs_to_many.rb +60 -0
  39. data/lib/active_record/associations/preloader/has_many.rb +17 -0
  40. data/lib/active_record/associations/preloader/has_many_through.rb +15 -0
  41. data/lib/active_record/associations/preloader/has_one.rb +23 -0
  42. data/lib/active_record/associations/preloader/has_one_through.rb +9 -0
  43. data/lib/active_record/associations/preloader/singular_association.rb +21 -0
  44. data/lib/active_record/associations/preloader/through_association.rb +67 -0
  45. data/lib/active_record/associations/singular_association.rb +64 -0
  46. data/lib/active_record/associations/through_association.rb +83 -0
  47. data/lib/active_record/attribute_assignment.rb +221 -0
  48. data/lib/active_record/attribute_methods.rb +272 -0
  49. data/lib/active_record/attribute_methods/before_type_cast.rb +31 -0
  50. data/lib/active_record/attribute_methods/deprecated_underscore_read.rb +32 -0
  51. data/lib/active_record/attribute_methods/dirty.rb +101 -0
  52. data/lib/active_record/attribute_methods/primary_key.rb +114 -0
  53. data/lib/active_record/attribute_methods/query.rb +39 -0
  54. data/lib/active_record/attribute_methods/read.rb +135 -0
  55. data/lib/active_record/attribute_methods/serialization.rb +93 -0
  56. data/lib/active_record/attribute_methods/time_zone_conversion.rb +62 -0
  57. data/lib/active_record/attribute_methods/write.rb +69 -0
  58. data/lib/active_record/autosave_association.rb +422 -0
  59. data/lib/active_record/base.rb +716 -0
  60. data/lib/active_record/callbacks.rb +275 -0
  61. data/lib/active_record/coders/yaml_column.rb +41 -0
  62. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +452 -0
  63. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +188 -0
  64. data/lib/active_record/connection_adapters/abstract/database_limits.rb +58 -0
  65. data/lib/active_record/connection_adapters/abstract/database_statements.rb +388 -0
  66. data/lib/active_record/connection_adapters/abstract/query_cache.rb +82 -0
  67. data/lib/active_record/connection_adapters/abstract/quoting.rb +115 -0
  68. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +492 -0
  69. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +598 -0
  70. data/lib/active_record/connection_adapters/abstract_adapter.rb +296 -0
  71. data/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +653 -0
  72. data/lib/active_record/connection_adapters/column.rb +270 -0
  73. data/lib/active_record/connection_adapters/mysql2_adapter.rb +288 -0
  74. data/lib/active_record/connection_adapters/mysql_adapter.rb +426 -0
  75. data/lib/active_record/connection_adapters/postgresql_adapter.rb +1261 -0
  76. data/lib/active_record/connection_adapters/schema_cache.rb +50 -0
  77. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +55 -0
  78. data/lib/active_record/connection_adapters/sqlite_adapter.rb +577 -0
  79. data/lib/active_record/connection_adapters/statement_pool.rb +40 -0
  80. data/lib/active_record/counter_cache.rb +119 -0
  81. data/lib/active_record/dynamic_finder_match.rb +56 -0
  82. data/lib/active_record/dynamic_matchers.rb +79 -0
  83. data/lib/active_record/dynamic_scope_match.rb +23 -0
  84. data/lib/active_record/errors.rb +195 -0
  85. data/lib/active_record/explain.rb +85 -0
  86. data/lib/active_record/explain_subscriber.rb +21 -0
  87. data/lib/active_record/fixtures.rb +906 -0
  88. data/lib/active_record/fixtures/file.rb +65 -0
  89. data/lib/active_record/identity_map.rb +156 -0
  90. data/lib/active_record/inheritance.rb +167 -0
  91. data/lib/active_record/integration.rb +49 -0
  92. data/lib/active_record/locale/en.yml +40 -0
  93. data/lib/active_record/locking/optimistic.rb +183 -0
  94. data/lib/active_record/locking/pessimistic.rb +77 -0
  95. data/lib/active_record/log_subscriber.rb +68 -0
  96. data/lib/active_record/migration.rb +765 -0
  97. data/lib/active_record/migration/command_recorder.rb +105 -0
  98. data/lib/active_record/model_schema.rb +366 -0
  99. data/lib/active_record/nested_attributes.rb +469 -0
  100. data/lib/active_record/observer.rb +121 -0
  101. data/lib/active_record/persistence.rb +372 -0
  102. data/lib/active_record/query_cache.rb +74 -0
  103. data/lib/active_record/querying.rb +58 -0
  104. data/lib/active_record/railtie.rb +119 -0
  105. data/lib/active_record/railties/console_sandbox.rb +6 -0
  106. data/lib/active_record/railties/controller_runtime.rb +49 -0
  107. data/lib/active_record/railties/databases.rake +620 -0
  108. data/lib/active_record/railties/jdbcmysql_error.rb +16 -0
  109. data/lib/active_record/readonly_attributes.rb +26 -0
  110. data/lib/active_record/reflection.rb +534 -0
  111. data/lib/active_record/relation.rb +534 -0
  112. data/lib/active_record/relation/batches.rb +90 -0
  113. data/lib/active_record/relation/calculations.rb +354 -0
  114. data/lib/active_record/relation/delegation.rb +49 -0
  115. data/lib/active_record/relation/finder_methods.rb +398 -0
  116. data/lib/active_record/relation/predicate_builder.rb +58 -0
  117. data/lib/active_record/relation/query_methods.rb +417 -0
  118. data/lib/active_record/relation/spawn_methods.rb +148 -0
  119. data/lib/active_record/result.rb +34 -0
  120. data/lib/active_record/sanitization.rb +194 -0
  121. data/lib/active_record/schema.rb +58 -0
  122. data/lib/active_record/schema_dumper.rb +204 -0
  123. data/lib/active_record/scoping.rb +152 -0
  124. data/lib/active_record/scoping/default.rb +142 -0
  125. data/lib/active_record/scoping/named.rb +202 -0
  126. data/lib/active_record/serialization.rb +18 -0
  127. data/lib/active_record/serializers/xml_serializer.rb +202 -0
  128. data/lib/active_record/session_store.rb +358 -0
  129. data/lib/active_record/store.rb +50 -0
  130. data/lib/active_record/test_case.rb +73 -0
  131. data/lib/active_record/timestamp.rb +113 -0
  132. data/lib/active_record/transactions.rb +360 -0
  133. data/lib/active_record/translation.rb +22 -0
  134. data/lib/active_record/validations.rb +83 -0
  135. data/lib/active_record/validations/associated.rb +43 -0
  136. data/lib/active_record/validations/uniqueness.rb +180 -0
  137. data/lib/active_record/version.rb +10 -0
  138. data/lib/rails/generators/active_record.rb +25 -0
  139. data/lib/rails/generators/active_record/migration.rb +15 -0
  140. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  141. data/lib/rails/generators/active_record/migration/templates/migration.rb +31 -0
  142. data/lib/rails/generators/active_record/model/model_generator.rb +43 -0
  143. data/lib/rails/generators/active_record/model/templates/migration.rb +15 -0
  144. data/lib/rails/generators/active_record/model/templates/model.rb +7 -0
  145. data/lib/rails/generators/active_record/model/templates/module.rb +7 -0
  146. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  147. data/lib/rails/generators/active_record/observer/templates/observer.rb +4 -0
  148. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +25 -0
  149. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +12 -0
  150. metadata +242 -0
@@ -0,0 +1,275 @@
1
+ require 'active_support/core_ext/array/wrap'
2
+
3
+ module ActiveRecord
4
+ # = Active Record Callbacks
5
+ #
6
+ # Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
7
+ # before or after an alteration of the object state. This can be used to make sure that associated and
8
+ # dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
9
+ # before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
10
+ # the <tt>Base#save</tt> call for a new record:
11
+ #
12
+ # * (-) <tt>save</tt>
13
+ # * (-) <tt>valid</tt>
14
+ # * (1) <tt>before_validation</tt>
15
+ # * (-) <tt>validate</tt>
16
+ # * (2) <tt>after_validation</tt>
17
+ # * (3) <tt>before_save</tt>
18
+ # * (4) <tt>before_create</tt>
19
+ # * (-) <tt>create</tt>
20
+ # * (5) <tt>after_create</tt>
21
+ # * (6) <tt>after_save</tt>
22
+ # * (7) <tt>after_commit</tt>
23
+ #
24
+ # Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
25
+ # Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
26
+ # <tt>after_rollback</tt>.
27
+ #
28
+ # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
29
+ # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
30
+ # are instantiated as well.
31
+ #
32
+ # That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
33
+ # Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
34
+ # except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
35
+ #
36
+ # Examples:
37
+ # class CreditCard < ActiveRecord::Base
38
+ # # Strip everything but digits, so the user can specify "555 234 34" or
39
+ # # "5552-3434" or both will mean "55523434"
40
+ # before_validation(:on => :create) do
41
+ # self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
42
+ # end
43
+ # end
44
+ #
45
+ # class Subscription < ActiveRecord::Base
46
+ # before_create :record_signup
47
+ #
48
+ # private
49
+ # def record_signup
50
+ # self.signed_up_on = Date.today
51
+ # end
52
+ # end
53
+ #
54
+ # class Firm < ActiveRecord::Base
55
+ # # Destroys the associated clients and people when the firm is destroyed
56
+ # before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
57
+ # before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
58
+ # end
59
+ #
60
+ # == Inheritable callback queues
61
+ #
62
+ # Besides the overwritable callback methods, it's also possible to register callbacks through the
63
+ # use of the callback macros. Their main advantage is that the macros add behavior into a callback
64
+ # queue that is kept intact down through an inheritance hierarchy.
65
+ #
66
+ # class Topic < ActiveRecord::Base
67
+ # before_destroy :destroy_author
68
+ # end
69
+ #
70
+ # class Reply < Topic
71
+ # before_destroy :destroy_readers
72
+ # end
73
+ #
74
+ # Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
75
+ # run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
76
+ # where the +before_destroy+ method is overridden:
77
+ #
78
+ # class Topic < ActiveRecord::Base
79
+ # def before_destroy() destroy_author end
80
+ # end
81
+ #
82
+ # class Reply < Topic
83
+ # def before_destroy() destroy_readers end
84
+ # end
85
+ #
86
+ # In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
87
+ # So, use the callback macros when you want to ensure that a certain callback is called for the entire
88
+ # hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
89
+ # to decide whether they want to call +super+ and trigger the inherited callbacks.
90
+ #
91
+ # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
92
+ # callbacks before specifying the associations. Otherwise, you might trigger the loading of a
93
+ # child before the parent has registered the callbacks and they won't be inherited.
94
+ #
95
+ # == Types of callbacks
96
+ #
97
+ # There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
98
+ # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
99
+ # are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
100
+ # creating mix-ins), and inline eval methods are deprecated.
101
+ #
102
+ # The method reference callbacks work by specifying a protected or private method available in the object, like this:
103
+ #
104
+ # class Topic < ActiveRecord::Base
105
+ # before_destroy :delete_parents
106
+ #
107
+ # private
108
+ # def delete_parents
109
+ # self.class.delete_all "parent_id = #{id}"
110
+ # end
111
+ # end
112
+ #
113
+ # The callback objects have methods named after the callback called with the record as the only parameter, such as:
114
+ #
115
+ # class BankAccount < ActiveRecord::Base
116
+ # before_save EncryptionWrapper.new
117
+ # after_save EncryptionWrapper.new
118
+ # after_initialize EncryptionWrapper.new
119
+ # end
120
+ #
121
+ # class EncryptionWrapper
122
+ # def before_save(record)
123
+ # record.credit_card_number = encrypt(record.credit_card_number)
124
+ # end
125
+ #
126
+ # def after_save(record)
127
+ # record.credit_card_number = decrypt(record.credit_card_number)
128
+ # end
129
+ #
130
+ # alias_method :after_find, :after_save
131
+ #
132
+ # private
133
+ # def encrypt(value)
134
+ # # Secrecy is committed
135
+ # end
136
+ #
137
+ # def decrypt(value)
138
+ # # Secrecy is unveiled
139
+ # end
140
+ # end
141
+ #
142
+ # So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
143
+ # a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
144
+ # initialization data such as the name of the attribute to work with:
145
+ #
146
+ # class BankAccount < ActiveRecord::Base
147
+ # before_save EncryptionWrapper.new("credit_card_number")
148
+ # after_save EncryptionWrapper.new("credit_card_number")
149
+ # after_initialize EncryptionWrapper.new("credit_card_number")
150
+ # end
151
+ #
152
+ # class EncryptionWrapper
153
+ # def initialize(attribute)
154
+ # @attribute = attribute
155
+ # end
156
+ #
157
+ # def before_save(record)
158
+ # record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
159
+ # end
160
+ #
161
+ # def after_save(record)
162
+ # record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
163
+ # end
164
+ #
165
+ # alias_method :after_find, :after_save
166
+ #
167
+ # private
168
+ # def encrypt(value)
169
+ # # Secrecy is committed
170
+ # end
171
+ #
172
+ # def decrypt(value)
173
+ # # Secrecy is unveiled
174
+ # end
175
+ # end
176
+ #
177
+ # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
178
+ # pass a "method string", which will then be evaluated within the binding of the callback. Example:
179
+ #
180
+ # class Topic < ActiveRecord::Base
181
+ # before_destroy 'self.class.delete_all "parent_id = #{id}"'
182
+ # end
183
+ #
184
+ # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
185
+ # is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
186
+ #
187
+ # class Topic < ActiveRecord::Base
188
+ # before_destroy 'self.class.delete_all "parent_id = #{id}"',
189
+ # 'puts "Evaluated after parents are destroyed"'
190
+ # end
191
+ #
192
+ # == <tt>before_validation*</tt> returning statements
193
+ #
194
+ # If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
195
+ # aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
196
+ # ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
197
+ #
198
+ # == Canceling callbacks
199
+ #
200
+ # If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
201
+ # cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
202
+ # Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
203
+ # methods on the model, which are called last.
204
+ #
205
+ # == Transactions
206
+ #
207
+ # The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
208
+ # within a transaction. That includes <tt>after_*</tt> hooks. If everything
209
+ # goes fine a COMMIT is executed once the chain has been completed.
210
+ #
211
+ # If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
212
+ # can also trigger a ROLLBACK raising an exception in any of the callbacks,
213
+ # including <tt>after_*</tt> hooks. Note, however, that in that case the client
214
+ # needs to be aware of it because an ordinary +save+ will raise such exception
215
+ # instead of quietly returning +false+.
216
+ #
217
+ # == Debugging callbacks
218
+ #
219
+ # The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
220
+ # <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
221
+ # defines what part of the chain the callback runs in.
222
+ #
223
+ # To find all callbacks in the before_save callback chain:
224
+ #
225
+ # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
226
+ #
227
+ # Returns an array of callback objects that form the before_save chain.
228
+ #
229
+ # To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
230
+ #
231
+ # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
232
+ #
233
+ # Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
234
+ #
235
+ module Callbacks
236
+ extend ActiveSupport::Concern
237
+
238
+ CALLBACKS = [
239
+ :after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
240
+ :before_save, :around_save, :after_save, :before_create, :around_create,
241
+ :after_create, :before_update, :around_update, :after_update,
242
+ :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
243
+ ]
244
+
245
+ included do
246
+ extend ActiveModel::Callbacks
247
+ include ActiveModel::Validations::Callbacks
248
+
249
+ define_model_callbacks :initialize, :find, :touch, :only => :after
250
+ define_model_callbacks :save, :create, :update, :destroy
251
+ end
252
+
253
+ def destroy #:nodoc:
254
+ run_callbacks(:destroy) { super }
255
+ end
256
+
257
+ def touch(*) #:nodoc:
258
+ run_callbacks(:touch) { super }
259
+ end
260
+
261
+ private
262
+
263
+ def create_or_update #:nodoc:
264
+ run_callbacks(:save) { super }
265
+ end
266
+
267
+ def create #:nodoc:
268
+ run_callbacks(:create) { super }
269
+ end
270
+
271
+ def update(*) #:nodoc:
272
+ run_callbacks(:update) { super }
273
+ end
274
+ end
275
+ end
@@ -0,0 +1,41 @@
1
+ module ActiveRecord
2
+ # :stopdoc:
3
+ module Coders
4
+ class YAMLColumn
5
+ RESCUE_ERRORS = [ ArgumentError ]
6
+
7
+ if defined?(Psych) && defined?(Psych::SyntaxError)
8
+ RESCUE_ERRORS << Psych::SyntaxError
9
+ end
10
+
11
+ attr_accessor :object_class
12
+
13
+ def initialize(object_class = Object)
14
+ @object_class = object_class
15
+ end
16
+
17
+ def dump(obj)
18
+ YAML.dump obj
19
+ end
20
+
21
+ def load(yaml)
22
+ return object_class.new if object_class != Object && yaml.nil?
23
+ return yaml unless yaml.is_a?(String) && yaml =~ /^---/
24
+ begin
25
+ obj = YAML.load(yaml)
26
+
27
+ unless obj.is_a?(object_class) || obj.nil?
28
+ raise SerializationTypeMismatch,
29
+ "Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
30
+ end
31
+ obj ||= object_class.new if object_class != Object
32
+
33
+ obj
34
+ rescue *RESCUE_ERRORS
35
+ yaml
36
+ end
37
+ end
38
+ end
39
+ end
40
+ # :startdoc
41
+ end
@@ -0,0 +1,452 @@
1
+ require 'thread'
2
+ require 'monitor'
3
+ require 'set'
4
+ require 'active_support/core_ext/module/deprecation'
5
+
6
+ module ActiveRecord
7
+ # Raised when a connection could not be obtained within the connection
8
+ # acquisition timeout period.
9
+ class ConnectionTimeoutError < ConnectionNotEstablished
10
+ end
11
+
12
+ module ConnectionAdapters
13
+ # Connection pool base class for managing Active Record database
14
+ # connections.
15
+ #
16
+ # == Introduction
17
+ #
18
+ # A connection pool synchronizes thread access to a limited number of
19
+ # database connections. The basic idea is that each thread checks out a
20
+ # database connection from the pool, uses that connection, and checks the
21
+ # connection back in. ConnectionPool is completely thread-safe, and will
22
+ # ensure that a connection cannot be used by two threads at the same time,
23
+ # as long as ConnectionPool's contract is correctly followed. It will also
24
+ # handle cases in which there are more threads than connections: if all
25
+ # connections have been checked out, and a thread tries to checkout a
26
+ # connection anyway, then ConnectionPool will wait until some other thread
27
+ # has checked in a connection.
28
+ #
29
+ # == Obtaining (checking out) a connection
30
+ #
31
+ # Connections can be obtained and used from a connection pool in several
32
+ # ways:
33
+ #
34
+ # 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
35
+ # earlier (pre-connection-pooling). Eventually, when you're done with
36
+ # the connection(s) and wish it to be returned to the pool, you call
37
+ # ActiveRecord::Base.clear_active_connections!. This will be the
38
+ # default behavior for Active Record when used in conjunction with
39
+ # Action Pack's request handling cycle.
40
+ # 2. Manually check out a connection from the pool with
41
+ # ActiveRecord::Base.connection_pool.checkout. You are responsible for
42
+ # returning this connection to the pool when finished by calling
43
+ # ActiveRecord::Base.connection_pool.checkin(connection).
44
+ # 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
45
+ # obtains a connection, yields it as the sole argument to the block,
46
+ # and returns it to the pool after the block completes.
47
+ #
48
+ # Connections in the pool are actually AbstractAdapter objects (or objects
49
+ # compatible with AbstractAdapter's interface).
50
+ #
51
+ # == Options
52
+ #
53
+ # There are two connection-pooling-related options that you can add to
54
+ # your database connection configuration:
55
+ #
56
+ # * +pool+: number indicating size of connection pool (default 5)
57
+ # * +wait_timeout+: number of seconds to block and wait for a connection
58
+ # before giving up and raising a timeout error (default 5 seconds).
59
+ class ConnectionPool
60
+ include MonitorMixin
61
+
62
+ attr_accessor :automatic_reconnect
63
+ attr_reader :spec, :connections
64
+
65
+ # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
66
+ # object which describes database connection information (e.g. adapter,
67
+ # host name, username, password, etc), as well as the maximum size for
68
+ # this ConnectionPool.
69
+ #
70
+ # The default ConnectionPool maximum size is 5.
71
+ def initialize(spec)
72
+ super()
73
+
74
+ @spec = spec
75
+
76
+ # The cache of reserved connections mapped to threads
77
+ @reserved_connections = {}
78
+
79
+ @queue = new_cond
80
+ @timeout = spec.config[:wait_timeout] || 5
81
+
82
+ # default max pool size to 5
83
+ @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
84
+
85
+ @connections = []
86
+ @automatic_reconnect = true
87
+ end
88
+
89
+ # Retrieve the connection associated with the current thread, or call
90
+ # #checkout to obtain one if necessary.
91
+ #
92
+ # #connection can be called any number of times; the connection is
93
+ # held in a hash keyed by the thread id.
94
+ def connection
95
+ @reserved_connections[current_connection_id] ||= checkout
96
+ end
97
+
98
+ # Check to see if there is an active connection in this connection
99
+ # pool.
100
+ def active_connection?
101
+ active_connections.any?
102
+ end
103
+
104
+ # Signal that the thread is finished with the current connection.
105
+ # #release_connection releases the connection-thread association
106
+ # and returns the connection to the pool.
107
+ def release_connection(with_id = current_connection_id)
108
+ conn = @reserved_connections.delete(with_id)
109
+ checkin conn if conn
110
+ end
111
+
112
+ # If a connection already exists yield it to the block. If no connection
113
+ # exists checkout a connection, yield it to the block, and checkin the
114
+ # connection when finished.
115
+ def with_connection
116
+ connection_id = current_connection_id
117
+ fresh_connection = true unless active_connection?
118
+ yield connection
119
+ ensure
120
+ release_connection(connection_id) if fresh_connection
121
+ end
122
+
123
+ # Returns true if a connection has already been opened.
124
+ def connected?
125
+ synchronize { @connections.any? }
126
+ end
127
+
128
+ # Disconnects all connections in the pool, and clears the pool.
129
+ def disconnect!
130
+ synchronize do
131
+ @reserved_connections = {}
132
+ @connections.each do |conn|
133
+ checkin conn
134
+ conn.disconnect!
135
+ end
136
+ @connections = []
137
+ end
138
+ end
139
+
140
+ # Clears the cache which maps classes.
141
+ def clear_reloadable_connections!
142
+ synchronize do
143
+ @reserved_connections = {}
144
+ @connections.each do |conn|
145
+ checkin conn
146
+ conn.disconnect! if conn.requires_reloading?
147
+ end
148
+ @connections.delete_if do |conn|
149
+ conn.requires_reloading?
150
+ end
151
+ end
152
+ end
153
+
154
+ # Verify active connections and remove and disconnect connections
155
+ # associated with stale threads.
156
+ def verify_active_connections! #:nodoc:
157
+ synchronize do
158
+ clear_stale_cached_connections!
159
+ @connections.each do |connection|
160
+ connection.verify!
161
+ end
162
+ end
163
+ end
164
+
165
+ def columns
166
+ with_connection do |c|
167
+ c.schema_cache.columns
168
+ end
169
+ end
170
+ deprecate :columns
171
+
172
+ def columns_hash
173
+ with_connection do |c|
174
+ c.schema_cache.columns_hash
175
+ end
176
+ end
177
+ deprecate :columns_hash
178
+
179
+ def primary_keys
180
+ with_connection do |c|
181
+ c.schema_cache.primary_keys
182
+ end
183
+ end
184
+ deprecate :primary_keys
185
+
186
+ def clear_cache!
187
+ with_connection do |c|
188
+ c.schema_cache.clear!
189
+ end
190
+ end
191
+ deprecate :clear_cache!
192
+
193
+ # Return any checked-out connections back to the pool by threads that
194
+ # are no longer alive.
195
+ def clear_stale_cached_connections!
196
+ keys = @reserved_connections.keys - Thread.list.find_all { |t|
197
+ t.alive?
198
+ }.map { |thread| thread.object_id }
199
+ keys.each do |key|
200
+ conn = @reserved_connections[key]
201
+ ActiveSupport::Deprecation.warn(<<-eowarn) if conn.in_use?
202
+ Database connections will not be closed automatically, please close your
203
+ database connection at the end of the thread by calling `close` on your
204
+ connection. For example: ActiveRecord::Base.connection.close
205
+ eowarn
206
+ checkin conn
207
+ @reserved_connections.delete(key)
208
+ end
209
+ end
210
+
211
+ # Check-out a database connection from the pool, indicating that you want
212
+ # to use it. You should call #checkin when you no longer need this.
213
+ #
214
+ # This is done by either returning an existing connection, or by creating
215
+ # a new connection. If the maximum number of connections for this pool has
216
+ # already been reached, but the pool is empty (i.e. they're all being used),
217
+ # then this method will wait until a thread has checked in a connection.
218
+ # The wait time is bounded however: if no connection can be checked out
219
+ # within the timeout specified for this pool, then a ConnectionTimeoutError
220
+ # exception will be raised.
221
+ #
222
+ # Returns: an AbstractAdapter object.
223
+ #
224
+ # Raises:
225
+ # - ConnectionTimeoutError: no connection can be obtained from the pool
226
+ # within the timeout period.
227
+ def checkout
228
+ # Checkout an available connection
229
+ synchronize do
230
+ loop do
231
+ conn = @connections.find { |c| c.lease }
232
+
233
+ unless conn
234
+ if @connections.size < @size
235
+ conn = checkout_new_connection
236
+ conn.lease
237
+ end
238
+ end
239
+
240
+ if conn
241
+ checkout_and_verify conn
242
+ return conn
243
+ end
244
+
245
+ @queue.wait(@timeout)
246
+
247
+ if(active_connections.size < @connections.size)
248
+ next
249
+ else
250
+ clear_stale_cached_connections!
251
+ if @size == active_connections.size
252
+ raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
253
+ end
254
+ end
255
+
256
+ end
257
+ end
258
+ end
259
+
260
+ # Check-in a database connection back into the pool, indicating that you
261
+ # no longer need this connection.
262
+ #
263
+ # +conn+: an AbstractAdapter object, which was obtained by earlier by
264
+ # calling +checkout+ on this pool.
265
+ def checkin(conn)
266
+ synchronize do
267
+ conn.run_callbacks :checkin do
268
+ conn.expire
269
+ @queue.signal
270
+ end
271
+ end
272
+ end
273
+
274
+ private
275
+
276
+ def new_connection
277
+ ActiveRecord::Base.send(spec.adapter_method, spec.config)
278
+ end
279
+
280
+ def current_connection_id #:nodoc:
281
+ ActiveRecord::Base.connection_id ||= Thread.current.object_id
282
+ end
283
+
284
+ def checkout_new_connection
285
+ raise ConnectionNotEstablished unless @automatic_reconnect
286
+
287
+ c = new_connection
288
+ c.pool = self
289
+ @connections << c
290
+ c
291
+ end
292
+
293
+ def checkout_and_verify(c)
294
+ c.run_callbacks :checkout do
295
+ c.verify!
296
+ end
297
+ c
298
+ end
299
+
300
+ def active_connections
301
+ @connections.find_all { |c| c.in_use? }
302
+ end
303
+ end
304
+
305
+ # ConnectionHandler is a collection of ConnectionPool objects. It is used
306
+ # for keeping separate connection pools for Active Record models that connect
307
+ # to different databases.
308
+ #
309
+ # For example, suppose that you have 5 models, with the following hierarchy:
310
+ #
311
+ # |
312
+ # +-- Book
313
+ # | |
314
+ # | +-- ScaryBook
315
+ # | +-- GoodBook
316
+ # +-- Author
317
+ # +-- BankAccount
318
+ #
319
+ # Suppose that Book is to connect to a separate database (i.e. one other
320
+ # than the default database). Then Book, ScaryBook and GoodBook will all use
321
+ # the same connection pool. Likewise, Author and BankAccount will use the
322
+ # same connection pool. However, the connection pool used by Author/BankAccount
323
+ # is not the same as the one used by Book/ScaryBook/GoodBook.
324
+ #
325
+ # Normally there is only a single ConnectionHandler instance, accessible via
326
+ # ActiveRecord::Base.connection_handler. Active Record models use this to
327
+ # determine that connection pool that they should use.
328
+ class ConnectionHandler
329
+ attr_reader :connection_pools
330
+
331
+ def initialize(pools = {})
332
+ @connection_pools = pools
333
+ @class_to_pool = {}
334
+ end
335
+
336
+ def establish_connection(name, spec)
337
+ @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
338
+ @class_to_pool[name] = @connection_pools[spec]
339
+ end
340
+
341
+ # Returns true if there are any active connections among the connection
342
+ # pools that the ConnectionHandler is managing.
343
+ def active_connections?
344
+ connection_pools.values.any? { |pool| pool.active_connection? }
345
+ end
346
+
347
+ # Returns any connections in use by the current thread back to the pool,
348
+ # and also returns connections to the pool cached by threads that are no
349
+ # longer alive.
350
+ def clear_active_connections!
351
+ @connection_pools.each_value {|pool| pool.release_connection }
352
+ end
353
+
354
+ # Clears the cache which maps classes.
355
+ def clear_reloadable_connections!
356
+ @connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
357
+ end
358
+
359
+ def clear_all_connections!
360
+ @connection_pools.each_value {|pool| pool.disconnect! }
361
+ end
362
+
363
+ # Verify active connections.
364
+ def verify_active_connections! #:nodoc:
365
+ @connection_pools.each_value {|pool| pool.verify_active_connections! }
366
+ end
367
+
368
+ # Locate the connection of the nearest super class. This can be an
369
+ # active or defined connection: if it is the latter, it will be
370
+ # opened and set as the active connection for the class it was defined
371
+ # for (not necessarily the current class).
372
+ def retrieve_connection(klass) #:nodoc:
373
+ pool = retrieve_connection_pool(klass)
374
+ (pool && pool.connection) or raise ConnectionNotEstablished
375
+ end
376
+
377
+ # Returns true if a connection that's accessible to this class has
378
+ # already been opened.
379
+ def connected?(klass)
380
+ conn = retrieve_connection_pool(klass)
381
+ conn && conn.connected?
382
+ end
383
+
384
+ # Remove the connection for this class. This will close the active
385
+ # connection and the defined connection (if they exist). The result
386
+ # can be used as an argument for establish_connection, for easily
387
+ # re-establishing the connection.
388
+ def remove_connection(klass)
389
+ pool = @class_to_pool.delete(klass.name)
390
+ return nil unless pool
391
+
392
+ @connection_pools.delete pool.spec
393
+ pool.automatic_reconnect = false
394
+ pool.disconnect!
395
+ pool.spec.config
396
+ end
397
+
398
+ def retrieve_connection_pool(klass)
399
+ pool = @class_to_pool[klass.name]
400
+ return pool if pool
401
+ return nil if ActiveRecord::Base == klass
402
+ retrieve_connection_pool klass.superclass
403
+ end
404
+ end
405
+
406
+ class ConnectionManagement
407
+ class Proxy # :nodoc:
408
+ attr_reader :body, :testing
409
+
410
+ def initialize(body, testing = false)
411
+ @body = body
412
+ @testing = testing
413
+ end
414
+
415
+ def method_missing(method_sym, *arguments, &block)
416
+ @body.send(method_sym, *arguments, &block)
417
+ end
418
+
419
+ def respond_to?(method_sym, include_private = false)
420
+ super || @body.respond_to?(method_sym)
421
+ end
422
+
423
+ def each(&block)
424
+ body.each(&block)
425
+ end
426
+
427
+ def close
428
+ body.close if body.respond_to?(:close)
429
+
430
+ # Don't return connection (and perform implicit rollback) if
431
+ # this request is a part of integration test
432
+ ActiveRecord::Base.clear_active_connections! unless testing
433
+ end
434
+ end
435
+
436
+ def initialize(app)
437
+ @app = app
438
+ end
439
+
440
+ def call(env)
441
+ testing = env.key?('rack.test')
442
+
443
+ status, headers, body = @app.call(env)
444
+
445
+ [status, headers, Proxy.new(body, testing)]
446
+ rescue
447
+ ActiveRecord::Base.clear_active_connections! unless testing
448
+ raise
449
+ end
450
+ end
451
+ end
452
+ end