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,18 @@
1
+ module ActiveRecord #:nodoc:
2
+ # = Active Record Serialization
3
+ module Serialization
4
+ extend ActiveSupport::Concern
5
+ include ActiveModel::Serializers::JSON
6
+
7
+ def serializable_hash(options = nil)
8
+ options = options.try(:clone) || {}
9
+
10
+ options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
11
+ options[:except] |= Array.wrap(self.class.inheritance_column)
12
+
13
+ super(options)
14
+ end
15
+ end
16
+ end
17
+
18
+ require 'active_record/serializers/xml_serializer'
@@ -0,0 +1,202 @@
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(options[:except]) | Array.wrap(@serializable.class.inheritance_column)
183
+ end
184
+
185
+ class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
186
+ def compute_type
187
+ klass = @serializable.class
188
+ type = if klass.serialized_attributes.key?(name)
189
+ super
190
+ elsif klass.columns_hash.key?(name)
191
+ klass.columns_hash[name].type
192
+ else
193
+ NilClass
194
+ end
195
+
196
+ { :text => :string,
197
+ :time => :datetime }[type] || type
198
+ end
199
+ protected :compute_type
200
+ end
201
+ end
202
+ end
@@ -0,0 +1,358 @@
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, options_hash = {})
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
+ ::Base64.encode64(Marshal.dump(data)) if data
55
+ end
56
+
57
+ def unmarshal(data)
58
+ Marshal.load(::Base64.decode64(data)) if data
59
+ end
60
+
61
+ def drop_table!
62
+ connection.schema_cache.clear_table_cache!(table_name)
63
+ connection.drop_table table_name
64
+ end
65
+
66
+ def create_table!
67
+ connection.schema_cache.clear_table_cache!(table_name)
68
+ connection.create_table(table_name) do |t|
69
+ t.string session_id_column, :limit => 255
70
+ t.text data_column_name
71
+ end
72
+ connection.add_index table_name, session_id_column, :unique => true
73
+ end
74
+ end
75
+
76
+ # The default Active Record class.
77
+ class Session < ActiveRecord::Base
78
+ extend ClassMethods
79
+
80
+ ##
81
+ # :singleton-method:
82
+ # Customizable data column name. Defaults to 'data'.
83
+ cattr_accessor :data_column_name
84
+ self.data_column_name = 'data'
85
+
86
+ attr_accessible :session_id, :data, :marshaled_data
87
+
88
+ before_save :marshal_data!
89
+ before_save :raise_on_session_data_overflow!
90
+
91
+ class << self
92
+ def data_column_size_limit
93
+ @data_column_size_limit ||= columns_hash[data_column_name].limit
94
+ end
95
+
96
+ # Hook to set up sessid compatibility.
97
+ def find_by_session_id(session_id)
98
+ setup_sessid_compatibility!
99
+ find_by_session_id(session_id)
100
+ end
101
+
102
+ private
103
+ def session_id_column
104
+ 'session_id'
105
+ end
106
+
107
+ # Compatibility with tables using sessid instead of session_id.
108
+ def setup_sessid_compatibility!
109
+ # Reset column info since it may be stale.
110
+ reset_column_information
111
+ if columns_hash['sessid']
112
+ def self.find_by_session_id(*args)
113
+ find_by_sessid(*args)
114
+ end
115
+
116
+ define_method(:session_id) { sessid }
117
+ define_method(:session_id=) { |session_id| self.sessid = session_id }
118
+ else
119
+ class << self; remove_method :find_by_session_id; end
120
+
121
+ def self.find_by_session_id(session_id)
122
+ find :first, :conditions => {:session_id=>session_id}
123
+ end
124
+ end
125
+ end
126
+ end
127
+
128
+ def initialize(attributes = nil, options = {})
129
+ @data = nil
130
+ super
131
+ end
132
+
133
+ # Lazy-unmarshal session state.
134
+ def data
135
+ @data ||= self.class.unmarshal(read_attribute(@@data_column_name)) || {}
136
+ end
137
+
138
+ attr_writer :data
139
+
140
+ # Has the session been loaded yet?
141
+ def loaded?
142
+ @data
143
+ end
144
+
145
+ private
146
+ def marshal_data!
147
+ return false unless loaded?
148
+ write_attribute(@@data_column_name, self.class.marshal(data))
149
+ end
150
+
151
+ # Ensures that the data about to be stored in the database is not
152
+ # larger than the data storage column. Raises
153
+ # ActionController::SessionOverflowError.
154
+ def raise_on_session_data_overflow!
155
+ return false unless loaded?
156
+ limit = self.class.data_column_size_limit
157
+ if limit and read_attribute(@@data_column_name).size > limit
158
+ raise ActionController::SessionOverflowError
159
+ end
160
+ end
161
+ end
162
+
163
+ # A barebones session store which duck-types with the default session
164
+ # store but bypasses Active Record and issues SQL directly. This is
165
+ # an example session model class meant as a basis for your own classes.
166
+ #
167
+ # The database connection, table name, and session id and data columns
168
+ # are configurable class attributes. Marshaling and unmarshaling
169
+ # are implemented as class methods that you may override. By default,
170
+ # marshaling data is
171
+ #
172
+ # ::Base64.encode64(Marshal.dump(data))
173
+ #
174
+ # and unmarshaling data is
175
+ #
176
+ # Marshal.load(::Base64.decode64(data))
177
+ #
178
+ # This marshaling behavior is intended to store the widest range of
179
+ # binary session data in a +text+ column. For higher performance,
180
+ # store in a +blob+ column instead and forgo the Base64 encoding.
181
+ class SqlBypass
182
+ extend ClassMethods
183
+
184
+ ##
185
+ # :singleton-method:
186
+ # The table name defaults to 'sessions'.
187
+ cattr_accessor :table_name
188
+ @@table_name = 'sessions'
189
+
190
+ ##
191
+ # :singleton-method:
192
+ # The session id field defaults to 'session_id'.
193
+ cattr_accessor :session_id_column
194
+ @@session_id_column = 'session_id'
195
+
196
+ ##
197
+ # :singleton-method:
198
+ # The data field defaults to 'data'.
199
+ cattr_accessor :data_column
200
+ @@data_column = 'data'
201
+
202
+ class << self
203
+ alias :data_column_name :data_column
204
+
205
+ # Use the ActiveRecord::Base.connection by default.
206
+ attr_writer :connection
207
+
208
+ # Use the ActiveRecord::Base.connection_pool by default.
209
+ attr_writer :connection_pool
210
+
211
+ def connection
212
+ @connection ||= ActiveRecord::Base.connection
213
+ end
214
+
215
+ def connection_pool
216
+ @connection_pool ||= ActiveRecord::Base.connection_pool
217
+ end
218
+
219
+ # Look up a session by id and unmarshal its data if found.
220
+ def find_by_session_id(session_id)
221
+ if record = connection.select_one("SELECT * FROM #{@@table_name} WHERE #{@@session_id_column}=#{connection.quote(session_id)}")
222
+ new(:session_id => session_id, :marshaled_data => record['data'])
223
+ end
224
+ end
225
+ end
226
+
227
+ delegate :connection, :connection=, :connection_pool, :connection_pool=, :to => self
228
+
229
+ attr_reader :session_id, :new_record
230
+ alias :new_record? :new_record
231
+
232
+ attr_writer :data
233
+
234
+ # Look for normal and marshaled data, self.find_by_session_id's way of
235
+ # telling us to postpone unmarshaling until the data is requested.
236
+ # We need to handle a normal data attribute in case of a new record.
237
+ def initialize(attributes)
238
+ @session_id = attributes[:session_id]
239
+ @data = attributes[:data]
240
+ @marshaled_data = attributes[:marshaled_data]
241
+ @new_record = @marshaled_data.nil?
242
+ end
243
+
244
+ # Lazy-unmarshal session state.
245
+ def data
246
+ unless @data
247
+ if @marshaled_data
248
+ @data, @marshaled_data = self.class.unmarshal(@marshaled_data) || {}, nil
249
+ else
250
+ @data = {}
251
+ end
252
+ end
253
+ @data
254
+ end
255
+
256
+ def loaded?
257
+ @data
258
+ end
259
+
260
+ def save
261
+ return false unless loaded?
262
+ marshaled_data = self.class.marshal(data)
263
+ connect = connection
264
+
265
+ if @new_record
266
+ @new_record = false
267
+ connect.update <<-end_sql, 'Create session'
268
+ INSERT INTO #{table_name} (
269
+ #{connect.quote_column_name(session_id_column)},
270
+ #{connect.quote_column_name(data_column)} )
271
+ VALUES (
272
+ #{connect.quote(session_id)},
273
+ #{connect.quote(marshaled_data)} )
274
+ end_sql
275
+ else
276
+ connect.update <<-end_sql, 'Update session'
277
+ UPDATE #{table_name}
278
+ SET #{connect.quote_column_name(data_column)}=#{connect.quote(marshaled_data)}
279
+ WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id)}
280
+ end_sql
281
+ end
282
+ end
283
+
284
+ def destroy
285
+ return if @new_record
286
+
287
+ connect = connection
288
+ connect.delete <<-end_sql, 'Destroy session'
289
+ DELETE FROM #{table_name}
290
+ WHERE #{connect.quote_column_name(session_id_column)}=#{connect.quote(session_id)}
291
+ end_sql
292
+ end
293
+ end
294
+
295
+ # The class used for session storage. Defaults to
296
+ # ActiveRecord::SessionStore::Session
297
+ cattr_accessor :session_class
298
+ self.session_class = Session
299
+
300
+ SESSION_RECORD_KEY = 'rack.session.record'
301
+ ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY
302
+
303
+ private
304
+ def get_session(env, sid)
305
+ Base.silence do
306
+ unless sid and session = @@session_class.find_by_session_id(sid)
307
+ # If the sid was nil or if there is no pre-existing session under the sid,
308
+ # force the generation of a new sid and associate a new session associated with the new sid
309
+ sid = generate_sid
310
+ session = @@session_class.new(:session_id => sid, :data => {})
311
+ end
312
+ env[SESSION_RECORD_KEY] = session
313
+ [sid, session.data]
314
+ end
315
+ end
316
+
317
+ def set_session(env, sid, session_data, options)
318
+ Base.silence do
319
+ record = get_session_model(env, sid)
320
+ record.data = session_data
321
+ return false unless record.save
322
+
323
+ session_data = record.data
324
+ if session_data && session_data.respond_to?(:each_value)
325
+ session_data.each_value do |obj|
326
+ obj.clear_association_cache if obj.respond_to?(:clear_association_cache)
327
+ end
328
+ end
329
+ end
330
+
331
+ sid
332
+ end
333
+
334
+ def destroy_session(env, session_id, options)
335
+ if sid = current_session_id(env)
336
+ Base.silence do
337
+ get_session_model(env, sid).destroy
338
+ env[SESSION_RECORD_KEY] = nil
339
+ end
340
+ end
341
+
342
+ generate_sid unless options[:drop]
343
+ end
344
+
345
+ def get_session_model(env, sid)
346
+ if env[ENV_SESSION_OPTIONS_KEY][:id].nil?
347
+ env[SESSION_RECORD_KEY] = find_session(sid)
348
+ else
349
+ env[SESSION_RECORD_KEY] ||= find_session(sid)
350
+ end
351
+ end
352
+
353
+ def find_session(id)
354
+ @@session_class.find_by_session_id(id) ||
355
+ @@session_class.new(:session_id => id, :data => {})
356
+ end
357
+ end
358
+ end