~singpolyma/sgx-jmp

sgx-jmp/lib/postgres.rb -rw-r--r-- 576 bytes
4ace3417Stephen Paul Weber Log errors from rev.ai 8 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# frozen_string_literal: true

require "delegate"

class Postgres < SimpleDelegator
	def self.connect(**kwargs)
		new(PG::EM::ConnectionPool.new(**kwargs) { |conn|
			conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
			conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
		})
	end

	def query_one(sql, *args, field_names_as: :symbol, default: nil)
		query_defer(sql, args).then do |rows|
			rows.field_names_as(field_names_as)&.first || default
		end
	end

	def transaction(*args)
		super(*args) do |db|
			yield self.class.new(db)
		end
	end
end