Skip to content

Instantly share code, notes, and snippets.

@rept
Created February 22, 2016 10:25
Show Gist options
  • Save rept/134b9f017f1b994b88f9 to your computer and use it in GitHub Desktop.
Save rept/134b9f017f1b994b88f9 to your computer and use it in GitHub Desktop.
Adapted raw_sql to do typing.
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