2 # A session store backed by an Active Record class. A default class is
3 # provided, but any object duck-typing to an Active Record Session class
4 # with text +session_id+ and +data+ attributes is sufficient.
6 # The default assumes a +sessions+ tables with columns:
7 # +id+ (numeric primary key),
8 # +session_id+ (text, or longtext if your session data exceeds 65K), and
9 # +data+ (text or longtext; careful if your session data exceeds 65KB).
10 # The +session_id+ column should always be indexed for speedy lookups.
11 # Session data is marshaled to the +data+ column in Base64 format.
12 # If the data you write is larger than the column's size limit,
13 # ActionController::SessionOverflowError will be raised.
15 # You may configure the table name, primary key, and data column.
16 # For example, at the end of <tt>config/environment.rb</tt>:
17 # ActiveRecord::SessionStore::Session.table_name = 'legacy_session_table'
18 # ActiveRecord::SessionStore::Session.primary_key = 'session_id'
19 # ActiveRecord::SessionStore::Session.data_column_name = 'legacy_session_data'
20 # Note that setting the primary key to the +session_id+ frees you from
21 # having a separate +id+ column if you don't want it. However, you must
22 # set <tt>session.model.id = session.session_id</tt> by hand! A before filter
23 # on ApplicationController is a good place.
25 # Since the default class is a simple Active Record, you get timestamps
26 # for free if you add +created_at+ and +updated_at+ datetime columns to
27 # the +sessions+ table, making periodic session expiration a snap.
29 # You may provide your own session class implementation, whether a
30 # feature-packed Active Record or a bare-metal high-performance SQL
32 # ActiveRecord::SessionStore.session_class = MySessionClass
33 # You must implement these methods:
34 # self.find_by_session_id(session_id)
35 # initialize(hash_of_session_id_and_data)
36 # attr_reader :session_id
41 # The example SqlBypass class is a generic SQL session store. You may
42 # use it as a basis for high-performance database-specific stores.
43 class SessionStore
< ActionController
::Session::AbstractStore
44 # The default Active Record class.
45 class Session
< ActiveRecord
::Base
48 # Customizable data column name. Defaults to 'data'.
49 cattr_accessor
:data_column_name
50 self.data_column_name
= 'data'
52 before_save
:marshal_data!
53 before_save
:raise_on_session_data_overflow!
56 def data_column_size_limit
57 @data_column_size_limit ||= columns_hash
[@
@data_column_name].limit
60 # Hook to set up sessid compatibility.
61 def find_by_session_id(session_id
)
62 setup_sessid_compatibility
!
63 find_by_session_id(session_id
)
67 ActiveSupport
::Base64.encode64(Marshal
.dump(data)) if data
71 Marshal
.load(ActiveSupport
::Base64.decode64(data)) if data
75 connection
.execute
<<-end_sql
76 CREATE TABLE #{table_name} (
77 id INTEGER PRIMARY KEY,
78 #{connection.quote_column_name('session_id')} TEXT UNIQUE,
79 #{connection.quote_column_name(@@data_column_name)} TEXT(255)
85 connection
.execute
"DROP TABLE #{table_name}"
89 # Compatibility with tables using sessid instead of session_id.
90 def setup_sessid_compatibility
!
91 # Reset column info since it may be stale.
92 reset_column_information
93 if columns_hash
['sessid']
94 def self.find_by_session_id(*args
)
98 define_method(:session_id) { sessid
}
99 define_method(:session_id=) { |session_id
| self.sessid
= session_id
}
101 def self.find_by_session_id(session_id
)
102 find
:first, :conditions => {:session_id=>session_id
}
108 # Lazy-unmarshal session state.
110 @data ||= self.class.unmarshal(read_attribute(@
@data_column_name)) || {}
115 # Has the session been loaded yet?
122 return false if !loaded
?
123 write_attribute(@
@data_column_name, self.class.marshal(self.data))
126 # Ensures that the data about to be stored in the database is not
127 # larger than the data storage column. Raises
128 # ActionController::SessionOverflowError.
129 def raise_on_session_data_overflow
!
130 return false if !loaded
?
131 limit
= self.class.data_column_size_limit
132 if loaded
? and limit
and read_attribute(@
@data_column_name).size
> limit
133 raise ActionController
::SessionOverflowError
138 # A barebones session store which duck-types with the default session
139 # store but bypasses Active Record and issues SQL directly. This is
140 # an example session model class meant as a basis for your own classes.
142 # The database connection, table name, and session id and data columns
143 # are configurable class attributes. Marshaling and unmarshaling
144 # are implemented as class methods that you may override. By default,
147 # ActiveSupport::Base64.encode64(Marshal.dump(data))
149 # and unmarshaling data is
151 # Marshal.load(ActiveSupport::Base64.decode64(data))
153 # This marshaling behavior is intended to store the widest range of
154 # binary session data in a +text+ column. For higher performance,
155 # store in a +blob+ column instead and forgo the Base64 encoding.
159 # Use the ActiveRecord::Base.connection by default.
160 cattr_accessor
:connection
164 # The table name defaults to 'sessions'.
165 cattr_accessor
:table_name
166 @
@table_name = 'sessions'
170 # The session id field defaults to 'session_id'.
171 cattr_accessor
:session_id_column
172 @
@session_id_column = 'session_id'
176 # The data field defaults to 'data'.
177 cattr_accessor
:data_column
178 @
@data_column = 'data'
182 @
@connection ||= ActiveRecord
::Base.connection
185 # Look up a session by id and unmarshal its data if found.
186 def find_by_session_id(session_id
)
187 if record
= @
@connection.select_one("SELECT * FROM #{@@table_name} WHERE #{@@session_id_column}=#{@@connection.quote(session_id)}")
188 new(:session_id => session_id
, :marshaled_data => record
['data'])
193 ActiveSupport
::Base64.encode64(Marshal
.dump(data)) if data
197 Marshal
.load(ActiveSupport
::Base64.decode64(data)) if data
201 @
@connection.execute
<<-end_sql
202 CREATE TABLE #{table_name} (
203 id INTEGER PRIMARY KEY,
204 #{@@connection.quote_column_name(session_id_column)} TEXT UNIQUE,
205 #{@@connection.quote_column_name(data_column)} TEXT
211 @
@connection.execute
"DROP TABLE #{table_name}"
215 attr_reader
:session_id
218 # Look for normal and marshaled data, self.find_by_session_id's way of
219 # telling us to postpone unmarshaling until the data is requested.
220 # We need to handle a normal data attribute in case of a new record.
221 def initialize(attributes
)
222 @session_id, @data, @marshaled_data = attributes
[:session_id], attributes
[:data], attributes
[:marshaled_data]
223 @new_record = @marshaled_data.nil?
230 # Lazy-unmarshal session state.
234 @data, @marshaled_data = self.class.unmarshal(@marshaled_data) || {}, nil
247 return false if !loaded
?
248 marshaled_data
= self.class.marshal(data)
252 @
@connection.update
<<-end_sql, 'Create session'
253 INSERT INTO #{@@table_name} (
254 #{@@connection.quote_column_name(@@session_id_column)},
255 #{@@connection.quote_column_name(@@data_column)} )
257 #{@@connection.quote(session_id)},
258 #{@@connection.quote(marshaled_data)} )
261 @
@connection.update
<<-end_sql, 'Update session'
262 UPDATE #{@@table_name}
263 SET #{@@connection.quote_column_name(@@data_column)}=#{@@connection.quote(marshaled_data)}
264 WHERE #{@@connection.quote_column_name(@@session_id_column)}=#{@@connection.quote(session_id)}
271 @
@connection.delete
<<-end_sql, 'Destroy session'
272 DELETE FROM #{@@table_name}
273 WHERE #{@@connection.quote_column_name(@@session_id_column)}=#{@@connection.quote(session_id)}
279 # The class used for session storage. Defaults to
280 # ActiveRecord::SessionStore::Session
281 cattr_accessor
:session_class
282 self.session_class
= Session
284 SESSION_RECORD_KEY
= 'rack.session.record'.freeze
287 def get_session(env, sid
)
290 session
= find_session(sid
)
291 env[SESSION_RECORD_KEY
] = session
296 def set_session(env, sid
, session_data
)
298 record
= env[SESSION_RECORD_KEY
] ||= find_session(sid
)
299 record
.data = session_data
300 return false unless record
.save
302 session_data
= record
.data
303 if session_data
&& session_data
.respond_to
?(:each_value)
304 session_data
.each_value
do |obj
|
305 obj
.clear_association_cache
if obj
.respond_to
?(:clear_association_cache)
314 @
@session_class.find_by_session_id(id
) ||
315 @
@session_class.new(:session_id => id
, :data => {})