Here is the solution that we came up with to extend DataMapper in our application and in this case we are assuming that we are using some sql version of an adapter.
module DataMapper
def self.generate_sql(dm_query)
statement, bind_vars = repository.adapter.send(:select_statement, dm_query.query)
repository.adapter.send(:open_connection).create_command(statement).send(:escape_sql, bind_vars)
end
end
def self.generate_sql(dm_query)
statement, bind_vars = repository.adapter.send(:select_statement, dm_query.query)
repository.adapter.send(:open_connection).create_command(statement).send(:escape_sql, bind_vars)
end
end
With this in our application we can now make a call like:
sql = DataMapper.generate_sql(User.all(:name.like=>'%Bob%')
This will return an SQL statement for selecting all the users in the User Table that match Bob in them. If we want to execute this SQL against our backend then all we need is:
results = repository(:default).adapter.select(sql)
And now results holds the records as structs. This is useful when dealing with a large number of records and you just want the results. Other fun things you may want to do include building transactions out of your DataMapper generated statements since I find some things to be lacking with the DataMapper transactions.
No comments:
Post a Comment