activerecord 1.0.0 → 3.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 (178) hide show
  1. data/CHANGELOG +5518 -76
  2. data/README.rdoc +222 -0
  3. data/examples/performance.rb +162 -0
  4. data/examples/simple.rb +14 -0
  5. data/lib/active_record/aggregations.rb +192 -80
  6. data/lib/active_record/association_preload.rb +403 -0
  7. data/lib/active_record/associations/association_collection.rb +545 -53
  8. data/lib/active_record/associations/association_proxy.rb +295 -0
  9. data/lib/active_record/associations/belongs_to_association.rb +91 -0
  10. data/lib/active_record/associations/belongs_to_polymorphic_association.rb +78 -0
  11. data/lib/active_record/associations/has_and_belongs_to_many_association.rb +127 -36
  12. data/lib/active_record/associations/has_many_association.rb +108 -84
  13. data/lib/active_record/associations/has_many_through_association.rb +116 -0
  14. data/lib/active_record/associations/has_one_association.rb +143 -0
  15. data/lib/active_record/associations/has_one_through_association.rb +40 -0
  16. data/lib/active_record/associations/through_association_scope.rb +154 -0
  17. data/lib/active_record/associations.rb +2086 -368
  18. data/lib/active_record/attribute_methods/before_type_cast.rb +33 -0
  19. data/lib/active_record/attribute_methods/dirty.rb +95 -0
  20. data/lib/active_record/attribute_methods/primary_key.rb +50 -0
  21. data/lib/active_record/attribute_methods/query.rb +39 -0
  22. data/lib/active_record/attribute_methods/read.rb +116 -0
  23. data/lib/active_record/attribute_methods/time_zone_conversion.rb +61 -0
  24. data/lib/active_record/attribute_methods/write.rb +37 -0
  25. data/lib/active_record/attribute_methods.rb +60 -0
  26. data/lib/active_record/autosave_association.rb +369 -0
  27. data/lib/active_record/base.rb +1603 -721
  28. data/lib/active_record/callbacks.rb +176 -225
  29. data/lib/active_record/connection_adapters/abstract/connection_pool.rb +365 -0
  30. data/lib/active_record/connection_adapters/abstract/connection_specification.rb +113 -0
  31. data/lib/active_record/connection_adapters/abstract/database_limits.rb +57 -0
  32. data/lib/active_record/connection_adapters/abstract/database_statements.rb +329 -0
  33. data/lib/active_record/connection_adapters/abstract/query_cache.rb +81 -0
  34. data/lib/active_record/connection_adapters/abstract/quoting.rb +72 -0
  35. data/lib/active_record/connection_adapters/abstract/schema_definitions.rb +739 -0
  36. data/lib/active_record/connection_adapters/abstract/schema_statements.rb +543 -0
  37. data/lib/active_record/connection_adapters/abstract_adapter.rb +165 -279
  38. data/lib/active_record/connection_adapters/mysql_adapter.rb +594 -82
  39. data/lib/active_record/connection_adapters/postgresql_adapter.rb +988 -135
  40. data/lib/active_record/connection_adapters/sqlite3_adapter.rb +53 -0
  41. data/lib/active_record/connection_adapters/sqlite_adapter.rb +365 -71
  42. data/lib/active_record/counter_cache.rb +115 -0
  43. data/lib/active_record/dynamic_finder_match.rb +53 -0
  44. data/lib/active_record/dynamic_scope_match.rb +32 -0
  45. data/lib/active_record/errors.rb +172 -0
  46. data/lib/active_record/fixtures.rb +941 -105
  47. data/lib/active_record/locale/en.yml +40 -0
  48. data/lib/active_record/locking/optimistic.rb +172 -0
  49. data/lib/active_record/locking/pessimistic.rb +55 -0
  50. data/lib/active_record/log_subscriber.rb +48 -0
  51. data/lib/active_record/migration.rb +617 -0
  52. data/lib/active_record/named_scope.rb +138 -0
  53. data/lib/active_record/nested_attributes.rb +417 -0
  54. data/lib/active_record/observer.rb +105 -36
  55. data/lib/active_record/persistence.rb +291 -0
  56. data/lib/active_record/query_cache.rb +36 -0
  57. data/lib/active_record/railtie.rb +91 -0
  58. data/lib/active_record/railties/controller_runtime.rb +38 -0
  59. data/lib/active_record/railties/databases.rake +512 -0
  60. data/lib/active_record/reflection.rb +364 -87
  61. data/lib/active_record/relation/batches.rb +89 -0
  62. data/lib/active_record/relation/calculations.rb +286 -0
  63. data/lib/active_record/relation/finder_methods.rb +355 -0
  64. data/lib/active_record/relation/predicate_builder.rb +41 -0
  65. data/lib/active_record/relation/query_methods.rb +261 -0
  66. data/lib/active_record/relation/spawn_methods.rb +112 -0
  67. data/lib/active_record/relation.rb +393 -0
  68. data/lib/active_record/schema.rb +59 -0
  69. data/lib/active_record/schema_dumper.rb +195 -0
  70. data/lib/active_record/serialization.rb +60 -0
  71. data/lib/active_record/serializers/xml_serializer.rb +244 -0
  72. data/lib/active_record/session_store.rb +340 -0
  73. data/lib/active_record/test_case.rb +67 -0
  74. data/lib/active_record/timestamp.rb +88 -0
  75. data/lib/active_record/transactions.rb +329 -75
  76. data/lib/active_record/validations/associated.rb +48 -0
  77. data/lib/active_record/validations/uniqueness.rb +185 -0
  78. data/lib/active_record/validations.rb +58 -179
  79. data/lib/active_record/version.rb +9 -0
  80. data/lib/active_record.rb +100 -24
  81. data/lib/rails/generators/active_record/migration/migration_generator.rb +25 -0
  82. data/lib/rails/generators/active_record/migration/templates/migration.rb +17 -0
  83. data/lib/rails/generators/active_record/model/model_generator.rb +38 -0
  84. data/lib/rails/generators/active_record/model/templates/migration.rb +16 -0
  85. data/lib/rails/generators/active_record/model/templates/model.rb +5 -0
  86. data/lib/rails/generators/active_record/model/templates/module.rb +5 -0
  87. data/lib/rails/generators/active_record/observer/observer_generator.rb +15 -0
  88. data/lib/rails/generators/active_record/observer/templates/observer.rb +2 -0
  89. data/lib/rails/generators/active_record/session_migration/session_migration_generator.rb +24 -0
  90. data/lib/rails/generators/active_record/session_migration/templates/migration.rb +16 -0
  91. data/lib/rails/generators/active_record.rb +27 -0
  92. metadata +216 -158
  93. data/README +0 -361
  94. data/RUNNING_UNIT_TESTS +0 -36
  95. data/dev-utils/eval_debugger.rb +0 -9
  96. data/examples/associations.rb +0 -87
  97. data/examples/shared_setup.rb +0 -15
  98. data/examples/validation.rb +0 -88
  99. data/install.rb +0 -60
  100. data/lib/active_record/deprecated_associations.rb +0 -70
  101. data/lib/active_record/support/class_attribute_accessors.rb +0 -43
  102. data/lib/active_record/support/class_inheritable_attributes.rb +0 -37
  103. data/lib/active_record/support/clean_logger.rb +0 -10
  104. data/lib/active_record/support/inflector.rb +0 -70
  105. data/lib/active_record/vendor/mysql.rb +0 -1117
  106. data/lib/active_record/vendor/simple.rb +0 -702
  107. data/lib/active_record/wrappers/yaml_wrapper.rb +0 -15
  108. data/lib/active_record/wrappings.rb +0 -59
  109. data/rakefile +0 -122
  110. data/test/abstract_unit.rb +0 -16
  111. data/test/aggregations_test.rb +0 -34
  112. data/test/all.sh +0 -8
  113. data/test/associations_test.rb +0 -477
  114. data/test/base_test.rb +0 -513
  115. data/test/class_inheritable_attributes_test.rb +0 -33
  116. data/test/connections/native_mysql/connection.rb +0 -24
  117. data/test/connections/native_postgresql/connection.rb +0 -24
  118. data/test/connections/native_sqlite/connection.rb +0 -24
  119. data/test/deprecated_associations_test.rb +0 -336
  120. data/test/finder_test.rb +0 -67
  121. data/test/fixtures/accounts/signals37 +0 -3
  122. data/test/fixtures/accounts/unknown +0 -2
  123. data/test/fixtures/auto_id.rb +0 -4
  124. data/test/fixtures/column_name.rb +0 -3
  125. data/test/fixtures/companies/first_client +0 -6
  126. data/test/fixtures/companies/first_firm +0 -4
  127. data/test/fixtures/companies/second_client +0 -6
  128. data/test/fixtures/company.rb +0 -37
  129. data/test/fixtures/company_in_module.rb +0 -33
  130. data/test/fixtures/course.rb +0 -3
  131. data/test/fixtures/courses/java +0 -2
  132. data/test/fixtures/courses/ruby +0 -2
  133. data/test/fixtures/customer.rb +0 -30
  134. data/test/fixtures/customers/david +0 -6
  135. data/test/fixtures/db_definitions/mysql.sql +0 -96
  136. data/test/fixtures/db_definitions/mysql2.sql +0 -4
  137. data/test/fixtures/db_definitions/postgresql.sql +0 -113
  138. data/test/fixtures/db_definitions/postgresql2.sql +0 -4
  139. data/test/fixtures/db_definitions/sqlite.sql +0 -85
  140. data/test/fixtures/db_definitions/sqlite2.sql +0 -4
  141. data/test/fixtures/default.rb +0 -2
  142. data/test/fixtures/developer.rb +0 -8
  143. data/test/fixtures/developers/david +0 -2
  144. data/test/fixtures/developers/jamis +0 -2
  145. data/test/fixtures/developers_projects/david_action_controller +0 -2
  146. data/test/fixtures/developers_projects/david_active_record +0 -2
  147. data/test/fixtures/developers_projects/jamis_active_record +0 -2
  148. data/test/fixtures/entrant.rb +0 -3
  149. data/test/fixtures/entrants/first +0 -3
  150. data/test/fixtures/entrants/second +0 -3
  151. data/test/fixtures/entrants/third +0 -3
  152. data/test/fixtures/fixture_database.sqlite +0 -0
  153. data/test/fixtures/fixture_database_2.sqlite +0 -0
  154. data/test/fixtures/movie.rb +0 -5
  155. data/test/fixtures/movies/first +0 -2
  156. data/test/fixtures/movies/second +0 -2
  157. data/test/fixtures/project.rb +0 -3
  158. data/test/fixtures/projects/action_controller +0 -2
  159. data/test/fixtures/projects/active_record +0 -2
  160. data/test/fixtures/reply.rb +0 -21
  161. data/test/fixtures/subscriber.rb +0 -5
  162. data/test/fixtures/subscribers/first +0 -2
  163. data/test/fixtures/subscribers/second +0 -2
  164. data/test/fixtures/topic.rb +0 -20
  165. data/test/fixtures/topics/first +0 -9
  166. data/test/fixtures/topics/second +0 -8
  167. data/test/fixtures_test.rb +0 -20
  168. data/test/inflector_test.rb +0 -104
  169. data/test/inheritance_test.rb +0 -125
  170. data/test/lifecycle_test.rb +0 -110
  171. data/test/modules_test.rb +0 -21
  172. data/test/multiple_db_test.rb +0 -46
  173. data/test/pk_test.rb +0 -57
  174. data/test/reflection_test.rb +0 -78
  175. data/test/thread_safety_test.rb +0 -33
  176. data/test/transactions_test.rb +0 -83
  177. data/test/unconnected_test.rb +0 -24
  178. data/test/validations_test.rb +0 -126
