1
+ namespace :db do
2
+ desc "Restore the SQLite database from Spaces backup"
3
+ task restore : :environment do
4
+ backup_file = ENV [ 'BACKUP_FILE' ]
5
+
6
+ unless backup_file
7
+ puts "ERROR: You must provide the backup file name."
8
+ puts "Usage: rake db:restore BACKUP_FILE=production_backup_20241025020000.tar.gz"
9
+ exit 1
10
+ end
11
+
12
+ begin
13
+ # Create backups directory if it doesn't exist
14
+ FileUtils . mkdir_p ( "db/backups" )
15
+ local_file = "db/backups/#{ backup_file } "
16
+
17
+ # Download from Spaces
18
+ puts "Downloading backup from Spaces..."
19
+ bucket_name = ENV [ 'SPACES_BUCKET_NAME' ]
20
+ S3_CLIENT . bucket ( bucket_name ) . object ( "backups/#{ backup_file } " ) . download_file ( local_file )
21
+
22
+ if backup_file . end_with? ( '.tar.gz' )
23
+ puts "Extracting #{ backup_file } ..."
24
+ extracted_file = `tar -xzvf #{ local_file } -C db/backups` . strip
25
+ extracted_file = "db/backups/#{ extracted_file } "
26
+
27
+ restore_from_file ( extracted_file )
28
+
29
+ File . delete ( extracted_file ) if File . exist? ( extracted_file )
30
+ else
31
+ restore_from_file ( local_file )
32
+ end
33
+
34
+ # Clean up
35
+ File . delete ( local_file ) if File . exist? ( local_file )
36
+ puts "Database restored successfully."
37
+ rescue => e
38
+ puts "ERROR: Failed to restore the database: #{ e . message } "
39
+ exit 1
40
+ end
41
+ end
42
+
43
+ def restore_from_file ( backup_file )
44
+ puts "Restoring database from #{ backup_file } ..."
45
+ database_path = Rails . configuration . database_configuration [ Rails . env ] [ 'database' ]
46
+
47
+ ActiveRecord ::Base . connection . execute ( "DROP TABLE IF EXISTS #{ ActiveRecord ::Base . connection . tables . join ( ', ' ) } " )
48
+ system ( "sqlite3 #{ database_path } < #{ backup_file } " )
49
+ end
50
+ end
0 commit comments