Skip to content

Commit

Permalink
fix: delete backup
Browse files Browse the repository at this point in the history
  • Loading branch information
dudantas authored Nov 14, 2024
1 parent bbeecd0 commit b6e1a5c
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions src/database/database.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ void Database::createDatabaseBackup(bool compress) const {
return;
}

std::string buffer(8192, '\0');
while (backupFile.read(&buffer[0], buffer.size()) || backupFile.gcount() > 0) {
gzwrite(gzFile, buffer.data(), backupFile.gcount());
char buffer[8192];
while (backupFile.read(buffer, sizeof(buffer)) || backupFile.gcount() > 0) {
gzwrite(gzFile, buffer, backupFile.gcount());
}

backupFile.close();
Expand All @@ -140,28 +140,21 @@ void Database::createDatabaseBackup(bool compress) const {
// Delete old backups
auto twentyFourHoursAgo = std::chrono::system_clock::now() - std::chrono::hours(24);
auto sevenDaysAgo = std::chrono::system_clock::now() - std::chrono::hours(24 * 7);
for (const auto &entry : std::filesystem::directory_iterator("database_backup")) {
for (const auto& entry : std::filesystem::directory_iterator("database_backup")) {
if (entry.is_directory()) {
auto dirTime = std::filesystem::last_write_time(entry);
if (!compress && dirTime.time_since_epoch() < sevenDaysAgo.time_since_epoch()) {
try {
std::filesystem::remove_all(entry);
g_logger().info("Deleted old backup directory (7 days): {}", entry.path().string());
} catch (const std::filesystem::filesystem_error &e) {
g_logger().error("Failed to delete old backup directory: {}. Error: {}", entry.path().string(), e.what());
}
}
if (compress && dirTime.time_since_epoch() < twentyFourHoursAgo.time_since_epoch()) {
for (const auto &file : std::filesystem::directory_iterator(entry)) {
if (file.path().extension() == ".gz") {
try {
try {
auto dirTime = std::filesystem::last_write_time(entry);
if (dirTime.time_since_epoch() < sevenDaysAgo.time_since_epoch()) {
// Instead of deleting the entire directory, delete only specific files
for (const auto& file : std::filesystem::directory_iterator(entry)) {
if (file.path().extension() == ".gz" || file.path().extension() == ".sql") {
std::filesystem::remove(file);
g_logger().info("Deleted compressed backup file (24 hours): {}", file.path().string());
} catch (const std::filesystem::filesystem_error &e) {
g_logger().error("Failed to delete compressed backup file: {}. Error: {}", file.path().string(), e.what());
g_logger().info("Deleted old backup file: {}", file.path().string());
}
}
}
} catch (const std::filesystem::filesystem_error& e) {
g_logger().error("Failed to check or delete files in backup directory: {}. Error: {}", entry.path().string(), e.what());
}
}
}
Expand Down

0 comments on commit b6e1a5c

Please sign in to comment.