Module: ODBA::Persistable

Included in:
Array, Hash, IdServer, IndexCommon
Defined in:
lib/odba/persistable.rb

Constant Summary collapse

Exact =
meta.new
Find =
Exact.dup
ODBA_EXCLUDE_VARS =

Classes which include Persistable may override ODBA_EXCLUDE_VARS to prevent data from being stored in the database (e.g. passwords, file descriptors). Simply redefine: ODBA_EXCLUDE_VARS = [‘@foo’]

[]
ODBA_INDEXABLE =

:nodoc:

true
ODBA_PREFETCH =

see odba_prefetch?

false
ODBA_PREDEFINE_EXCLUDE_VARS =

:nodoc:

['@odba_observers']
ODBA_PREDEFINE_SERIALIZABLE =

:nodoc:, legacy

['@odba_target_ids']
ODBA_SERIALIZABLE =

If you want to prevent Persistables from being disconnected and stored separately (Array and Hash are Persistable by default), redefine: ODBA_SERIALIZABLE = [‘@bar’]

[]
@@sanitize_ptrn =
/[^a-z0-9_]/i
@@odba_id_name =
RUBY_VERSION >= '1.9' ? :@odba_id : '@odba_id'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#odba_idObject

If no id had been assigned, this is now done. No attempt is made to store the Persistable in the db.



265
266
267
# File 'lib/odba/persistable.rb', line 265

def odba_id
	@odba_id ||= ODBA.cache.next_id
end

#odba_nameObject

Returns the value of attribute odba_name.



166
167
168
# File 'lib/odba/persistable.rb', line 166

def odba_name
  @odba_name
end

#odba_persistentObject

Classes which include Persistable have a class-method ‘odba_index’



31
32
33
# File 'lib/odba/persistable.rb', line 31

def odba_persistent
  @odba_persistent
end

#odba_prefetchObject

Returns the value of attribute odba_prefetch.



166
167
168
# File 'lib/odba/persistable.rb', line 166

def odba_prefetch
  @odba_prefetch
end

Class Method Details

.append_features(mod) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/odba/persistable.rb', line 32

def Persistable.append_features(mod)
  super
  mod.module_eval {
    class << self
      def odba_index(*keys)
        require 'odba/index_definition'
        origin_klass = self
        resolve_origin = nil
        resolve_target = :none
        resolve = {}
        opts = {}
        if(keys.size > 1)
          if(keys.last.is_a?(Hash))
            opts = keys.pop
          end
          if(keys.last.is_a?(Class))
            origin_klass = keys.pop 
            resolve = keys.pop
            resolve_origin = keys.pop
          elsif(keys.last.is_a?(Symbol))
            keys.each { |key|
              resolve.store(key, {'resolve' => key})
            }
          else
            resolve = keys.pop
          end
        else
          resolve = keys.first
        end
        keys.each { |key| 
          if RUBY_VERSION >= '1.9'
            key = key.to_sym
          else
            key = key.to_s
          end
          unless(instance_methods.include?(key))
            attr_accessor key
          end
        }
        index_prefix = self.name.downcase.gsub(/::/, '_')
        index_suffix = Persistable.sanitize(keys.join('_and_'))
        index_name = sprintf("%s_%s", index_prefix, index_suffix)
        search_name = sprintf("search_by_%s", index_suffix)
        exact_name = sprintf("search_by_exact_%s", index_suffix)
        find_name = sprintf("find_by_%s", index_suffix)
        keys_name = sprintf("%s_keys", index_suffix)
        index_definition = IndexDefinition.new
        index_definition.index_name = index_name
        index_definition.origin_klass = origin_klass
        index_definition.target_klass = self
        index_definition.resolve_search_term = resolve
        index_definition.resolve_origin = resolve_origin.to_s
        index_definition.resolve_target = resolve_target
        opts.each { |key, val| index_definition.send "#{key}=", val }
        ODBA.cache.ensure_index_deferred(index_definition)
        meta_eval {
          define_method(search_name) { |*vals| 
            if(vals.size > 1) 
              args = {}
              vals.each_with_index { |val, idx|
                cond = case val
                       when Numeric, Date
                         '='
                       else
                         'like'
                       end
                args.store(keys.at(idx), 
                           { 'value' => val, 'condition' => cond })
              }
              ODBA.cache.retrieve_from_index(index_name, args)
            else
              ODBA.cache.retrieve_from_index(index_name, vals.first)
            end
          }
          define_method(exact_name) {  |*vals|
            if(vals.size > 1) 
              args = {}
              vals.each_with_index { |val, idx|
                args.store(keys.at(idx), val)
              }
              ODBA.cache.retrieve_from_index(index_name, args, 
                                             ODBA::Persistable::Exact)
            else
              ODBA.cache.retrieve_from_index(index_name, vals.first,
                                             ODBA::Persistable::Exact)
            end
          }
          define_method(find_name) {  |*vals|
            if(vals.size > 1) 
              args = {}
              vals.each_with_index { |val, idx|
                cond = case val
                       when Numeric, Date
                         '='
                       else
                         'like'
                       end
                args.store(keys.at(idx), 
                           { 'value' => val, 'condition' => cond })
              }
              ODBA.cache.retrieve_from_index(index_name, args,
                                             ODBA::Persistable::Find)
            else
              ODBA.cache.retrieve_from_index(index_name, vals.first,
                                             ODBA::Persistable::Find)
            end.first
          }
          define_method(keys_name) { |*vals|
            # TODO fix this for fulltext and condition indices
            length, = vals
            ODBA.cache.index_keys(index_name, length)
          }
        }
        index_definition
      end
      def odba_extent
        all = ODBA.cache.extent(self) 
        if(block_given?)
          all.each { |instance| yield instance }
          nil
        else
          all
        end
      end
      def odba_count
        ODBA.cache.count(self) 
      end
    end
  }
