Commit c5d5cafc authored by Ohad Dahan's avatar Ohad Dahan

Slight refactoring

parent 575a22e9
require "nativepluck/version"
module Nativepluck
class << self
attr_accessor :nativepluck_type_map_for_results, :nativepluck_type_map_for_queries
attr_accessor :original_type_map_for_results, :original_type_map_for_queries
end
def self.included(klass)
klass.extend(ClassMethods)
$nativepluck_type_map_for_results = PG::BasicTypeMapForResults.new ActiveRecord::Base.connection.raw_connection
$nativepluck_type_map_for_queries = PG::BasicTypeMapForQueries.new ActiveRecord::Base.connection.raw_connection
$original_type_map_for_results = ActiveRecord::Base.connection.raw_connection.type_map_for_results
$original_type_map_for_queries = ActiveRecord::Base.connection.raw_connection.type_map_for_queries
@nativepluck_type_map_for_results = PG::BasicTypeMapForResults.new ActiveRecord::Base.connection.raw_connection
@nativepluck_type_map_for_queries = PG::BasicTypeMapForQueries.new ActiveRecord::Base.connection.raw_connection
@original_type_map_for_results = ActiveRecord::Base.connection.raw_connection.type_map_for_results
@original_type_map_for_queries = ActiveRecord::Base.connection.raw_connection.type_map_for_queries
end
def self.set_pg_native_casters
ActiveRecord::Base.connection.raw_connection.type_map_for_results = Nativepluck.nativepluck_type_map_for_results
ActiveRecord::Base.connection.raw_connection.type_map_for_queries = Nativepluck.nativepluck_type_map_for_queries
end
def self.return_original_casters
ActiveRecord::Base.connection.raw_connection.type_map_for_results = Nativepluck.original_type_map_for_results
ActiveRecord::Base.connection.raw_connection.type_map_for_queries = Nativepluck.original_type_map_for_queries
end
module ClassMethods
def nativepluck(*columns, **opts)
Nativepluck.set_pg_native_casters
raise ArgumentError.new('No columns to pluck were provided') if columns.size == 0
ActiveRecord::Base.connection.raw_connection.type_map_for_results = $nativepluck_type_map_for_results
ActiveRecord::Base.connection.raw_connection.type_map_for_queries = $nativepluck_type_map_for_queries
results = ActiveRecord::Base.connection.raw_connection.async_exec(
"select #{columns.join(',')} from #{self.table_name} #{"limit #{opts[:limit]}" if opts[:limit]}"
)
columns.size == 1 ? out = results.column_values(0) : out = results.values
ActiveRecord::Base.connection.raw_connection.type_map_for_results = $original_type_map_for_results
ActiveRecord::Base.connection.raw_connection.type_map_for_queries = $original_type_map_for_queries
Nativepluck.return_original_casters
return out
end
end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment