Guides

Events and statistics

Run code before and after every write, cancel a write from a handler, and read the size and shape of a database.

Before and after a write

XodContext raises BeforeAction before every insert, update, delete and drop, and AfterAction once it is done. Each handler gets a TriggerEventArgs:

Property Meaning
Action Insert, Update, Delete or Drop
Type the class being written
Item the object being written
Cancel set to true in BeforeAction to stop the write
db.BeforeAction += (sender, e) =>
{
    if (e.Action == DatabaseActions.Insert && e.Item is Order { Status: "blocked" })
        e.Cancel = true; // this insert doesn't happen
};

db.AfterAction += (sender, e) =>
    logger.LogInformation("{Action} {Type}", e.Action, e.Type.Name);

Use them for auditing, for rules that span tables, or to keep a cache in step with the database.

  • A handler that throws leaves nothing of the write, in Immediate mode, Buffered mode and inside a transaction (InsertRange, DeleteWhere and DropAll included), while keeping earlier writes intact (see Writes outside a transaction).
  • Each row a cascade deletes fires its own pair of handlers, with the object read from its row. Setting Cancel keeps that row. Cascaded rows are deleted after their parent’s row, so a child’s handler won’t find its parent stored.
  • DeleteWhere fires one pair of handlers per deleted row, equal rows included.
  • Calls refused inside a handler:
    • BeginTransaction(), Commit() and Rollback() throw TransactionException.
    • Dispose() and setting, changing or removing the database password throw InvalidOperationException.
    • Flush(), ClearCache()/ClearCaches() and GetStatistics() throw InvalidOperationException in buffered mode or a transaction. Call them once the write returns.

Statistics

GetStatistics() describes the size and shape of the database:

DatabaseStatistics stats = db.GetStatistics();

Console.WriteLine($"{stats.TotalRowCount} rows in {stats.TableCount} tables, {stats.TotalSizeBytes:N0} bytes");

foreach (var t in stats.Tables)
    Console.WriteLine($"{t.TableName}: {t.RowCount} rows, {t.PageCount} pages, {t.IndexedPropertyCount} indexes");
DatabaseStatistics
DatabasePath the database file
StorageFormat XML, JSON or binary
IsEncrypted whether it has a password
TotalSizeBytes, TableCount, TotalPageCount, TotalRowCount totals
Tables one TableStatistics per table: TableName, RowCount, PageCount, IndexedPropertyCount, SizeBytes

xod stats prints the same from the command line (see Command-line tool).

Memory

XOD caches recently used pages and indexes. ClearCaches() writes out anything buffered and releases the caches, for example after a large one-off read in a long-running process. Inside a transaction, ClearCache() and ClearCaches() keep the transaction’s pending changes and write nothing to disk.

Source on GitHub · Report a problem with this page