Class: Ekylibre::Tenant

Inherits:
Object
  • Object
show all
Defined in:
lib/ekylibre/tenant.rb

Constant Summary collapse

AGGREGATION_NAME =
'__all__'.freeze

Class Method Summary collapse

Class Method Details

.add(name) ⇒ Object

Adds a tenant in config. No schema are created.


123
124
125
126
127
# File 'lib/ekylibre/tenant.rb', line 123

def add(name)
  list << name unless list.include?(name)
  write
  # byebug
end

.check!(name, options = {}) ⇒ Object

Tests existence of a tenant in DB and removes it if not exist


20
21
22
23
24
25
# File 'lib/ekylibre/tenant.rb', line 20

def check!(name, options = {})
  if list.include?(name)
    switch_to_database_for(name)
    drop(name, options) unless Apartment.connection.schema_exists? name
  end
end

.clear!Object


254
255
256
257
258
# File 'lib/ekylibre/tenant.rb', line 254

def clear!
  list unless @list
  @list[env] = []
  write
end

.correct_tenants_with_migration_problem!Object


314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/ekylibre/tenant.rb', line 314

def correct_tenants_with_migration_problem!
  tenants = list_tenants_with_migration_problem

  tenants.each do |tenant|
    Ekylibre::Tenant.switch! tenant[:name]

    connection = ActiveRecord::Base.connection
    connection.execute('INSERT INTO schema_migrations SELECT * FROM public.schema_migrations')

    puts (tenant[:name] + ' : done').yellow
  end

  load!

  puts 'Task done'.blue
end

.create(name) ⇒ Object

Create a new tenant with tables and co

Raises:


46
47
48
49
50
51
52
53
54
# File 'lib/ekylibre/tenant.rb', line 46

def create(name)
  name = name.to_s
  check!(name)
  raise TenantError, 'Already existing tenant' if exist?(name)
  create_database_for!(name) if multi_database > 0
  add(name)
  Apartment::Tenant.create(name)
  # byebug
end

.create_aggregation_schema!Object


275
276
277
# File 'lib/ekylibre/tenant.rb', line 275

def create_aggregation_schema!
  create_aggregation_views_schema!
end

.create_aggregation_views_schema!Object


279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/ekylibre/tenant.rb', line 279

def create_aggregation_views_schema!
  raise 'No tenant to build an aggregation schema' if list.empty?
  name = AGGREGATION_NAME
  connection = ActiveRecord::Base.connection
  connection.execute("CREATE SCHEMA IF NOT EXISTS #{name};")
  Ekylibre::Schema.tables.keys.each do |table|
    connection.execute "DROP VIEW IF EXISTS #{name}.#{table}"
    columns = Ekylibre::Schema.columns(table)
    queries = list.collect do |tenant|
      "SELECT '#{tenant}' AS tenant_name, " + columns.collect { |c| c[:name] }.join(', ') + " FROM #{tenant}.#{table}"
    end
    query = "CREATE VIEW #{name}.#{table} AS " + queries.join(' UNION ALL ')
    connection.execute(query)
  end
end

.create_database_for!(name, magnitude = nil) ⇒ Object


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/ekylibre/tenant.rb', line 60

def create_database_for!(name, magnitude = nil)
  magnitude ||= multi_database
  if magnitude > 0
    database = database_for(name, magnitude)
    ActiveRecord::Base.connection.create_database(database)
    switch_to_database_for(name, magnitude)
    Ekylibre::Schema.setup_extensions
    ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths)
    Ekylibre::Schema.model_names.each do |model_name|
      model_name.to_s.constantize.reset_column_information
    end
    Rails.logger.info "Created #{database}"
  end
rescue ActiveRecord::StatementInvalid => e
  # NOP
end

.currentObject

Returns the current tenant


28
29
30
31
32
33
# File 'lib/ekylibre/tenant.rb', line 28

def current
  unless name = Apartment::Tenant.current
    raise TenantError, 'No current tenant'
  end
  name
end

.database_for(name, magnitude = nil) ⇒ Object


91
92
93
94
95
96
97
98
99
# File 'lib/ekylibre/tenant.rb', line 91

def database_for(name, magnitude = nil)
  conf = Rails.configuration.database_configuration[Rails.env]
  magnitude ||= multi_database
  if magnitude > 0
    conf['database'] + '_' + Digest::MD5.hexdigest(name)[0..(magnitude - 1)]
  else
    conf['database']
  end
end

.drop(name, options = {}) ⇒ Object

Drop tenant

Raises:


138
139
140
141
142
143
144
145
146
# File 'lib/ekylibre/tenant.rb', line 138

def drop(name, options = {})
  name = name.to_s
  raise TenantError, "Unexistent tenant: #{name}" unless exist?(name)
  switch_to_database_for(name)
  Apartment::Tenant.drop(name) if Apartment.connection.schema_exists? name
  FileUtils.rm_rf private_directory(name) unless options[:keep_files]
  @list[env].delete(name)
  write