end

.sanitize(name) ⇒ Object



163
164
165
# File 'lib/odba/persistable.rb', line 163

def Persistable.sanitize(name)
  name.gsub(@@sanitize_ptrn, '_')
end

Instance Method Details

#==(other) ⇒ Object

:nodoc:



185
186
187
# File 'lib/odba/persistable.rb', line 185

def ==(other) # :nodoc:
	super(other.odba_instance)
end

#dupObject

:nodoc:



189
190
191
192
193
194
195
# File 'lib/odba/persistable.rb', line 189

def dup # :nodoc:
  twin = super
  ## since twin may not be a Persistable, we need to do some magic here to 
  #  ensure that it does not have the same odba_id
  twin.instance_variable_set(@@odba_id_name, nil)
  twin
end

#eql?(other) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


196
197
198
199
# File 'lib/odba/persistable.rb', line 196

def eql?(other) # :nodoc:
  (other.is_a?(Stub) && other.odba_id == @odba_id) \
    || super(other.odba_instance)
end

#odba_add_observer(obj) ⇒ Object

Add an observer for Cache#store(self), Cache#delete(self) and Cache#clean removing the object from the Cache



202
203
204
205
# File 'lib/odba/persistable.rb', line 202

def odba_add_observer(obj)
  odba_observers.push(obj)
  obj
end

#odba_collectionObject

:nodoc:



206
207
208
# File 'lib/odba/persistable.rb', line 206

def odba_collection # :nodoc:
	[]
end

#odba_cut_connection(remove_object) ⇒ Object

Removes all connections to another persistable. This method is called by the Cache server when remove_object is deleted from the database



211
212
213
214
215
216
217
218
# File 'lib/odba/persistable.rb', line 211

def odba_cut_connection(remove_object)
	odba_potentials.each { |name|
		var = instance_variable_get(name)
		if(var.eql?(remove_object))
			instance_variable_set(name, nil)
		end
	}
end

#odba_deleteObject

Permanently deletes this Persistable from the database and remove all connections to it



221
222
223
# File 'lib/odba/persistable.rb', line 221

def odba_delete
	ODBA.cache.delete(self)
end

#odba_delete_observer(observer) ⇒ Object

Delete observer as an observer on this object. It will no longer receive notifications.



226
227
228
# File 'lib/odba/persistable.rb', line 226

def odba_delete_observer(observer)
  @odba_observers.delete(observer) if(@odba_observers)
end

#odba_delete_observersObject

Delete all observers associated with this object.



230
231
232
# File 'lib/odba/persistable.rb', line 230

def odba_delete_observers
  @odba_observers = nil
end

#odba_dupObject

:nodoc:



233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/odba/persistable.rb', line 233

def odba_dup #:nodoc:
	twin = dup
    twin.extend(Persistable)
    twin.odba_id = @odba_id
	odba_potentials.each { |name|
		var = twin.instance_variable_get(name)
		if(var.is_a?(ODBA::Stub))
			stub = var.odba_dup
			stub.odba_container = twin
			twin.instance_variable_set(name, stub)
		end
	}
	twin
end

#odba_exclude_varsObject

:nodoc:



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/odba/persistable.rb', line 247

def odba_exclude_vars # :nodoc:
			exc = if(defined?(self::class::ODBA_PREDEFINE_EXCLUDE_VARS))
          self::class::ODBA_PREDEFINE_EXCLUDE_VARS
        else
          ODBA_PREDEFINE_EXCLUDE_VARS
        end
			if(defined?(self::class::ODBA_EXCLUDE_VARS))
    exc += self::class::ODBA_EXCLUDE_VARS 
  end
  if RUBY_VERSION >= '1.9'
    exc.map{|v| v.to_sym}
  else
    exc
  end
