Skip to main content

Restore Database

SwartzDB provides a restore function that allows you to recover a previously backed-up database. This is essential in cases where the main database gets corrupted, accidentally deleted, or modified incorrectly.


How to Use the restore Function

To restore a database from a backup, use:

$sdb->restore("mydatabase.1701234567.bak");

Restore From a Different Backup Directory

The restore function by default searches the /backup/ directory. Change it to the directory where the backup is stored:

$sdb->restore("mydatabase.1701234567.bak",  "new_dir");

Custom Restore with a New Name

If you want to restore the backup to a different database name, or if the backup does not contain the orignal database name, specify the third parameter:

$sdb->restore("new_name.bak", "backup", "mydatabase");

This will restore the backup file new_name.bak into either an existing or a new database file named mydatabase.sdb.


How the Restore Function Works

  1. Locate the Backup File

    • It looks for the backup file inside the default backup folder (/backup/).
    • If the file does not exist, the function returns false.
  2. Determine the Original Database Name

    • If the third parameter ($originalFile) is not provided, the function extracts the original filename from the backup file.
    • For example, if the backup file is "users.1701234567.bak", it assumes "users" as the database name.
  3. Restore the Data

    • Reads the backup file contents.
    • Overwrites (or creates) the database file with the original or new name.
    • Returns true on success.

Return Values

  • true → The database was successfully restored.
  • false → The backup file does not exist or the restore failed.

Use Cases for Restoring a Database

  • After Accidental Deletion: If a database was mistakenly deleted, restoring it is a simple one-command process.
  • Undoing Corrupt Changes: If a modification broke the database, restoring an earlier version ensures data integrity.
  • Data Migration: If you need to create a copy of an old database under a different name.

Example: Auto-Restore If Integrity Fails

You can combine the restore function with the integrity check to automatically recover a corrupted database:

if (!$sdb->integrity("mydatabase")) {
echo "Database corrupted! Restoring from backup...";
if ($sdb->restore("mydatabase.1701234567.bak")) {
echo "Restore successful!";
} else {
echo "Restore failed. Check backup files.";
}
}

Important Notes

  • Always store backup files securely to prevent accidental loss.
  • Restoring will overwrite the existing database if the original name is used.
  • Ensure that SwartzDB has the correct write permissions to modify files.

Using the restore function, you can efficiently recover lost or corrupted databases, ensuring data safety in your SwartzDB-based applications.