Class: RailsMultisite::ConnectionManagement

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

Defined Under Namespace

Classes: ConnectionSpecification, NullInstance

Constant Summary collapse

DEFAULT =
"default"

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_filename) ⇒ ConnectionManagement

Returns a new instance of ConnectionManagement.



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rails_multisite/connection_management.rb', line 91

def initialize(config_filename)
  @config_filename = config_filename

  @db_spec_cache = {}
  @default_spec = ConnectionSpecification.default
  @default_connection_handler = ActiveRecord::Base.connection_handler

  @reload_mutex = Mutex.new

  load_config!
end

Class Attribute Details

.asset_hostnamesObject

Returns the value of attribute asset_hostnames.



21
22
23
# File 'lib/rails_multisite/connection_management.rb', line 21

def asset_hostnames
  @asset_hostnames
end

Instance Attribute Details

#config_filenameObject (readonly)

Returns the value of attribute config_filename.



18
19
20
# File 'lib/rails_multisite/connection_management.rb', line 18

def config_filename
  @config_filename
end

#db_spec_cacheObject (readonly)

Returns the value of attribute db_spec_cache.



18
19
20
# File 'lib/rails_multisite/connection_management.rb', line 18

def db_spec_cache
  @db_spec_cache
end

Class Method Details

.clear_settings!Object



41
42
43
44
# File 'lib/rails_multisite/connection_management.rb', line 41

def clear_settings!
  instance.clear_settings!
  @instance = nil
end

.config_filename=(config_filename) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/rails_multisite/connection_management.rb', line 55

def config_filename=(config_filename)
  if config_filename.blank?
    @instance = nil
  else
    @instance = new(config_filename)
  end
end

.current_db_hostnamesObject



67
68
69
70
71
72
73
# File 'lib/rails_multisite/connection_management.rb', line 67

def current_db_hostnames
  config =
    (
      connection_spec(db: current_db) || ConnectionSpecification.current
    ).config
  config[:host_names] || [config[:host]]
end

.current_hostnameObject



63
64
65
# File 'lib/rails_multisite/connection_management.rb', line 63

def current_hostname
  current_db_hostnames.first
end

.default_config_filenameObject



37
38
39
# File 'lib/rails_multisite/connection_management.rb', line 37

def default_config_filename
  File.absolute_path(Rails.root.to_s + "/config/multisite.yml")
end

.handler_key(spec) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rails_multisite/connection_management.rb', line 75

def handler_key(spec)
  @handler_key_suffix ||=
    begin
      if ActiveRecord.respond_to?(:writing_role)
        "_#{ActiveRecord.writing_role}"
      elsif ActiveRecord::Base.respond_to?(:writing_role)
        "_#{ActiveRecord::Base.writing_role}"
      else
        ""
      end
    end

  :"#{spec.name}#{@handler_key_suffix}"
end

.instanceObject



51
52
53
# File 'lib/rails_multisite/connection_management.rb', line 51

def instance
  @instance || NullInstance.instance
end

.load_settings!Object



46
47
48
49
# File 'lib/rails_multisite/connection_management.rb', line 46

def load_settings!
  # no op only here backwards compat
  STDERR.puts "RailsMultisite::ConnectionManagement.load_settings! is deprecated"
end

Instance Method Details

#all_dbsObject



288
289
290
# File 'lib/rails_multisite/connection_management.rb', line 288

def all_dbs
  [DEFAULT] + db_spec_cache.keys.to_a
end

#clear_settings!Object



323
324
325
326
327
# File 'lib/rails_multisite/connection_management.rb', line 323

def clear_settings!
  db_spec_cache.each do |key, spec|
    connection_handlers.delete(handler_key(spec))
  end
end

#connection_spec(opts) ⇒ Object



319
320
321
# File 'lib/rails_multisite/connection_management.rb', line 319

def connection_spec(opts)
  opts[:host] ? @host_spec_cache[opts[:host]] : db_spec_cache[opts[:db]]
end

#current_dbObject



292
293
294
# File 'lib/rails_multisite/connection_management.rb', line 292

def current_db
  ConnectionSpecification.current.config[:db_key] || DEFAULT
end

#current_hostnameObject



296
297
298
# File 'lib/rails_multisite/connection_management.rb', line 296

def current_hostname
  ConnectionManagement.current_hostname
end

#default_connection_handler=(connection_handler) ⇒ Object



329
330
331
332
333
334
335
336
337
# File 'lib/rails_multisite/connection_management.rb', line 329

