Module: Switchman::ActiveRecord::ConnectionPool

Defined in:
lib/switchman/active_record/connection_pool.rb

Instance Method Summary collapse

Instance Method Details

#checkout_new_connectionObject



27
28
29
30
31
# 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) ⇒ Object



33
34
35
36
37
38
39
# 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_schemaObject



20
21
22
23
24
25
# 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) ⇒ Object



41
42
43
44
45
# 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) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# 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

#shardObject



8
9
10
# File 'lib/switchman/active_record/connection_pool.rb', line 8

def shard
  shard_stack.last || Shard.default
end

#shard_stackObject



12
13
14
15
16
17
18
# 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) ⇒ Object



59
60
61
62
63
# 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