end

.drop_aggregation_schema!Object


271
272
273
# File 'lib/ekylibre/tenant.rb', line 271

def drop_aggregation_schema!
  ActiveRecord::Base.connection.execute("CREATE SCHEMA IF NOT EXISTS #{AGGREGATION_NAME};")
end

.dump(name, options = {}) ⇒ Object

Dump database and files data to a zip archive with specific places This archive is database independent


172
173
174
175
176
177
178
179
# File 'lib/ekylibre/tenant.rb', line 172

def dump(name, options = {})
  raise "Tenant doesn't exist: #{name}" unless exist?(name)
  verbose = !options[:verbose].is_a?(FalseClass)
  start = Time.current
  dump_v3(name, options)
  duration = Time.current - start
  puts "Done! (#{duration.round(2)}s)".yellow if verbose
end

.exist?(name) ⇒ Boolean

Tests existence of a tenant

Returns:

  • (Boolean)

14
15
16
# File 'lib/ekylibre/tenant.rb', line 14

def exist?(name)
  list.include?(name)
end

.hostObject


35
36
37
# File 'lib/ekylibre/tenant.rb', line 35

def host
  "#{current}.#{ENV['HOST_DOMAIN_NAME'] || 'example.org'}"
end

.listObject


260
261
262
263
264
# File 'lib/ekylibre/tenant.rb', line 260

def list
  load! unless @list
  @list[env] ||= []
  @list[env]
end

.list_tenant_with_table_not_exist(table_name) ⇒ Object


331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/ekylibre/tenant.rb', line 331

def list_tenant_with_table_not_exist(table_name)
  tenants = []

  list.each do |tenant|
    Ekylibre::Tenant.switch! tenant

    connection = ActiveRecord::Base.connection
    result = connection.execute(
      "SELECT EXISTS(
        SELECT 1
        FROM information_schema.tables
        WHERE table_schema = current_schema()
        AND table_name = '#{table_name}'
      )"
    ).to_a

    next if result.first.value?('t')

    migration_version = ActiveRecord::Migrator.current_version
    tenants << { name: tenant, migration_version: migration_version }
  end

  tenants
end

.list_tenants_with_migration_problemObject


299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/ekylibre/tenant.rb', line 299

def list_tenants_with_migration_problem
  tenants = []

  list.each do |tenant|
    Ekylibre::Tenant.switch! tenant
    migration_version = ActiveRecord::Migrator.current_version

    next if migration_version.nonzero?

    tenants << { name: tenant, version: migration_version }
  end

  tenants
end

.load!Object


266
267
268
269
# File 'lib/ekylibre/tenant.rb', line 266

def load!
  @list = (File.exist?(config_file) ? YAML.load_file(config_file) : {})
  @list ||= {}
end

.migrate(name, options = {}) ⇒ Object

Migrate tenant to wanted version


149
150
151
152
153
# File 'lib/ekylibre/tenant.rb', line 149

def migrate(name, options = {})
  switch(name) do
    ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, options[:to])
  end
end

.multi_databaseObject


56
57
58
# File 'lib/ekylibre/tenant.rb', line 56

def multi_database
  Rails.env.test? ? 0 : ENV['MULTI_DATABASE'].to_i
end

.private_directory(name = nil) ⇒ Object

Returns the private directory of the current tenant If tenant name given, it returns its private_directory


41
42
43
# File 'lib/ekylibre/tenant.rb', line 41

def private_directory(name = nil)
  Ekylibre.root.join('private', name || current)
end

.remove_last_migration_and_migrate!(tenant_name) ⇒ Object


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/ekylibre/tenant.rb', line 356

def remove_last_migration_and_migrate!(tenant_name)
  Ekylibre::Tenant.switch! tenant_name

  ActiveRecord::Base.connection.execute(
    "DELETE FROM schema_migrations
     WHERE version IN (
        SELECT version
        FROM schema_migrations
        ORDER BY version DESC
        LIMIT 1
    )"
  )

  ActiveRecord::Migrator.migrate 'db/migrate'

  load!
end

.rename(old, new) ⇒ Object

Raises:


155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/ekylibre/tenant.rb', line 155

def rename(old, new)
  return if old == new
  check!(old)
  raise TenantError, "Unexistent tenant: #{old}" unless Apartment.connection.schema_exists?(old)
  raise TenantError, "Tenant already exists: #{new}" if Apartment.connection.schema_exists?(new)
  ActiveRecord::Base.connection.execute("ALTER SCHEMA #{old.to_s.inspect} RENAME TO #{new.to_s.inspect};")
  if private_directory(old).exist?
    FileUtils.rm_rf(private_directory(new))
    FileUtils.mv(private_directory(old), private_directory(new))
  end
  @list[env].delete(old.to_s)
  @list[env] << new.to_s
  write
end

.reset_search_path!Object


