module Switchman::ActiveRecord::ConnectionPool

Public Instance Methods

checkout_new_connection() click to toggle source
Calls superclass method
# File lib/switchman/active_record/connection_pool.rb, line 27
def checkout_new_connection
  conn = super
  conn.shard = shard
  conn
end
connection(switch_shard: true) click to toggle source
Calls superclass method
# File lib/switchman/active_record/connection_pool.rb, line 33
def connection(switch_shard: true)
  conn = super()
  raise NonExistentShardError if shard.new_record?

  switch_database(conn) if conn.shard != shard && switch_shard
  conn
end
default_schema() click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 20
def default_schema
  connection unless @schemas
  # default shard will not switch databases immediately, so it won't be set yet
  @schemas ||= connection.current_schemas
  @schemas.first
end
release_connection(with_id = Thread.current) click to toggle source
Calls superclass method
# File lib/switchman/active_record/connection_pool.rb, line 41
def release_connection(with_id = Thread.current)
  super(with_id)

  flush
end
remove_shard!(shard) click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 47
def remove_shard!(shard)
  synchronize do
    # The shard might be currently active, so we need to update our own shard
    self.shard = Shard.default if self.shard == shard
    # Update out any connections that may be using this shard
    @connections.each do |conn|
      # This will also update the connection's shard to the default shard
      switch_database(conn) if conn.shard == shard
    end
  end
end
shard() click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 8
def shard
  shard_stack.last || Shard.default
end
shard_stack() click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 12
def shard_stack
  unless (shard_stack = Thread.current.thread_variable_get(tls_key))
    shard_stack = Concurrent::Array.new
    Thread.current.thread_variable_set(tls_key, shard_stack)
  end
  shard_stack
end
switch_database(conn) click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 59
def switch_database(conn)
  @schemas = conn.current_schemas if !@schemas && conn.adapter_name == 'PostgreSQL' && !shard.database_server.config[:shard_name]

  conn.shard = shard
end

Private Instance Methods

tls_key() click to toggle source
# File lib/switchman/active_record/connection_pool.rb, line 67
def tls_key
  "#{object_id}_shard".to_sym
end