Class: Ensql::PostgresAdapter

Inherits:
Object
  • Object
show all
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.

Examples:

# Use with ActiveRecord's connection pool
Ensql.adapter = Ensql::PostgresAdapter.new(Ensql::ActiveRecordAdapter.pool)

# Use with Sequel's connection pool
DB = Sequel.connect(ENV['DATABASE_URL'])
Ensql.adapter = Ensql::PostgresAdapter.new(Ensql::SequelAdapter.pool(DB))

# Use with our own thread-safe connection pool
Ensql.adapter = Ensql::PostgresAdapter.pool { PG.connect ENV['DATABASE_URL'] }
Ensql.adapter = Ensql::PostgresAdapter.pool(size: 5) { PG.connect ENV['DATABASE_URL'] }

See Also:

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pool) ⇒ PostgresAdapter

Returns a new instance of PostgresAdapter.

Parameters:

  • pool (PoolWrapper, ConnectionPool, #with)

    a object that yields a PG::Connection using #with



49
50
51
52
53
54
# File 'lib/ensql/postgres_adapter.rb', line 49

def initialize(pool)
  @pool = pool
  @quoter = PG::TextEncoder::QuotedLiteral.new
  @result_type_map = @pool.with { |c| PG::BasicTypeMapForResults.new(c) }
  @query_type_map = @pool.with { |c| build_query_type_map(c) }
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'] }

Parameters:

  • pool_opts

    are sent straight to the ConnectionPool initializer.

Options Hash (**pool_opts):

  • timeout (Integer) — default: 5

    number of seconds to wait for a connection if none currently available.

  • size (Integer) — default: 5

    number of connections to pool.

Yield Returns:

  • (PG::Connection)

    a new connection.



44
45
46
# File 'lib/ensql/postgres_adapter.rb', line 44

def self.pool(**pool_opts, &connection_block)
  new ConnectionPool.new(**pool_opts, &connection_block)
end