@@ -0,0 +1,244 @@
1
+ require 'active_support/core_ext/array/wrap'
2
+ require 'active_support/core_ext/hash/conversions'
3
+
4
+ module ActiveRecord #:nodoc:
5
+ module Serialization
6
+ include ActiveModel::Serializers::Xml
7
+
8
+ # Builds an XML document to represent the model. Some configuration is
9
+ # available through +options+. However more complicated cases should
10
+ # override ActiveRecord::Base#to_xml.
11
+ #
12
+ # By default the generated XML document will include the processing
13
+ # instruction and all the object's attributes. For example:
14
+ #
15
+ # <?xml version="1.0" encoding="UTF-8"?>
16
+ # <topic>
17
+ # <title>The First Topic</title>
18
+ # <author-name>David</author-name>
19
+ # <id type="integer">1</id>
20
+ # <approved type="boolean">false</approved>
21
+ # <replies-count type="integer">0</replies-count>
22
+ # <bonus-time type="datetime">2000-01-01T08:28:00+12:00</bonus-time>
23
+ # <written-on type="datetime">2003-07-16T09:28:00+1200</written-on>
24
+ # <content>Have a nice day</content>
25
+ # <author-email-address>david@loudthinking.com</author-email-address>
26
+ # <parent-id></parent-id>
27
+ # <last-read type="date">2004-04-15</last-read>
28
+ # </topic>
29
+ #
30
+ # This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
31
+ # <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
32
+ # The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
33
+ # +attributes+ method. The default is to dasherize all column names, but you
34
+ # can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
35
+ # to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
36
+ # To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
37
+ #
38
+ # For instance:
39
+ #
40
+ # topic.to_xml(:skip_instruct => true, :except => [ :id, :bonus_time, :written_on, :replies_count ])
41
+ #
42
+ # <topic>
43
+ # <title>The First Topic</title>
44
+ # <author-name>David</author-name>
45
+ # <approved type="boolean">false</approved>
46
+ # <content>Have a nice day</content>
47
+ # <author-email-address>david@loudthinking.com</author-email-address>
48
+ # <parent-id></parent-id>
49
+ # <last-read type="date">2004-04-15</last-read>
50
+ # </topic>
51
+ #
52
+ # To include first level associations use <tt>:include</tt>:
53
+ #
54
+ # firm.to_xml :include => [ :account, :clients ]
55
+ #
56
+ # <?xml version="1.0" encoding="UTF-8"?>
57
+ # <firm>
58
+ # <id type="integer">1</id>
59
+ # <rating type="integer">1</rating>
60
+ # <name>37signals</name>
61
+ # <clients type="array">
62
+ # <client>
63
+ # <rating type="integer">1</rating>
64
+ # <name>Summit</name>
65
+ # </client>
66
+ # <client>
67
+ # <rating type="integer">1</rating>
68
+ # <name>Microsoft</name>
69
+ # </client>
70
+ # </clients>
71
+ # <account>
72
+ # <id type="integer">1</id>
73
+ # <credit-limit type="integer">50</credit-limit>
74
+ # </account>
75
+ # </firm>
76
+ #
77
+ # Additionally, the record being serialized will be passed to a Proc's second
78
+ # parameter. This allows for ad hoc additions to the resultant document that
79
+ # incorporate the context of the record being serialized. And by leveraging the
80
+ # closure created by a Proc, to_xml can be used to add elements that normally fall
81
+ # outside of the scope of the model -- for example, generating and appending URLs
82
+ # associated with models.
83
+ #
84
+ # proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
85
+ # firm.to_xml :procs => [ proc ]
86
+ #
87
+ # <firm>
88
+ # # ... normal attributes as shown above ...
89
+ # <name-reverse>slangis73</name-reverse>
90
+ # </firm>
91
+ #
92
+ # To include deeper levels of associations pass a hash like this:
93
+ #
94
+ # firm.to_xml :include => {:account => {}, :clients => {:include => :address}}
95
+ # <?xml version="1.0" encoding="UTF-8"?>
96
+ # <firm>
97
+ # <id type="integer">1</id>
98
+ # <rating type="integer">1</rating>
99
+ # <name>37signals</name>
100
+ # <clients type="array">
101
+ # <client>
102
+ # <rating type="integer">1</rating>
103
+ # <name>Summit</name>
104
+ # <address>
105
+ # ...
106
+ # </address>
107
+ # </client>
108
+ # <client>
109
+ # <rating type="integer">1</rating>
110
+ # <name>Microsoft</name>
111
+ # <address>
112
+ # ...
113
+ # </address>
114
+ # </client>
115
+ # </clients>
116
+ # <account>
117
+ # <id type="integer">1</id>
118
+ # <credit-limit type="integer">50</credit-limit>
119
+ # </account>
120
+ # </firm>
121
+ #
122
+ # To include any methods on the model being called use <tt>:methods</tt>:
123
+ #
124
+ # firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
125
+ #
126
+ # <firm>
127
+ # # ... normal attributes as shown above ...
128
+ # <calculated-earnings>100000000000000000</calculated-earnings>
129
+ # <real-earnings>5</real-earnings>
130
+ # </firm>
131
+ #
132
+ # To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
133
+ # modified version of the options hash that was given to +to_xml+:
134
+ #
135
+ # proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
136
+ # firm.to_xml :procs => [ proc ]
137
+ #
138
+ # <firm>
139
+ # # ... normal attributes as shown above ...
140
+ # <abc>def</abc>
141
+ # </firm>
142
+ #
143
+ # Alternatively, you can yield the builder object as part of the +to_xml+ call:
144
+ #
145
+ # firm.to_xml do |xml|
146
+ # xml.creator do
147
+ # xml.first_name "David"
148
+ # xml.last_name "Heinemeier Hansson"
149
+ # end
150
+ # end
151
+ #
152
+ # <firm>
153
+ # # ... normal attributes as shown above ...
154
+ # <creator>
155
+ # <first_name>David</first_name>
156
+ # <last_name>Heinemeier Hansson</last_name>
157
+ # </creator>
158
+ # </firm>
159
+ #
160
+ # As noted above, you may override +to_xml+ in your ActiveRecord::Base
161
+ # subclasses to have complete control about what's generated. The general
162
+ # form of doing this is:
163
+ #
164
+ # class IHaveMyOwnXML < ActiveRecord::Base
165
+ # def to_xml(options = {})
166
+ # options[:indent] ||= 2
167
+ # xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
168
+ # xml.instruct! unless options[:skip_instruct]
169
+ # xml.level_one do
170
+ # xml.tag!(:second_level, 'content')
171
+ # end
172
+ # end
173
+ # end
174
+ def to_xml(options = {}, &block)
175
+ XmlSerializer.new(self, options).serialize(&block)
176
+ end
177
+ end
178
+
179
+ class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
180
+ def initialize(*args)
181
+ super
182
+ options[:except] |= Array.wrap(@serializable.class.inheritance_column)
183
+ end
184
+
185
+ def add_extra_behavior
186
+ add_includes
187
+ end
188
+
189
+ def add_includes
190
+ procs = options.delete(:procs)
191
+ @serializable.send(:serializable_add_includes, options) do |association, records, opts|
192
+ add_associations(association, records, opts)
193
+ end
194
+ options[:procs] = procs
195
+ end
196
+
197
+ # TODO This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
198
+ def add_associations(association, records, opts)
199
+ association_name = association.to_s.singularize
200
+ merged_options = options.merge(opts).merge!(:root => association_name, :skip_instruct => true)
201
+
202
+ if records.is_a?(Enumerable)
203
+ tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
204
+ type = options[:skip_types] ? { } : {:type => "array"}
205
+
206
+ if records.empty?
207
+ @builder.tag!(tag, type)
208
+ else
209
+ @builder.tag!(tag, type) do
210
+ records.each do |record|
211
+ if options[:skip_types]
212
+ record_type = {}
213
+ else
214
+ record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
215
+ record_type = {:type => record_class}
216
+ end
217
+
218
+ record.to_xml merged_options.merge(record_type)
219
+ end
220
+ end
221
+ end
222
+ elsif record = @serializable.send(association)
223
+ record.to_xml(merged_options)
224
+ end
225
+ end
226
+
227
+ class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
228
+ def compute_type
229
+ type = @serializable.class.serialized_attributes.has_key?(name) ?
230
+ super : @serializable.class.columns_hash[name].type
231
+
232
+ case type
233
+ when :text
234
+ :string
235
+ when :time
236
+ :datetime
237
+ else
238
+ type
239
+ end
240
+ end
241
+ protected :compute_type
242
+ end
243
+ end
244
+ end
@@ -0,0 +1,340 @@
1
+ module ActiveRecord
2
+ # = Active Record Session Store
3
+ #
4
+ # A session store backed by an Active Record class. A default class is
5
+ # provided, but any object duck-typing to an Active Record Session class
6
+ # with text +session_id+ and +data+ attributes is sufficient.
7
+ #
8
+ # The default assumes a +sessions+ tables with columns:
9
+ # +id+ (numeric primary key),
10
+ # +session_id+ (text, or longtext if your session data exceeds 65K), and
11
+ # +data+ (text or longtext; careful if your session data exceeds 65KB).
12
+ #
13
+ # The +session_id+ column should always be indexed for speedy lookups.
14
+ # Session data is marshaled to the +data+ column in Base64 format.
15
+ # If the data you write is larger than the column's size limit,
16
+ # ActionController::SessionOverflowError will be raised.
17
+ #
18
+ # You may configure the table name, primary key, and data column.
19
+ # For example, at the end of <tt>config/application.rb</tt>:
20
+ #
21
+ # ActiveRecord::SessionStore::Session.table_name = 'legacy_session_table'
22
+ # ActiveRecord::SessionStore::Session.primary_key = 'session_id'
23
+ # ActiveRecord::SessionStore::Session.data_column_name = 'legacy_session_data'
24
+ #
25
+ # Note that setting the primary key to the +session_id+ frees you from
26
+ # having a separate +id+ column if you don't want it. However, you must
27
+ # set <tt>session.model.id = session.session_id</tt> by hand! A before filter
28
+ # on ApplicationController is a good place.
29
+ #
30
+ # Since the default class is a simple Active Record, you get timestamps
31
+ # for free if you add +created_at+ and +updated_at+ datetime columns to
32
+ # the +sessions+ table, making periodic session expiration a snap.
33
+ #
34
+ # You may provide your own session class implementation, whether a
35
+ # feature-packed Active Record or a bare-metal high-performance SQL
36
+ # store, by setting
37
+ #
38
+ # ActiveRecord::SessionStore.session_class = MySessionClass
39
+ #
40
+ # You must implement these methods:
41
+ #
42
+ # self.find_by_session_id(session_id)
43
+ # initialize(hash_of_session_id_and_data)
44
+ # attr_reader :session_id
45
+ # attr_accessor :data
46
+ # save
47
+ # destroy
48
+ #
49
+ # The example SqlBypass class is a generic SQL session store. You may
50
+ # use it as a basis for high-performance database-specific stores.
51
+ class SessionStore < ActionDispatch::Session::AbstractStore
52
+ module ClassMethods # :nodoc:
53
+ def marshal(data)
54
+ ActiveSupport::Base64.encode64(Marshal.dump(data)) if data
55
+ end
56
+
57
+ def unmarshal(data)
58
+ Marshal.load(ActiveSupport::Base64.decode64(data)) if data
59
+ end
60
+
61
+ def drop_table!
62
+ connection.drop_table table_name
63
+ end
64
+
65
+ def create_table!
66
+ connection.create_table(table_name) do |t|
67
+ t.string session_id_column, :limit => 255
68
+ t.text data_column_name
69
+ end
70
+ connection.add_index table_name, session_id_column, :unique => true
71
+ end
72
+ end
73
+
74
+ # The default Active Record class.
75
+ class Session < ActiveRecord::Base
76
+ extend ClassMethods
77
+
78
+ ##
79
+ # :singleton-method:
80
+ # Customizable data column name. Defaults to 'data'.
81
+ cattr_accessor :data_column_name
82
+ self.data_column_name = 'data'
83
+
84
+ before_save :marshal_data!
85
+ before_save :raise_on_session_data_overflow!
86
+
87
+ class << self
88
+ def data_column_size_limit
89
+ @data_column_size_limit ||= columns_hash[data_column_name].limit
90
+ end
91
+
92
+ # Hook to set up sessid compatibility.
93
+ def find_by_session_id(session_id)
94
+ setup_sessid_compatibility!
95
+ find_by_session_id(session_id)
96
+ end
97
+
98
+ private
99
+ def session_id_column
100
+ 'session_id'
101
+ end
102
+
103
+ # Compatibility with tables using sessid instead of session_id.
104
+ def setup_sessid_compatibility!
105
+ # Reset column info since it may be stale.
106
+ reset_column_information
107
+ if columns_hash['sessid']
108
+ def self.find_by_session_id(*args)
109
+ find_by_sessid(*args)
110
+ end
111
+
112
+ define_method(:session_id) { sessid }
113
+ define_method(:session_id=) { |session_id| self.sessid = session_id }
114
+ else
115
+ class << self; remove_method :find_by_session_id; end
116
+
117
+ def self.find_by_session_id(session_id)
118
+ find :first, :conditions => {:session_id=>session_id}
119
+ end
120
+ end
121
+ end
122
+ end
123
+
124
+ def initialize(attributes = nil)
125
+ @data = nil
126
+ super
127
+ end
128
+
129
+ # Lazy-unmarshal session state.
130
+ def data
131
+ @data ||= self.class.unmarshal(read_attribute(@@data_column_name)) || {}
132
+ end
133
+
134
+ attr_writer :data
135
+
136
+ # Has the session been loaded yet?
137
+ def loaded?
138
+ @data
139
+ end
140
+
141
+ private
142
+ def marshal_data!
143
+ return false unless loaded?
144
+ write_attribute(@@data_column_name, self.class.marshal(data))
145
+ end
146
+
147
+ # Ensures that the data about to be stored in the database is not
148
+ # larger than the data storage column. Raises
149
+ # ActionController::SessionOverflowError.
150
+ def raise_on_session_data_overflow!
151
+ return false unless loaded?
152
+ limit = self.class.data_column_size_limit
153
+ if limit and read_attribute(@@data_column_name).size > limit
154
+ raise ActionController::SessionOverflowError
155
+ end
156
+ end
157
+ end
158
+
159
+ # A barebones session store which duck-types with the default session
160
+ # store but bypasses Active Record and issues SQL directly. This is
161
+ # an example session model class meant as a basis for your own classes.
162
+ #
163
+ # The database connection, table name, and session id and data columns
164
+ # are configurable class attributes. Marshaling and unmarshaling
165
+ # are implemented as class methods that you may override. By default,
166
+ # marshaling data is
167
+ #
168
+ # ActiveSupport::Base64.encode64(Marshal.dump(data))
169
+ #
170
+ # and unmarshaling data is
171
+ #
172
+ # Marshal.load(ActiveSupport::Base64.decode64(data))
173
+ #
174
+ # This marshaling behavior is intended to store the widest range of
175
+ # binary session data in a +text+ column. For higher performance,
176
+ # store in a +blob+ column instead and forgo the Base64 encoding.
177
+ class SqlBypass
178
+ extend ClassMethods
179
+
180
+ ##
181
+ # :singleton-method:
182
+ # Use the ActiveRecord::Base.connection by default.
183
+ cattr_accessor :connection
184
+
185
+ ##
186
+ # :singleton-method:
187
+ # The table name defaults to 'sessions'.
188
+ cattr_accessor :table_name
189
+ @@table_name = 'sessions'
190
+
191
+ ##
192
+ # :singleton-method:
193
+ # The session id field defaults to 'session_id'.
194
+ cattr_accessor :session_id_column
195
+ @@session_id_column = 'session_id'
196
+
197
+ ##
198
+ # :singleton-method:
199
+ # The data field defaults to 'data'.
200
+ cattr_accessor :data_column
201
+ @@data_column = 'data'
202
+
203
+ class << self
204
+ alias :data_column_name :data_column
205
+
206
+ remove_method :connection
207
+ def connection
208
+ @@connection ||= ActiveRecord::Base.connection
209
+ end
210
+
211
+ # Look up a session by id and unmarshal its data if found.
212
+ def find_by_session_id(session_id)
213
+ if record = connection.select_one("SELECT * FROM #{@@table_name} WHERE #{@@session_id_column}=#{connection.quote(session_id)}")
214
+ new(:session_id => session_id, :marshaled_data => record['data'])
215
+ end
216
+ end
217
+ end
218
+
219
+ attr_reader :session_id, :new_record
220
+ alias :new_record? :new_record
221
+
222
+ attr_writer :data
223
+
224
+ # Look for normal and marshaled data, self.find_by_session_id's way of
225
+ # telling us to postpone unmarshaling until the data is requested.
226
+ # We need to handle a normal data attribute in case of a new record.
227
+ def initialize(attributes)
228
+ @session_id = attributes[:session_id]
229
+ @data = attributes[:data]
230
+ @marshaled_data = attributes[:marshaled_data]
231
+ @new_record = @marshaled_data.nil?
232
+ end
233
+
234
+ # Lazy-unmarshal session state.
235
+ def data
236
+ unless @data
237
+ if @marshaled_data
238
+ @data, @marshaled_data = self.class.unmarshal(@marshaled_data) || {}, nil
239
+ else
240
+ @data = {}
241
+ end
242
+ end
243
+ @data
244
+ end
245
+
246
+ def loaded?
247
+ @data
248
+ end
249
+
250
+ def save
251
+ return false unless loaded?
252
+ marshaled_data = self.class.marshal(data)
253
+ connect = connection
254
+
255
+ if @new_record
256
+ @new_record = false
257
+ connect.update <<-end_sql, 'Create session'
258
+ INSERT INTO #{table_name} (
259
+ #{connect.quote_column_name(session_id_column)},
260
+ #{connect.quote_column_name(data_column)} )
261
+ VALUES (
262
+ #{connect.quote(session_id)},
263
+ #{connect.quote(marshaled_data)} )
264
+ end_sql
265
+ else
266
+ connect.update <<-end_sql, 'Update session'
267
+ UPDATE #{table_name}
268
+ SET #{connect.quote_column_name(data_column)}=#{connect.quote(marshaled_data)}
269
+ WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id)}
270
+ end_sql
271
+ end
272
+ end
273
+
274
+ def destroy
275
+ return if @new_record
276
+
277
+ connect = connection
278
+ connect.delete <<-end_sql, 'Destroy session'
279
+ DELETE FROM #{table_name}
280
+ WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id)}
281
+ end_sql
282
+ end
283
+ end
284
+
285
+ # The class used for session storage. Defaults to
286
+ # ActiveRecord::SessionStore::Session
287
+ cattr_accessor :session_class
288
+ self.session_class = Session
289
+
290
+ SESSION_RECORD_KEY = 'rack.session.record'
291
+
292
+ private
293
+ def get_session(env, sid)
294
+ Base.silence do
295
+ sid ||= generate_sid
296
+ session = find_session(sid)
297
+ env[SESSION_RECORD_KEY] = session
298
+ [sid, session.data]
299
+ end
300
+ end
301
+
302
+ def set_session(env, sid, session_data)
303
+ Base.silence do
304
+ record = get_session_model(env, sid)
305
+ record.data = session_data
306
+ return false unless record.save
307
+
308
+ session_data = record.data
309
+ if session_data && session_data.respond_to?(:each_value)
310
+ session_data.each_value do |obj|
311
+ obj.clear_association_cache if obj.respond_to?(:clear_association_cache)
312
+ end
313
+ end
314
+ end
315
+
316
+ sid
317
+ end
318
+
319
+ def destroy(env)
320
+ if sid = current_session_id(env)
321
+ Base.silence do
322
+ get_session_model(env, sid).destroy
323
+ end
324
+ end
325
+ end
326
+
327
+ def get_session_model(env, sid)
328
+ if env[ENV_SESSION_OPTIONS_KEY][:id].nil?
329
+ env[SESSION_RECORD_KEY] = find_session(sid)
330
+ else
331
+ env[SESSION_RECORD_KEY] ||= find_session(sid)
332
+ end
333
+ end
334
+
335
+ def find_session(id)
336
+ @@session_class.find_by_session_id(id) ||
337
+ @@session_class.new(:session_id => id, :data => {})
338
+ end
339
+ end
340
+ end
@@ -0,0 +1,67 @@
1
+ module ActiveRecord
2
+ # = Active Record Test Case
3
+ #
4
+ # Defines some test assertions to test against SQL queries.
5
+ class TestCase < ActiveSupport::TestCase #:nodoc:
6
+ def assert_date_from_db(expected, actual, message = nil)
7
+ # SybaseAdapter doesn't have a separate column type just for dates,
8
+ # so the time is in the string and incorrectly formatted
9
+ if current_adapter?(:SybaseAdapter)
10
+ assert_equal expected.to_s, actual.to_date.to_s, message
11
+ else
12
+ assert_equal expected.to_s, actual.to_s, message
13
+ end
14
+ end
15
+
16
+ def assert_sql(*patterns_to_match)
17
+ $queries_executed = []
18
+ yield
19
+ ensure
20
+ failed_patterns = []
21
+ patterns_to_match.each do |pattern|
22
+ failed_patterns << pattern unless $queries_executed.any?{ |sql| pattern === sql }
23
+ end
24
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
25
+ end
26
+
27
+ def assert_queries(num = 1)
28
+ $queries_executed = []
29
+ yield
30
+ ensure
31
+ %w{ BEGIN COMMIT }.each { |x| $queries_executed.delete(x) }
32
+ assert_equal num, $queries_executed.size, "#{$queries_executed.size} instead of #{num} queries were executed.#{$queries_executed.size == 0 ? '' : "\nQueries:\n#{$queries_executed.join("\n")}"}"
33
+ end
34
+
35
+ def assert_no_queries(&block)
36
+ assert_queries(0, &block)
37
+ end
38
+
39
+ def self.use_concurrent_connections
40
+ setup :connection_allow_concurrency_setup
41
+ teardown :connection_allow_concurrency_teardown
42
+ end
43
+
44
+ def connection_allow_concurrency_setup
45
+ @connection = ActiveRecord::Base.remove_connection
46
+ ActiveRecord::Base.establish_connection(@connection.merge({:allow_concurrency => true}))
47
+ end
48
+
49
+ def connection_allow_concurrency_teardown
50
+ ActiveRecord::Base.clear_all_connections!
51
+ ActiveRecord::Base.establish_connection(@connection)
52
+ end
53
+
54
+ def with_kcode(kcode)
55
+ if RUBY_VERSION < '1.9'
56
+ orig_kcode, $KCODE = $KCODE, kcode
57
+ begin
58
+ yield
59
+ ensure
60
+ $KCODE = orig_kcode
61
+ end
62
+ else
63
+ yield
64
+ end
65
+ end
66
+ end
67
+ end