Created
February 22, 2016 10:25
-
-
Save rept/134b9f017f1b994b88f9 to your computer and use it in GitHub Desktop.
Adapted raw_sql to do typing.
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 RawSQL | |
include ActiveRecord::ConnectionAdapters::Quoting | |
def initialize(filename) | |
@filename = filename | |
end | |
def result(params) | |
pg = ActiveRecord::Base.connection | |
@type_map ||= PG::BasicTypeMapForResults.new(pg.raw_connection) | |
res = pg.execute(query % quoted_parameters(params)) | |
res.type_map = @type_map #http://stackoverflow.com/questions/25331778/getting-typed-results-from-activerecord-raw-sql/30948357 | |
res | |
end | |
private | |
attr_reader :filename | |
def query | |
Rails.root.join('lib', 'sql', filename).read | |
end | |
def quoted_parameters(params) | |
params.each_with_object({}) do |(key, value), result| | |
result[key] = | |
if value.is_a?(Array) | |
value.map { |item| quote(item) }.join(', ') | |
elsif value.is_a?(Integer) | |
value | |
else | |
quote(value) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment