Skip to content

Instantly share code, notes, and snippets.

@jeremyevans
Forked from nelsnelson/non_persistent_test.rb
Created March 1, 2012 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeremyevans/1951186 to your computer and use it in GitHub Desktop.
Save jeremyevans/1951186 to your computer and use it in GitHub Desktop.
Testing non-persistent fields on persisted identity-mapped entity instances in JRuby and Sequel through jdbc-postgres
#! /usr/bin/env jruby
require 'rubygems'
require 'sequel'
DB = Sequel.sqlite
DB.create_table? :test do
primary_key :id
foreign_key :parent_id, :test, :on_delete => :set_null
String :name
String :object_type, :null => false
index :name
end
Sequel::Model.plugin :identity_map
class Test < Sequel::Model(:test)
plugin :rcte_tree
plugin :single_table_inheritance, :object_type
def non_persistent_stuff
@non_persistent_stuff ||= []
end
def to_s
"#{name} <object_id:#{object_id},entity_id:#{id}>"
end
end
a = Test.find_or_create(:name => 'A')
b = nil
c = nil
t0 = Thread.new do
b = Test.find_or_create(:name => 'B')
c = Test.find_or_create(:name => 'C')
a.add_child b
puts "a.children.include? b # => #{a.children.include? b}"
b.non_persistent_stuff << c
puts ""
puts "b (should be 'B') # => #{b}"
puts "b.non_persistent_stuff # => [#{b.non_persistent_stuff}]"
puts "b.non_persistent_stuff.include? c # => #{b.non_persistent_stuff.include? c}"
end
t0.join
puts ""
t1 = Thread.new do
Test.with_identity_map do
x = Test.find(:name => 'A')
b = Test.find(:name => 'B')
z = Test.find(:name => 'C')
b.non_persistent_stuff << c
y = x.children.first
puts "x (should be 'A') # => #{x}"
puts "z (should be 'C') # => #{z}"
puts "x.children.include? b # => #{a.children.include? b}"
puts ""
puts "b (should be 'B') # => #{b}"
puts "y (should be 'B') # => #{y}"
puts ""
puts "b == y (should be true) # => #{b == y}"
puts "b.object_id == y.object_id (shouldn't this be true? perhaps I don't understand what an identity map does) # => #{b.object_id == y.object_id}"
puts ""
puts "y.non_persistent_stuff # => [#{y.non_persistent_stuff}]"
puts "y.non_persistent_stuff.include? z # => #{y.non_persistent_stuff.include? z}"
end
end
t1.join
Sequel::Model.db.drop_table :test if Sequel::Model.db.table_exists? :test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment