Class: RailsMultisite::ConnectionManagement

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_multisite/connection_management.rb

Constant Summary collapse

CONFIG_FILE =
'config/multisite.yml'
DEFAULT =
'default'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, config = nil) ⇒ ConnectionManagement

Returns a new instance of ConnectionManagement.



207
208
209
# File 'lib/rails_multisite/connection_management.rb', line 207

def initialize(app, config = nil)
  @app = app
end

Class Method Details

.all_dbsObject



139
140
141
142
143
144
145
146
# File 'lib/rails_multisite/connection_management.rb', line 139

def self.all_dbs
  ["default"] +
    if defined?(@@db_spec_cache) && @@db_spec_cache
      @@db_spec_cache.keys.to_a
    else
      []
    end
end

.clear_settings!Object



165
166
167
168
169
# File 'lib/rails_multisite/connection_management.rb', line 165

def self.clear_settings!
  @@db_spec_cache = nil
  @@host_spec_cache = nil
  @@default_spec = nil
end

.config_filenameObject



156
157
158
# File 'lib/rails_multisite/connection_management.rb', line 156

def self.config_filename
  @@config_filename ||= File.absolute_path(Rails.root.to_s + "/" + RailsMultisite::ConnectionManagement::CONFIG_FILE)
end

.config_filename=(config_filename) ⇒ Object



152
153
154
# File 'lib/rails_multisite/connection_management.rb', line 152

def self.config_filename=(config_filename)
  @@config_filename = config_filename
end

.connection_spec(opts) ⇒ Object



231
232
233
234
235
236
237
# File 'lib/rails_multisite/connection_management.rb', line 231

def self.connection_spec(opts)
  if opts[:host]
    @@host_spec_cache[opts[:host]]
  else
    @@db_spec_cache[opts[:db]]
  end
end

.current_dbObject



148
149
150
# File 'lib/rails_multisite/connection_management.rb', line 148

def self.current_db
  ActiveRecord::Base.connection_pool.spec.config[:db_key] || "default"
end

.current_hostnameObject



160
161
162
163
# File 'lib/rails_multisite/connection_management.rb', line 160

def self.current_hostname
  config = ActiveRecord::Base.connection_pool.spec.config
  config[:host_names].nil? ? config[:host] : config[:host_names].first
end

.each_connection(opts = nil, &blk) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/rails_multisite/connection_management.rb', line 81

def self.each_connection(opts=nil, &blk)

  old = current_db
  connected = ActiveRecord::Base.connection_pool.connected?

  queue = nil
  threads = nil

  if (opts && (threads = opts[:threads]))
    queue = Queue.new
    all_dbs.each{|db| queue << db}
  end

  errors = nil

  if queue
    threads.times.map do
      Thread.new do

        while true
          begin
            db = queue.deq(true)
          rescue ThreadError
            db = nil
          end

          break unless db

          establish_connection(:db => db)
          # no choice but to rescue, should probably log

          begin
            blk.call(db)
          rescue => e
            (errors ||= []) << e
          end
          ActiveRecord::Base.connection_handler.clear_active_connections!
        end
      end
    end.map(&:join)
  else
    all_dbs.each do |db|
      establish_connection(:db => db)
      blk.call(db)
      ActiveRecord::Base.connection_handler.clear_active_connections!
    end
  end

  if errors && errors.length > 0
    raise StandardError, "Failed to run queries #{errors.inspect}"
  end


ensure
  establish_connection(:db => old)
  ActiveRecord::Base.connection_handler.clear_active_connections! unless connected
end

.establish_connection(opts) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails_multisite/connection_management.rb', line 15