def default_connection_handler=(connection_handler)
  unless connection_handler.is_a?(
           ActiveRecord::ConnectionAdapters::ConnectionHandler
         )
    raise ArgumentError.new("Invalid connection handler")
  end

  @default_connection_handler = connection_handler
end

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



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/rails_multisite/connection_management.rb', line 229

def 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)
  unless connected
    ActiveRecord::Base.connection_handler.clear_active_connections!
  end
end

#establish_connection(db: nil, host: nil, raise_on_missing: true) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/rails_multisite/connection_management.rb', line 158

def establish_connection(db: nil, host: nil, raise_on_missing: true)
  db = db.to_s

  spec =
    if db == DEFAULT
      @default_spec
    elsif (found = connection_spec(db: db, host: host))
      found
    elsif raise_on_missing
      raise UnknownSiteError.new(host || db)
    else
      @default_spec
    end

  handler = nil
  if spec != @default_spec
    handler = connection_handlers[handler_key(spec)]
    unless handler
      handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
      handler.establish_connection(spec.config)
      connection_handlers[handler_key(spec)] = handler
    end
  else
    handler = @default_connection_handler
  end

  ActiveRecord::Base.connection_handler = handler
end

#has_db?(db) ⇒ Boolean

Returns:

  • (Boolean)


154
155
156
# File 'lib/rails_multisite/connection_management.rb', line 154

def has_db?(db)
  db == DEFAULT || !!db_spec_cache[db]
end

#host(env) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/rails_multisite/connection_management.rb', line 300

def host(env)
  if host = env["RAILS_MULTISITE_HOST"]
    return host
  end

  request = Rack::Request.new(env)

  host =
    if request.params["__ws"] &&
         self.class.asset_hostnames&.include?(request.host)
      request.cookies.clear
      request.params["__ws"]
    else
      request.host
    end

  env["RAILS_MULTISITE_HOST"] = host
end

#load_config!Object



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
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/rails_multisite/connection_management.rb', line 103

def load_config!
  configs = YAML.safe_load(File.open(config_filename))

  no_prepared_statements =
    @default_spec.config[:prepared_statements] == false

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

  # Build a hash of db name => spec
  new_db_spec_cache = ConnectionSpecification.db_spec_cache(configs)
  new_db_spec_cache.each do |k, v|
    # If spec already existed, use the old version
    if v&.to_hash == db_spec_cache[k]&.to_hash
      new_db_spec_cache[k] = db_spec_cache[k]
    end
  end

  # Build a hash of hostname => spec
  new_host_spec_cache = {}
  configs.each do |k, v|
    next unless v["host_names"]
    v["host_names"].each do |host|
      new_host_spec_cache[host] = new_db_spec_cache[k]
    end
  end

  # Add the default hostnames as well
  @default_spec.config[:host_names].each do |host|
    new_host_spec_cache[host] = @default_spec
  end

  removed_dbs = db_spec_cache.keys - new_db_spec_cache.keys
  removed_specs = db_spec_cache.values_at(*removed_dbs)

  @host_spec_cache = new_host_spec_cache
  @db_spec_cache = new_db_spec_cache

  # Clean up connection handler cache.
  removed_specs.each { |s| connection_handlers.delete(handler_key(s)) }
end

#reloadObject



150
151
152
# File 'lib/rails_multisite/connection_management.rb', line 150

def reload
  @reload_mutex.synchronize { load_config! }
end

#with_connection(db = DEFAULT, raise_on_missing: true) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/rails_multisite/connection_management.rb', line 208

def with_connection(db = DEFAULT, raise_on_missing: true)
  old = current_db
  connected = ActiveRecord::Base.connection_pool.connected?

  if !(connected && db == old)
    establish_connection(db: db, raise_on_missing: raise_on_missing)
  end
  rval = yield db

  if !(connected && db == old)
    ActiveRecord::Base.connection_handler.clear_active_connections!

    establish_connection(db: old, raise_on_missing: false)
    unless connected
      ActiveRecord::Base.connection_handler.clear_active_connections!
    end
  end

  rval
end

#with_hostname(hostname, raise_on_missing: true) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/rails_multisite/connection_management.rb', line 187

def with_hostname(hostname, raise_on_missing: true)
  old = current_hostname
  connected = ActiveRecord::Base.connection_pool.connected?

  if !(connected && hostname == old)
    establish_connection(host: hostname, raise_on_missing: raise_on_missing)
  end
  rval = yield hostname

  if !(connected && hostname == old)
    ActiveRecord::Base.connection_handler.clear_active_connections!

    establish_connection(host: old, raise_on_missing: false)
    if !connected
      ActiveRecord::Base.connection_handler.clear_active_connections!
    end
  end

  rval
end