Class: Tools::Database
- Inherits:
-
Object
- Object
- Tools::Database
- Defined in:
- lib/tools/database.rb
Instance Method Summary collapse
-
#dump(debug: false) ⇒ Object
Backup the database and save it on the backup folder set in the configuration.
-
#initialize(configuration) ⇒ Database
constructor
A new instance of Database.
-
#list_files ⇒ Object
List all backup files from the local backup folder.
-
#reset ⇒ Object
Drop the database and recreate it.
-
#restore(file_name, debug: false) ⇒ Object
Restore the database from a file in the file system.
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 |
# File 'lib/tools/database.rb', line 14 def dump(debug: false) 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) file_path end |
#list_files ⇒ Object
List all backup files from the local backup folder.
Return a list of strings containing only the file names.
49 50 51 52 53 |
# File 'lib/tools/database.rb', line 49 def list_files Dir.glob("#{backup_folder}/*.sql") .reject { |f| File.directory?(f) } .map { |f| Pathname.new(f).basename } end |
#reset ⇒ Object
Drop the database and recreate it.
This is done by invoking two Active Record’s rake tasks:
-
rake db:drop
-
rake db:create
29 30 31 |
# File 'lib/tools/database.rb', line 29 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.
37 38 39 40 41 42 43 44 |
# File 'lib/tools/database.rb', line 37 def restore(file_name, debug: false) 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) file_path end |