Skip to main content

Backup Database

SwartzDB provides a backup function that allows you to create a copy of an existing database file. This feature is useful for data recovery, versioning, and preventing accidental data loss.

Using the backup Function

To create a backup of a database, use the following method:

$sdb->backup("mydatabase");

How It Works:

  • "mydatabase" – The name of the database file to be backed up (without the .sdb extension).
  • The function reads the contents of mydatabase.sdb and saves a copy in the backup directory.

Backup File Location

  • By default, backups are stored inside the backup folder located in the SwartzDB storage directory (/SwartzDB/storage/backup/).
  • If the backup folder does not exist, SwartzDB automatically creates it.

Custom Backup Names

By default, the backup file is named using the format:

<database_name>.<timestamp>.bak

For example, backing up mydatabase might create a file like:

mydatabase.1710409256.bak

You can also specify a custom name for the backup:

$sdb->backup("mydatabase", "custom_backup_name");

This will create:

custom_backup_name.bak

Changing the Backup Folder

By default, SwartzDB stores backups in /storage/backup/. If you want to store the backup in a custom directory, provide the folder name as the third parameter:

$sdb->backup("mydatabase", null, "my_backups");

This will store the backup inside:

/SwartzDB/storage/my_backups/

If the specified folder does not exist, SwartzDB automatically creates it.

Understanding the Process

  1. Reads the Database File – The function retrieves the contents of mydatabase.sdb.
  2. Creates Backup Directory (if needed) – If the backup folder is missing, it is created.
  3. Stores the Backup File – A backup copy is written to the backup directory.

Important Notes:

  • Backups Do Not Replace Main Databases: The backup function does not overwrite the original .sdb file.
  • Backups Preserve Data: The function ensures that a snapshot of the database is saved for future restoration.
  • Permissions: Ensure the script has the necessary write permissions to create and store backups.
  • Use Meaningful Custom Names: If you plan to restore backups manually, using descriptive names makes it easier to track different versions.

By using the backup function, you can efficiently safeguard your database files against data loss and corruption.