postgres.rb

 1# frozen_string_literal: true
 2
 3require "delegate"
 4
 5class Postgres < SimpleDelegator
 6	def self.connect(**kwargs)
 7		new(PG::EM::ConnectionPool.new(**kwargs) { |conn|
 8			conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
 9			conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
10		})
11	end
12
13	# WARNING: this uses up a connection from the pool which never releases
14	# Use it only if you need the same connection for the life of the process
15	def acquire
16		conn = __getobj__.send(:acquire, Fiber.current) until conn
17		conn
18	end
19
20	def query_one(sql, *args, field_names_as: :symbol, default: nil)
21		query_defer(sql, args).then do |rows|
22			rows.field_names_as(field_names_as)&.first || default
23		end
24	end
25
26	def transaction(*args)
27		super(*args) do |db|
28			yield self.class.new(db)
29		end
30	end
31end