Class: Tools::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/tools/database.rb

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Database

Returns a new instance of Database.



4
5
6
# File 'lib/tools/database.rb', line 4

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#dump(debug: false) ⇒ Object

Backup the database and save it on the backup folder set in the configuration. If you need to make the command more verbose, pass ‘debug: true` in the arguments of the function.

Return the full path of the backup file created in the disk.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/tools/database.rb', line 14

def dump(debug: false)
  hooks.before_dump

  file_path = File.join(backup_folder, "#{file_name}#{file_suffix}.sql")

  cmd = "PGPASSWORD='#{password}' pg_dump -F p -v -O -U '#{user}' -h '#{host}' -d '#{database}' -f '#{file_path}' -p '#{port}' "
  debug ? system(cmd) : system(cmd, err: File::NULL)

  hooks.after_dump

  file_path
end

#list_filesObject

List all backup files from the local backup folder.

Return a list of strings containing only the file names.



57
58
59
60
61
# File 'lib/tools/database.rb', line 57

def list_files
  Dir.glob("#{backup_folder}/*.sql")
    .reject { |f| File.directory?(f) }
    .map { |f| Pathname.new(f).basename }
end

#resetObject

Drop the database and recreate it.

This is done by invoking two Active Record’s rake tasks:

  • rake db:drop

  • rake db:create



33
34
35
# File 'lib/tools/database.rb', line 33

def reset
  system('bundle exec rake db:drop db:create')
end

#restore(file_name, debug: false) ⇒ Object

Restore the database from a file in the file system.

If you need to make the command more verbose, pass ‘debug: true` in the arguments of the function.



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/tools/database.rb', line 41

def restore(file_name, debug: false)
  hooks.before_restore

  file_path = File.join(backup_folder, file_name)
  output_redirection = debug ? '': ' > /dev/null'
  cmd = "PGPASSWORD='#{password}' psql -U '#{user}' -h '#{host}' -d '#{database}' -f '#{file_path}' -p '#{port}' #{output_redirection}"
  system(cmd)

  hooks.after_restore

  file_path
end