def self.establish_connection(opts)
  if opts[:db] == DEFAULT && (!defined?(@@default_spec) || !@@default_spec)
    # don't do anything .. handled implicitly
  else
    spec = connection_spec(opts) || @@default_spec
    handler = nil
    if spec != @@default_spec
      handler = @@connection_handlers[spec]
      unless handler
        handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
        handler.establish_connection(ActiveRecord::Base, spec)
        @@connection_handlers[spec] = handler
      end
    else
      handler = @@default_connection_handler
      if !@@established_default
        handler.establish_connection(ActiveRecord::Base, spec)
        @@established_default = true
      end
    end

    ActiveRecord::Base.connection_handler = handler
  end
end

.has_db?(db) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
9
# File 'lib/rails_multisite/connection_management.rb', line 6

def self.has_db?(db)
  return true if db == DEFAULT
  (defined? @@db_spec_cache) && @@db_spec_cache && @@db_spec_cache[db]
end

.host(env) ⇒ Object



211
212
213
214
# File 'lib/rails_multisite/connection_management.rb', line 211

def self.host(env)
  request = Rack::Request.new(env)
  request['__ws'] || request.host
end

.load_settings!Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rails_multisite/connection_management.rb', line 171

def self.load_settings!
  spec_klass = ActiveRecord::ConnectionAdapters::ConnectionSpecification
  configs = YAML::load(File.open(self.config_filename))

  no_prepared_statements = ActiveRecord::Base.configurations[Rails.env]["prepared_statements"] == false

  configs.each do |k,v|
    raise ArgumentError.new("Please do not name any db default!") if k == "default"
    v[:db_key] = k
    v[:prepared_statements] = false if no_prepared_statements
  end

  @@db_spec_cache = Hash[*configs.map do |k, data|
    [k, spec_klass::Resolver.new(configs).spec(k)]
  end.flatten]

  @@host_spec_cache = {}
  configs.each do |k,v|
    next unless v["host_names"]
    v["host_names"].each do |host|
      @@host_spec_cache[host] = @@db_spec_cache[k]
    end
  end

  @@default_spec = spec_klass::Resolver.new(ActiveRecord::Base.configurations).spec(Rails.env)
  ActiveRecord::Base.configurations[Rails.env]["host_names"].each do |host|
    @@host_spec_cache[host] = @@default_spec
  end

  @@default_connection_handler = ActiveRecord::Base.connection_handler

  @@connection_handlers = {}
  @@established_default = false
end

.rails4?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/rails_multisite/connection_management.rb', line 11

def self.rails4?
  !!(Rails.version =~ /^4/)
end

.with_connection(db = "default") ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rails_multisite/connection_management.rb', line 64

def self.with_connection(db = "default")
  old = current_db
  connected = ActiveRecord::Base.connection_pool.connected?

  establish_connection(:db => db) unless connected && db == old
  rval = yield db

  unless connected && db == old
    ActiveRecord::Base.connection_handler.clear_active_connections!

    establish_connection(:db => old)
    ActiveRecord::Base.connection_handler.clear_active_connections! unless connected
  end

  rval
end

.with_hostname(hostname) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rails_multisite/connection_management.rb', line 40

def self.with_hostname(hostname)

  unless defined? @@db_spec_cache
    # just fake it for non multisite
    yield hostname
    return
  end

  old = current_hostname
  connected = ActiveRecord::Base.connection_pool.connected?

  establish_connection(:host => hostname) unless connected && hostname == old
  rval = yield hostname

  unless connected && hostname == old
    ActiveRecord::Base.connection_handler.clear_active_connections!

    establish_connection(:host => old)
    ActiveRecord::Base.connection_handler.clear_active_connections! unless connected
  end

  rval
end

Instance Method Details

#call(env) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/rails_multisite/connection_management.rb', line 216

def call(env)
  host = self.class.host(env)
  begin

    #TODO: add a callback so users can simply go to a domain to register it, or something
    return [404, {}, ["not found"]] unless @@host_spec_cache[host]

    ActiveRecord::Base.connection_handler.clear_active_connections!
    self.class.establish_connection(:host => host)
    @app.call(env)
  ensure
    ActiveRecord::Base.connection_handler.clear_active_connections!
  end
end