Sha256: 8f1938886d78f64bf0f7ddcc80b18f0fc7ff9d94eac4bf78c88b53087fcf3d9f

Contents?: true

Size: 1.76 KB

Versions: 9

Compression:

Stored size: 1.76 KB

Contents

require "pg"

# private
module Simple::SQL::Connection
  Logging = ::Simple::SQL::Logging

  def self.active_record_connection
    ActiveRecordConnection
  end

  def self.pg_connection(database_url)
    config = ::Simple::SQL::Config.parse_url(database_url)

    Logging.info "Connecting to #{database_url}"

    raw_connection = PG::Connection.new(config)
    PgConnection.new(raw_connection)
  end

  # A PgConnection object is built around a raw connection. It includes
  # the ConnectionAdapter, which implements ask, all, + friends, and also
  # includes a quiet simplistic Transaction implementation
  class PgConnection
    attr_reader :raw_connection

    def initialize(raw_connection)
      @raw_connection = raw_connection
    end

    def disconnect!
      return unless @raw_connection

      Logging.info "Disconnecting from database"
      @raw_connection.close
      @raw_connection = nil
    end

    include ::Simple::SQL::ConnectionAdapter          # all, ask, first, etc.
    include ::Simple::SQL::SimpleTransactions         # transactions

    extend Forwardable
    delegate [:wait_for_notify] => :raw_connection    # wait_for_notify
  end

  module ActiveRecordConnection
    extend self

    extend ::Simple::SQL::ConnectionAdapter           # all, ask, first, etc.

    extend Forwardable
    delegate [:transaction] => :connection            # transactions
    delegate [:wait_for_notify] => :connection        # wait_for_notify

    def raw_connection
      ActiveRecord::Base.connection.raw_connection
    end

    def disconnect!
      # This doesn't really disconnect. We hope ActiveRecord puts the connection
      # back into the connection pool instead.
      @raw_connection = nil
    end

    def connection
      ActiveRecord::Base.connection
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
simple-sql-0.4.17 lib/simple/sql/connection.rb
simple-sql-0.4.16 lib/simple/sql/connection.rb
simple-sql-0.4.15 lib/simple/sql/connection.rb
simple-sql-0.4.14 lib/simple/sql/connection.rb
simple-sql-0.4.13 lib/simple/sql/connection.rb
simple-sql-0.4.12 lib/simple/sql/connection.rb
simple-sql-0.4.11 lib/simple/sql/connection.rb
simple-sql-0.4.10 lib/simple/sql/connection.rb
simple-sql-0.4.9 lib/simple/sql/connection.rb