Sha256: 7443cdde9aaddc3fe07e08eba76f791dfb6b85490f9c44701a26e023bff4ef4e

Contents?: true

Size: 1.87 KB

Versions: 14

Compression:

Stored size: 1.87 KB

Contents

# The ConnectionManager manages a pool of ActiveRecord::Base classes.
#
# ActiveRecord assigns a connection_pool to a class. If you want to connect to
# multiple detabases you must inherit from ActiveRecord::Base. This is what
# we do dynamically in this ConnectionManager.
#
# Note that connections to the same database are always shared within a single
# ConnectionPool.
module Simple::SQL
  module ConnectionManager
    extend self

    def disconnect_all!
      ActiveRecord::Base.connection_pool.disconnect! if ActiveRecord::Base.connected?

      connection_classes = connection_class_by_url.values
      connection_classes.select(&:connected?).map(&:connection_pool).each(&:disconnect!)
      connection_class_by_url.clear
    end

    def connection_class(url)
      connection_class_by_url[url] ||= create_connection_class(url)
    end

    private

    def connection_class_by_url
      @connection_class_by_url ||= {}
    end

    # ActiveRecord needs a class name in order to connect.
    module WritableClassName
      attr_accessor :name
    end

    def create_connection_class(url)
      Class.new(ActiveRecord::Base).tap do |klass|
        klass.extend WritableClassName
        klass.name = "Simple::SQL::Connection::ExplicitConnection::Adapter/#{url}"

        klass.establish_connection url
        connection_pool = klass.connection_pool
        connection_pool_stats = {
          size: connection_pool.size,
          automatic_reconnect: connection_pool.automatic_reconnect,
          checkout_timeout: connection_pool.checkout_timeout
        }
        ::Simple::SQL.logger.info "#{URI.without_password url}: connected to connection pool w/#{connection_pool_stats.inspect}"
      end
    end
  end
end

module URI
  def self.without_password(uri)
    uri = URI.parse(uri) unless uri.is_a?(URI)
    uri = uri.dup
    uri.password = "*" * uri.password.length if uri.password
    uri
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
simple-sql-0.5.37 lib/simple/sql/connection_manager.rb
simple-sql-0.5.36 lib/simple/sql/connection_manager.rb
simple-sql-0.5.35 lib/simple/sql/connection_manager.rb
simple-sql-0.5.34 lib/simple/sql/connection_manager.rb
simple-sql-0.5.33 lib/simple/sql/connection_manager.rb
simple-sql-0.5.32 lib/simple/sql/connection_manager.rb
simple-sql-0.5.31 lib/simple/sql/connection_manager.rb
simple-sql-0.5.30 lib/simple/sql/connection_manager.rb
simple-sql-0.5.29 lib/simple/sql/connection_manager.rb
simple-sql-0.5.28 lib/simple/sql/connection_manager.rb
simple-sql-0.5.27 lib/simple/sql/connection_manager.rb
simple-sql-0.5.26 lib/simple/sql/connection_manager.rb
simple-sql-0.5.25 lib/simple/sql/connection_manager.rb
simple-sql-0.5.24 lib/simple/sql/connection_manager.rb