Check Database Integrity
SwartzDB includes an integrity function that helps verify whether a database file is valid and readable. This function is useful for detecting corruption.
How to Use the integrity Function
To check the integrity of a database, use:
if ($sdb->integrity("mydatabase")) {
echo "Database is intact.";
} else {
echo "Database might be corrupted.";
}
How the Integrity Check Works
- Retrieves Structured Data – The function calls
get($file)to parse the database contents. - Reads Raw Data – It separately fetches the raw file contents of
mydatabase.sdb. - Comparison:
- If
get($file)returns empty data, but the raw file is not empty, it indicates that the database structure may be broken. - If both structured and raw data exist, the database is considered intact.
- If both are empty, the database is assumed to be valid but simply unused.
- If
Return Values
true→ Database is intact and properly formatted.false→ The file exists, but SwartzDB cannot interpret it as a valid database.
Use Cases for integrity
- Before Performing Operations: Ensures that the database is not corrupt before reading or modifying data.
- Data Recovery: Helps identify if a backup or a new database file needs to be restored.
- Error Handling: Can be used in an automated system to alert admins if corruption is detected.
Example: Preventing Operations on a Corrupt Database
if (!$sdb->integrity("user_data")) {
die("Error: Database is corrupted. Please restore a backup.");
}
Important Notes
- The
integrityfunction does not repair a corrupted database; it only detects potential issues. - If a database fails the integrity check, restoring from a backup is recommended.
- File permission issues might also cause integrity failures, so ensure that SwartzDB has read access to the database files.
By using the integrity function, you can safeguard your application against data corruption issues and ensure smooth database operations.