295
296
297
# File 'lib/ekylibre/tenant.rb', line 295

def reset_search_path!
  ActiveRecord::Base.connection.schema_search_path = Ekylibre::Application.config.database_configuration[::Rails.env]['schema_search_path']
end

.restore(archive_file, options = {}) ⇒ Object

Restore an archive


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/ekylibre/tenant.rb', line 182

def restore(archive_file, options = {})
  code = options[:tenant] || Time.zone.now.to_i.to_s(36) + rand(999_999_999).to_s(36)
  verbose = !options[:verbose].is_a?(FalseClass)

  archive_path = Rails.root.join('tmp', 'archives', "#{code}-restore")
  FileUtils.rm_rf(archive_path)
  FileUtils.mkdir_p(archive_path)

  puts "Decompressing #{archive_file.basename} to #{archive_path.basename}...".yellow if verbose
  Zip::File.open(archive_file.to_s) do |zile|
    zile.each do |entry|
      entry.extract(archive_path.join(entry.name))
    end
  end

  puts 'Checking archive...'.yellow if verbose
  if !archive_path.join('manifest.yml').exist?
    raise 'Cannot not handle this archive'
  else
    manifest = YAML.load_file(archive_path.join('manifest.yml')).symbolize_keys
    # Bugfix
    if manifest[:tenant] == 'Ekylibre::Tenant'
      Dir.chdir(archive_path) do
        f = Dir.glob('*.sql').first
        manifest[:tenant] = f.gsub('.sql', '') if f
      end
    end
    unless name = options[:tenant] || manifest[:tenant]
      raise 'No given name for the tenant'
    end

    format_version = manifest[:format_version].to_s
    if format_version == '3'
      restore_v3(archive_path, name, options.merge(dump_file: archive_path.join("#{manifest[:tenant]}.sql")))
    elsif ['2.0', '2'].include? format_version
      restore_v2(archive_path, name, options)
    else
      raise "Cannot handle this version of archive: #{format_version.inspect}"
    end
  end
  FileUtils.rm_rf(archive_path)
end

.setup!(name, options = {}) ⇒ Object

Add a tenant in config without creating it Nothing is done if already exist


131
132
133
134
135
# File 'lib/ekylibre/tenant.rb', line 131

def setup!(name, options = {})
  check!(name, options)
  create(name) unless exist?(name)
  switch!(name)
end

.switch(name, &block) ⇒ Object

Change current tenant


226
227
228
229
# File 'lib/ekylibre/tenant.rb', line 226

def switch(name, &block)
  raise 'Need block to use Ekylibre::Tenant.switch' unless block_given?
  Apartment::Tenant.switch(name, &block)
end

.switch!(name) ⇒ Object Also known as: current=


231
232
233
# File 'lib/ekylibre/tenant.rb', line 231

def switch!(name)
  Apartment::Tenant.switch!(name)
end

.switch_default!Object


237
238
239
240
241
242
243
# File 'lib/ekylibre/tenant.rb', line 237

def switch_default!
  if list.empty?
    raise TenantError, 'No default tenant'
  else
    switch!(list.first)
  end
end

.switch_each(&_block) ⇒ Object

Browse all tenant to make actions on it


246
247
248
249
250
251
252
# File 'lib/ekylibre/tenant.rb', line 246

def switch_each(&_block)
  list.each do |tenant|
    switch(tenant) do
      yield tenant
    end
  end
end

.switch_to_database(database) ⇒ Object


86
87
88
89
# File 'lib/ekylibre/tenant.rb', line 86

def switch_to_database(database)
  configuration = Rails.configuration.database_configuration[Rails.env]
  Apartment.establish_connection configuration.merge('database' => database)
end

.switch_to_database_for(name, magnitude = nil) ⇒ Object


77
78
79
80
81
82
83
84
# File 'lib/ekylibre/tenant.rb', line 77

def switch_to_database_for(name, magnitude = nil)
  magnitude ||= multi_database
  if magnitude > 0
    database = database_for(name, magnitude)
    switch_to_database(database)
    database
  end
end

.with_pg_env(_name) ⇒ Object


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/ekylibre/tenant.rb', line 101

def with_pg_env(_name)
  pghost = ENV['PGHOST']
  pgport = ENV['PGPORT']
  pguser = ENV['PGUSER']
  pgpassword = ENV['PGPASSWORD']

  config = Rails.configuration.database_configuration[Rails.env].with_indifferent_access

  ENV['PGHOST'] = config[:host] if config[:host]
  ENV['PGPORT'] = config[:port].to_s if config[:port]
  ENV['PGUSER'] = config[:username].to_s if config[:username]
  ENV['PGPASSWORD'] = config[:password].to_s if config[:password]

  yield
ensure
  ENV['PGHOST'] = pghost
  ENV['PGPORT'] = pgport
  ENV['PGUSER'] = pguser
  ENV['PGPASSWORD'] = pgpassword
end