Database Manual · Chapter 9

Backup · Journal Mode · Operational Checkpoints

Using a DB on a real machine for a long time requires backups, the right journal mode and code prepared for failures. This chapter collects, together with the script functions, the settings and habits that help you avoid the biggest problems in real production.

Backup Methods

A SQLite connection can be backed up in three ways. All of them use SQLite's online backup and create a consistent copy while the connection stays open.

MethodBehaviorEvents
Database Studio [Backup...]Saves the open DB to a file. Default folder XDatabase\Backup, default file name ConnectionName_date_time.dbNone
DB["local"].Backup(path)Waits until the backup finishes and returns true / falseOnDbError on failure
DB["local"].StartBackupThread(path)Runs the backup in the background and returns at once. While it runs, IsBackupRunning is true and BackupProgress is 0–100OnBackupStarted · OnBackupProgress (every second) · OnBackupDone
  • A relative path passed from a script is based on the project folder, and missing folders are created.
  • StartBackupThread returns false if a backup is already running (backup already running in LastError).
  • MSSQL connections do not support backup (OnBackupDone is called with failure).
xscript
FUNCTION DB_BackupNow()
{
   // Add the date and time to the file name ( a relative path is based on the project folder )
   string stamp = SYS.GetDateTimeStringFormat("yyyyMMdd_HHmmss");
   string file  = $"XDatabase/Backup/local_{stamp}.db";
 
   if( DB["local"].Backup(file) == false )
   {
      LogError($"DB backup failed : {DB["local"].LastError}");
      return false;
   }
 
   Log($"DB backup OK : {file}");
   return true;
}

To run the backup in the background and receive the result as an event, use StartBackupThread and put OnBackupDone in the Event module (Chapter 8).

xscript
FUNCTION OnBackupDone(string dbName, string filePath, bool success, string errorMsg)
{
   if( success )
   {
      Log($"Backup done : db='{dbName}', file='{filePath}'");
   }
   else
   {
      LogError($"Backup failed : db='{dbName}', msg='{errorMsg}'");
   }
}

1) JournalMode — WAL / DELETE

Journal Mode on the Database Connections screen (JournalMode in connections.json) offers two choices.

ValueBehavior
WAL (default)Sets WAL (Write-Ahead Logging) mode every time the connection opens. Other connections can read while data is being written
DELETEDoes not set the journal mode

The sample uses "WAL". In WAL mode, Database Studio or an external analysis tool can query the DB while the machine sequence keeps writing to it. A DB used in WAL mode has the companion files LocalDB.db-wal and LocalDB.db-shm in the XDatabase\ folder.

Caution When you copy the DB file directly with Explorer or an external script, copy the -wal · -shm files too, or run PRAGMA wal_checkpoint(TRUNCATE); on the SQL tab to write the changes into the main file before copying the .db. The built-in backups above need none of this.


2) BackupFolder and the Automatic Backup Options

In the current version, the backup settings at the bottom of the Database Connections screen are only saved.

OptionCurrent behavior
BackupFolderOnly saved. Studio [Backup...] opens XDatabase\Backup as the default folder, and script backups use the path you pass
AutoBackupEnabled · AutoBackupIntervalHours · BackupKeepLastOnly saved; no automatic backup or cleanup of old files runs

If you need regular backups, have your script call Backup() or StartBackupThread() itself, and clean up old backup files yourself as well.


3) ConnectionTimeout / CommandTimeout / Reconnect

The time options of a Connections item apply to MSSQL connections only.

OptionDefaultCurrent behavior
ConnectionTimeout15 sUsed as the MSSQL connection timeout
CommandTimeout30 sOnly saved — the command timeout is always 30 s
PingIntervalSec10 sOnly saved — the disconnection check interval is always 10 s
ReconnectRetries3Only saved — automatic reconnection is always tried 3 times

These values are not used by a single-file SQLite connection.


4) Six Checkpoints in Operational Code

Six pieces of defensive code shared by the sample's DB functions.

A. IsOpen guard

xscript
if( DB["local"].IsOpen == false )
{
   ShowMessage(EB_Ok, "DB is not open. Press [Open] first.");
   return false;
}

B. Selected-row guard

xscript
if( SelectIndex < 0 || SelectIndex >= DB["local"].RowCount )
{
   ShowMessage(EB_Ok, "Select a row first.");
   return false;
}

C. Logging LastError

xscript
if( DB["local"].RunSqlQueryParam(sql, p) == false )
{
   LogError($"DB_xxx failed : {DB["local"].LastError}");
   ShowMessage(EB_Ok, $"DB xxx failed : {DB["local"].LastError}");
   return false;
}

D. Rollback when a transaction fails

xscript
if( DB["local"].RunSqlQueryParam(sql, p) == false )
{
   DB["local"].Rollback();
   // ...
}

E. Sync the status label when Open fails

xscript
if( DB["local"].Open() == false )
{
   DbStatusText = "● CLOSED";
   return false;
}
DbStatusText = "● OPEN";

F. Refresh after a change

xscript
return DB_Refresh();

After INSERT / UPDATE / DELETE, always refill the screen with Refresh so that the DB state and the screen state never drift apart.


5) Pre-production Checklist

ItemCheck
JournalMode"WAL" (default)
BackupIs backup implemented with Backup() · StartBackupThread() in scripts? (the automatic backup options are only saved for now)
Backup resultIs success · failure checked with OnBackupDone or the return value of Backup()?
Backup locationA separate disk is recommended
Error loggingLastError logged in every failure branch, or OnDbError in the Event module
IsOpen guardAt the start of every DB function
DB_Refresh at the end of data-changing functionsWithout it the screen shows stale data
MSSQL passwordRe-entered and saved on the deployed machine? (it becomes empty when the PC or account changes)
External backupA regular OS-level backup is also recommended

That is everything the DB_Sqlite sample shows about production-grade database integration. When applying it to a real project, bring over the patterns of these 9 chapters as they are and replace only the domain tables.

Subscribe