Removing SELECT id FROM ... WHERE id=...

251 views
Skip to first unread message

Richard Fairhurst

unread,
Dec 8, 2012, 11:56:18 AM12/8/12
to DataMapper
Hi,

I'm building a model where I'd like _all_ the properties, including
the primary key, to be lazy-loaded. Like this:

class Post
include DataMapper::Resource

property :id, Serial, :lazy => [ :show ]
property :title, String, :lazy => [ :show ]
property :body, Text, :lazy => [ :show ]
property :created_at, DateTime, :lazy => [ :show ]
[...]

However, when I try to get an instance, the result is this:

post=Post.get(1)
~ (0.000379) SELECT `id` FROM `posts` WHERE `id` = 1 LIMIT 1

Is there any way of eliminating this database query? I'm presuming
DataMapper does it because it wants to validate that the record
exists, but if possible, I'd rather take that chance and skip the
query.

cheers
Richard

solnic

unread,
Dec 10, 2012, 5:57:52 AM12/10/12
to datam...@googlegroups.com
Hey Richard,

This sounds like trouble. Serial is used as the identifier in identity map so lazy loading it doesn't sound like a good idea.

Cheers

# solnic

Richard Fairhurst

unread,
Dec 20, 2012, 9:17:58 AM12/20/12
to DataMapper
On Dec 10, 10:57 am, solnic <piotr.soln...@gmail.com> wrote:
> Hey Richard,
>
> This sounds like trouble. Serial is used as the identifier in identity map
> so lazy loading it doesn't sound like a good idea.

Ok. I can see the logic but... let me explain what I'm trying to do
and you might be able to tell me what I'm doing wrong. :)

I'm building a site with DataMapper and Rack where I might want to
view a post like this:
Post.get($1).view

In the Post class, I therefore have a 'view' method which simply
renders the post as an HTML page. That would typically do something
like this:
page = Page.new(title)
page.add('post/single_item', { post: self })
page.out

where page.add reads in the specified erb template.

The challenge is that I'm trying to build this to be pretty scalable.
So page.add will check memcached to see if the HTML produced by that
erb template is cached, and if so, just use that instead - no need for
any db access. Except, of course, for this one query - SELECT `id`
FROM `posts` WHERE `id` = 1 LIMIT 1. Hence why I'd like to get rid of
it if possible.

(I could perhaps do this with a static method, say:
Post.get_by_id($1).view

and only actually get the object from the db when I'm ready to write
out the erb template. But that seems much less elegant, and besides,
it starts to get inefficient if you do
page.add('post/single_item', { post_id: id })
page.add('post/related_items', { post_id: id })

because you're probably then fetching the object twice.)

Obviously premature optimisation is the root of all evil though. :)

cheers
Richard
Reply all
Reply to author
Forward
0 new messages