public
Last active

DataMapper identity map test

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, 'postgres://localhost/test') # createdb test
 
class Container
include DataMapper::Resource
 
property :id, Serial
 
has n, :slots
end
 
class Slot
include DataMapper::Resource
 
property :id, Serial
 
belongs_to :container
belongs_to :content
end
 
class Content
include DataMapper::Resource
 
property :id, Serial
property :data, String
 
has n, :slot
end
 
DataMapper.finalize
 
DataMapper.auto_migrate!
 
3.times {|x| Content.create(:data => "hello#{x}") }
2.times do
Container.create.tap do |container|
container.slots.create(:content => contents.sample)
container.slots.create(:content => contents.sample)
end
end
 
puts "\n\n\n\n"
 
DataMapper.repository {
Content.all.to_a
Container.all.map(&:slots).flatten.map(&:content)
}
 
# Output is:
# ~ (0.000679) SELECT "id", "data" FROM "contents" ORDER BY "id"
# ~ (0.000392) SELECT "id" FROM "containers" ORDER BY "id"
# ~ (0.000670) SELECT "id", "container_id", "content_id" FROM "slots" WHERE "container_id" IN (1, 2) ORDER BY "id"
# ~ (0.000430) SELECT "id", "data" FROM "contents" WHERE "id" = 2 ORDER BY "id" LIMIT 1
# ~ (0.001075) SELECT "id", "data" FROM "contents" WHERE "id" = 3 ORDER BY "id" LIMIT 1
# ~ (0.000432) SELECT "id", "data" FROM "contents" WHERE "id" = 1 ORDER BY "id" LIMIT 1
# ~ (0.002290) SELECT "id", "data" FROM "contents" WHERE "id" = 2 ORDER BY "id" LIMIT 1
# Expected:
# ~ (0.000679) SELECT "id", "data" FROM "contents" ORDER BY "id"
# ~ (0.000392) SELECT "id" FROM "containers" ORDER BY "id"
# ~ (0.000670) SELECT "id", "container_id", "content_id" FROM "slots" WHERE "container_id" IN (1, 2) ORDER BY "id"
# (Contents should be in the identity map, and not be reloaded)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.