Class: Ensql::PostgresAdapter
- Inherits:
-
Object
- Object
- Ensql::PostgresAdapter
- Includes:
- Adapter
- Defined in:
- lib/ensql/postgres_adapter.rb
Overview
Wraps a pool of PG connections to implement the Adapter interface. The adapter can use a 3rd-party pool (e.g. from ActiveRecord of Sequel) or manage its own using the simple connection_pool gem.
This adapter is much faster and offers much better PostgreSQL specific parameter interpolation than the framework adapters. See #query_type_map for options.
Class Method Summary collapse
-
.pool(**pool_opts, &connection_block) ⇒ Object
Set up a connection pool using the supplied block to initialise connections.
Instance Method Summary collapse
-
#initialize(pool) ⇒ PostgresAdapter
constructor
A new instance of PostgresAdapter.
-
#query_type_map ⇒ PG::TypeMapByClass
A map for encoding Ruby objects into PostgreSQL literals based on their class.
Constructor Details
#initialize(pool) ⇒ PostgresAdapter
Returns a new instance of PostgresAdapter.
50 51 52 53 |
# File 'lib/ensql/postgres_adapter.rb', line 50 def initialize(pool) @pool = pool @quoter = PG::TextEncoder::QuotedLiteral.new end |
Class Method Details
.pool(**pool_opts, &connection_block) ⇒ Object
Set up a connection pool using the supplied block to initialise connections.
PostgresAdapter.pool(size: 20) { PG.connect ENV['DATABASE_URL'] }
45 46 47 |
# File 'lib/ensql/postgres_adapter.rb', line 45 def self.pool(**pool_opts, &connection_block) new ConnectionPool.new(**pool_opts, &connection_block) end |
Instance Method Details
#query_type_map ⇒ PG::TypeMapByClass
A map for encoding Ruby objects into PostgreSQL literals based on their class. You can add additional class mappings to suit your needs. See https://rubydoc.info/gems/pg/PG/BasicTypeRegistry for details of adding your own encoders and decoders.
# Encode any `IPAddr` objects for interpolation using the `InetEncoder`.
Ensql.adapter.query_type_map[IPAddr] = InetEncoder.new
# Deserialize `inet` columns as IPAddr objects.
PG::BasicTypeRegistry.register_type(0, 'inet', InetEncoder, InetDecoder)
67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/ensql/postgres_adapter.rb', line 67 def query_type_map @query_type_map ||= @pool.with do |connection| map = PG::BasicTypeMapForQueries.new(connection) # Ensure encoders are set up for old versions of the pg gem map[Date] ||= PG::TextEncoder::Date.new map[Time] ||= PG::TextEncoder::TimestampWithoutTimeZone.new map[Hash] ||= PG::TextEncoder::JSON.new map[BigDecimal] ||= NumericEncoder.new map end end |