end

#odba_indexable?Boolean

:nodoc:

Returns:

  • (Boolean)


300
301
302
303
# File 'lib/odba/persistable.rb', line 300

def odba_indexable? # :nodoc:
	@odba_indexable \
      || (defined?(self::class::ODBA_INDEXABLE) && self::class::ODBA_INDEXABLE)
end

#odba_isolated_dumpObject

:nodoc:



268
269
270
# File 'lib/odba/persistable.rb', line 268

def odba_isolated_dump # :nodoc:
	ODBA.marshaller.dump(odba_isolated_twin)
end

#odba_isolated_storeObject

Convenience method equivalent to ODBA.cache.store(self)



272
273
274
275
# File 'lib/odba/persistable.rb', line 272

def odba_isolated_store 
	@odba_persistent = true
	ODBA.cache.store(self)
end

#odba_isolated_stubObject

Returns a new instance of Stub, which can be used as a stand-in replacement for this Persistable.



278
279
280
# File 'lib/odba/persistable.rb', line 278

def odba_isolated_stub
	Stub.new(self.odba_id, nil, self)
end

#odba_isolated_twinObject

Returns a duplicate of this Persistable, for which all connected Persistables have been replaced by a Stub



283
284
285
286
287
288
289
290
# File 'lib/odba/persistable.rb', line 283

def odba_isolated_twin
	# ensure a valid odba_id
	self.odba_id
	twin = self.odba_dup
	twin.odba_replace_persistables
	twin.odba_replace_excluded!
	twin
end

#odba_notify_observers(*args) ⇒ Object

Invoke the update method in each currently associated observer in turn, passing it the given arguments



306
307
308
# File 'lib/odba/persistable.rb', line 306

def odba_notify_observers(*args) 
  odba_observers.each { |obs| obs.odba_update(*args) }
end

#odba_observersObject



309
310
311
# File 'lib/odba/persistable.rb', line 309

def odba_observers
  @odba_observers ||= []
end

#odba_potentialsObject

:nodoc:



312
313
314
# File 'lib/odba/persistable.rb', line 312

def odba_potentials # :nodoc:
	instance_variables - odba_serializables - odba_exclude_vars
end

#odba_prefetch?Boolean

A Persistable instance can be prefetchable. This means that the object can be loaded at startup by calling ODBA.cache.prefetch, and that it will never expire from the Cache. The prefetch status can be controlled per instance by setting the instance variable @odba_prefetch, and per class by overriding the module constant ODBA_PREFETCH

Returns:

  • (Boolean)


296
297
298
299
# File 'lib/odba/persistable.rb', line 296

def odba_prefetch?
	@odba_prefetch \
      || (defined?(self::class::ODBA_PREFETCH) && self::class::ODBA_PREFETCH)
end

#odba_replace!(obj) ⇒ Object

:nodoc:



315
316
317
318
319
# File 'lib/odba/persistable.rb', line 315

def odba_replace!(obj) # :nodoc:
  instance_variables.each { |name|
    instance_variable_set(name, obj.instance_variable_get(name))
  }
end

#odba_replace_persistablesObject

:nodoc:



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/odba/persistable.rb', line 320

def odba_replace_persistables # :nodoc:
	odba_potentials.each { |name|
		var = instance_variable_get(name)
		if(var.is_a?(ODBA::Stub))
        var.odba_clear_receiver   # ensure we don't leak into the db
        var.odba_container = self # ensure we don't leak into memory
		elsif(var.is_a?(ODBA::Persistable))
			odba_id = var.odba_id
			stub = ODBA::Stub.new(odba_id, self, var)
			instance_variable_set(name, stub)
		end
	}
	odba_serializables.each { |name|
		var = instance_variable_get(name)
		if(var.is_a?(ODBA::Stub))
			instance_variable_set(name, var.odba_instance)
		end
	}
end

#odba_replace_stubs(odba_id, substitution) ⇒ Object

:nodoc:



339
340
341
342
343
344
345
346
# File 'lib/odba/persistable.rb', line 339

def odba_replace_stubs(odba_id, substitution) # :nodoc:
    odba_potentials.each { |name|
      var = instance_variable_get(name)
      if(var.is_a?(Stub) && odba_id == var.odba_id)
        instance_variable_set(name, substitution)
      end
    }
end

#odba_restore(collection = []) ⇒ Object

:nodoc:



347
348
# File 'lib/odba/persistable.rb', line 347

def odba_restore(collection=[]) # :nodoc:
end

#odba_serializablesObject

