Created
January 23, 2014 11:21
-
-
Save davybrion/8576995 to your computer and use it in GitHub Desktop.
easy way to create query classes that create prepared statements through the 'sequel' library... performance impact of this is really low (query string is only stored in memory once and query execution always goes through prepared statement)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Query | |
def self.query_name | |
:return_valid_query_name_in_subclass_or_you_will_get_really_weird_results | |
end | |
def self.create_prepared_statement(sql, placeholders_array) | |
sql = sql.super_strip unless Environment.log_sql? | |
DB[sql, *placeholders_array].prepare(:select, query_name) | |
end | |
def self.call_prepared_statement(parameter_hash) | |
DB.call(query_name, parameter_hash) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this query returns an array of hashes, where each hash contains the following keys: | |
# :category_id, :category_name, :number_of_companies | |
class GetCategoriesForCityQuery < Query | |
def self.query_name | |
:get_categories_for_city_query | |
end | |
create_prepared_statement %{ | |
select | |
cat.id as "category_id", | |
cat.name as "category_name", | |
count(com.*) as "number_of_companies" | |
from | |
categories cat | |
inner join categories_companies cat_com on cat.id = cat_com.category_id | |
inner join companies com on cat_com.company_id = com.id | |
where | |
com.city = ? and | |
com.zipcode = ? | |
group by | |
cat.id | |
}, [ :$city_name, :$zipcode ] | |
def self.execute(city_name, zipcode) | |
call_prepared_statement :city_name => city_name, :zipcode => zipcode | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment