From 2c960727d6c12b1859c1f41d1c32b8d6fc7fa666 Mon Sep 17 00:00:00 2001 From: "connorc@orbitnode.net" Date: Sat, 18 Mar 2023 11:57:03 -0600 Subject: [PATCH] Add code to find and delete an existing backup file in a Backblaze B2 bucket before uploading a new backup file This commit modifies the upload_to_b2 method in the MysqlDatabaseBackup class to search for an existing backup file with the same name as the backup file being uploaded in a specified Backblaze B2 bucket. The implementation retrieves a list of all files in the bucket using the b2 ls command and then iterates over each line to search for a file with the same name as the backup file. If a matching file is found, the implementation extracts its file ID using a regular expression and then uses the b2 delete-file-version command to delete the file from the bucket. Note that this implementation assumes that the backup file has a unique name. --- mysql_database_backup.rb | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/mysql_database_backup.rb b/mysql_database_backup.rb index 5a8803e..cb9d6c3 100644 --- a/mysql_database_backup.rb +++ b/mysql_database_backup.rb @@ -55,10 +55,11 @@ class MysqlDatabaseBackup b2_file_url = "b2://#{@b2_bucket_name}/#{b2_file_name}" # Check if a backup file with the same name already exists in the B2 bucket - existing_file = `b2 list-file-names #{@b2_bucket_name} --prefix #{b2_file_name}` - if existing_file.include?(b2_file_name) - # Delete the existing backup file from the B2 bucket - file_id = existing_file.match(/"fileId": "([^"]+)"/)[1] + existing_files = `b2 ls #{@b2_bucket_name}` + existing_files.each_line do |line| + next unless line.include?(b2_file_name) + + file_id = line.match(/"fileId": "([^"]+)"/)[1] `b2 delete-file-version #{@b2_bucket_name} #{b2_file_name} #{file_id}` puts "Deleted existing backup file from B2 bucket: #{b2_file_url}" end