:nodoc:



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/odba/persistable.rb', line 349

def odba_serializables # :nodoc:
	srs = if(defined?(self::class::ODBA_PREDEFINE_SERIALIZABLE))
            self::class::ODBA_PREDEFINE_SERIALIZABLE
          else
            ODBA_PREDEFINE_SERIALIZABLE
          end
	if(defined?(self::class::ODBA_SERIALIZABLE))
      srs += self::class::ODBA_SERIALIZABLE 
    end
    if RUBY_VERSION >= '1.9'
      srs.map{|s| s.to_sym}
    else
      srs
    end
end

#odba_snapshot(snapshot_level) ⇒ Object

:nodoc:



364
365
366
367
368
369
# File 'lib/odba/persistable.rb', line 364

def odba_snapshot(snapshot_level) # :nodoc:
	if(snapshot_level > @odba_snapshot_level.to_i)
		@odba_snapshot_level = snapshot_level
		odba_isolated_store
	end
end

#odba_store(name = nil) ⇒ Object

Stores this Persistable and recursively all connected unsaved persistables, until no more direcly connected unsaved persistables can be found. The optional parameter name can be used later to retrieve this Persistable using Cache#fetch_named



374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/odba/persistable.rb', line 374

def odba_store(name = nil)
	begin
		unless (name.nil?)
			old_name = @odba_name
			@odba_name = name
		end
		odba_store_unsaved
      self
	rescue 
		@odba_name = old_name
		raise
	end
end

#odba_store_unsavedObject

:nodoc:



387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/odba/persistable.rb', line 387

def odba_store_unsaved # :nodoc:
	@odba_persistent = false
	current_level = [self]
	while(!current_level.empty?)
		next_level = []
		current_level.each { |item|
			if(item.odba_unsaved?)
				next_level += item.odba_unsaved_neighbors
				item.odba_isolated_store
			end
		}
		current_level = next_level
	end
end

#odba_stubize(obj, opts = {}) ⇒ Object

:nodoc:



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/odba/persistable.rb', line 401

def odba_stubize(obj, opts={}) # :nodoc:
    return false if(frozen?)
	id = obj.odba_id
	odba_potentials.each { |name|
		var = instance_variable_get(name)
		# must not be synchronized because of the following if
		# statement (if an object has already been replaced by
		# a	stub, it will have the correct id and it
		# will be ignored) 
      case var
      when Stub
        # no need to make a new stub
      when Persistable
			if(var.odba_id == id) 
          stub = ODBA::Stub.new(id, self, obj)
          instance_variable_set(name, stub) 
        end
		end
	}
    odba_notify_observers(:stubize, id, obj.object_id)
    ## allow CacheEntry to retire
    true
end

#odba_take_snapshotObject

Recursively stores all connected Persistables.



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/odba/persistable.rb', line 425

def odba_take_snapshot
	@odba_snapshot_level ||= 0
	snapshot_level = @odba_snapshot_level.next
	current_level = [self]
	tree_level = 0
	while(!current_level.empty?)
		tree_level += 1
		obj_count = 0
		next_level = []
		current_level.each { |item|
			if(item.odba_unsaved?(snapshot_level))
				obj_count += 1
				next_level += item.odba_unsaved_neighbors(snapshot_level)
				item.odba_snapshot(snapshot_level)
			end
		}
		current_level = next_level #.uniq
	end
end

#odba_target_idsObject

:nodoc:



444
445
446
447
448
449
450
451
# File 'lib/odba/persistable.rb', line 444

def odba_target_ids # :nodoc:
	odba_potentials.collect { |name|
		var = instance_variable_get(name)
		if(var.is_a?(ODBA::Persistable))
			var.odba_id
		end
	}.compact.uniq
end

#odba_unsaved?(snapshot_level = nil) ⇒ Boolean

:nodoc:

Returns:

  • (Boolean)


463
464
465
466
467
468
469
470
# File 'lib/odba/persistable.rb', line 463

def odba_unsaved?(snapshot_level = nil) # :nodoc:
	if(snapshot_level.nil?)
		!@odba_persistent
		#true
	else
		@odba_snapshot_level.to_i < snapshot_level
	end
end

#odba_unsaved_neighbors(snapshot_level = nil) ⇒ Object

:nodoc:



452
453
454
455
456
457
458
459
460
461
462
# File 'lib/odba/persistable.rb', line 452

def odba_unsaved_neighbors(snapshot_level = nil) # :nodoc:
	unsaved = []
	odba_potentials.each { |name|
		item = instance_variable_get(name)
			if(item.is_a?(ODBA::Persistable) \
				&& item.odba_unsaved?(snapshot_level))
				unsaved.push(item)
			end
		}
	unsaved
end