Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Created November 9, 2010 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaviershay/668930 to your computer and use it in GitHub Desktop.
Save xaviershay/668930 to your computer and use it in GitHub Desktop.
DataMapper identity map test
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment