Audit Trail & Event Sourcing — Database

An audit trail records every change to your data, in the columns action (INSERT, UPDATE, DELETE), table_name, record_id, old_values, new_values, user_id and…

Yesterday Milk Coffee cost $4.50. This morning it's $4.75. Who changed it, when, and what was it before? The products table can't say, because it only keeps the latest number.

An audit trail can answer these questions. It is a record of every change to your data. Each record holds which table, which row, what action (INSERT, UPDATE or DELETE), what the row held before and after, who changed it, and when. Think of your banking app. Its main screen only shows your latest balance, but its transaction history lists every payment in and out, so you can trace where that balance came from. The products table is the balance, and the audit table is the transaction history.

The shape of one audit row

We continue with Sunset Coffee. The products table holds Milk Coffee ($4.50), Palm Sugar Milk Coffee ($5.50), Milk Tea ($3.75) and Toast ($5.00), each price in whole cents. Next to it we create an audit_logs table to store the audit trail's records. A table like this is often called an audit log:

CREATE TABLE audit_logs (
  id INTEGER PRIMARY KEY,
  table_name TEXT NOT NULL,     -- the table that changed
  record_id INTEGER NOT NULL,   -- the id of the row that changed
  action TEXT NOT NULL,         -- 'INSERT', 'UPDATE' or 'DELETE'
  old_values TEXT,              -- what it held before, NULL for INSERT
  new_values TEXT,              -- what it holds after, NULL for DELETE
  user_id INTEGER,              -- who changed it
  created_at TEXT DEFAULT CURRENT_TIMESTAMP  -- when
);

For example, one row per action:

action table_name record_id old_values new_values
INSERT products 5 NULL {"name":"Iced Black Coffee","price":400}
UPDATE products 1 {"name":"Milk Coffee","price":450} {"name":"Milk Coffee","price":475}
DELETE products 4 {"name":"Toast","price":500} NULL

There are two ways to fill this table: the database records it itself, or the app does.

Way 1: a trigger in the database

You met the trigger in the Denormalisation lesson: SQL the database runs automatically every time something happens to a table. In SQLite, one trigger handles one action:

CREATE TRIGGER products_audit_update
AFTER UPDATE ON products
BEGIN
  INSERT INTO audit_logs (table_name, record_id, action, old_values, new_values)
  VALUES ('products', OLD.id, 'UPDATE',
    json_object('name', OLD.name, 'price', OLD.price),
    json_object('name', NEW.name, 'price', NEW.price));
END;

Now raise every price by 50. Wherever this command is sent from, the trigger still runs:

UPDATE products SET price = price + 50;
SELECT action, record_id, old_values, new_values, user_id FROM audit_logs;
action record_id old_values new_values user_id
UPDATE 1 {"name":"Milk Coffee","price":450} {"name":"Milk Coffee","price":500} NULL
UPDATE 2 {"name":"Palm Sugar Milk Coffee","price":550} {"name":"Palm Sugar Milk Coffee","price":600} NULL
UPDATE 3 {"name":"Milk Tea","price":375} {"name":"Milk Tea","price":425} NULL
UPDATE 4 {"name":"Toast","price":500} {"name":"Toast","price":550} NULL

4 rows changed, 4 audit rows. A trigger can't be skipped: changes from the app, from a database console (a program for typing SQL straight into the database), or from another script are all recorded. Its weakness is in the last column: user_id is empty. The database only knows which connection sent the command, not which app user is logged in.

In PostgreSQL, one trigger function (the function a trigger calls) can serve all three actions. TG_OP holds the action's name, 'INSERT', 'UPDATE' or 'DELETE', and to_jsonb(OLD) turns the whole row into JSONB. The app can tell the database who the app user is, for each transaction, with SET LOCAL app.user_id = '5', like app.tenant_id in the Multi-tenancy lesson. The trigger then reads it with current_setting('app.user_id', true): the argument true means current_setting gives no error if that setting doesn't exist yet.

Way 2: logging from the app

In Laravel, the usual way is the package spatie/laravel-activitylog. Add the LogsActivity trait to a model. From then on, every row created, updated or deleted through that model is recorded in the activity_log table, together with the logged-in user (called the causer):

use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Product extends Model
{
    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()->logOnly(['name', 'price'])->logOnlyDirty();
    }
}

Before you read on, guess: one evening an admin runs DB::table('products')->increment('price', 50), which raises the price of 4 products at once. How many audit rows does this package record: 4, 1, or 0?

The answer is 0 audit rows, even though 4 products changed. Model events only fire when a change goes through a model, one at a time. DB::table('products')->increment('price', 50) or Product::where(...)->update([...]) send a single UPDATE straight to the database without loading any model. A command like this is called a mass update: one command that changes many rows at once. No event, so no log. The same happens to SQL typed into a database console and to changes from other apps.

Trigger or app log?

Database trigger App log
Changes through a model recorded recorded
Mass updates, console SQL, other apps recorded missed
Which user, IP, page unknown, unless the app tells it known
Where the logic lives in the database, not visible in the code in the app's code

Closely watched data (balances, prices, stock) often uses both: a trigger so no change is missed, and an app log to know who did it.

📌 Event sourcing

An audit trail sits beside an ordinary table: products still holds the latest price, and the audit is an extra record next to it. Event sourcing reverses that. What gets stored is the list of events, the things that happened (OrderCreated, ItemAdded, PaymentMade, OrderShipped). An order's current contents are calculated by running all of those events again, one by one from the start. The history is complete and never edited, but a simple question like "what's in this order?" gets harder to answer. Use event sourcing only when that history is the core of the business.

⚠️ Changes that escape the log, or get logged too much

TL;DR: An audit trail records every change to your data, in the columns action (INSERT, UPDATE, DELETE), table_name, record_id, old_values, new_values, user_id and created_at. INSERT has no old contents (old_values NULL), DELETE has no new contents (new_values NULL). A database trigger (SQL the database runs automatically every time a table changes) records every change, mass updates (one command that changes many rows) and SQL typed straight into the database included. But a trigger doesn't know the app user. An app log (a record written by the app's code) such as the Laravel package spatie/laravel-activitylog knows who is logged in. But an app log misses mass updates and raw SQL, because no model event (a signal Eloquent sends when a model changes) fires. Important data often uses both.

⚡ One row per change

Write:

CREATE TABLE audit_logs (
  id INTEGER PRIMARY KEY,
  table_name TEXT NOT NULL,     -- the table that changed
  record_id INTEGER NOT NULL,   -- the id of the row that changed
  action TEXT NOT NULL,         -- 'INSERT', 'UPDATE' or 'DELETE'
  old_values TEXT,              -- what it held before, NULL for INSERT
  new_values TEXT,              -- what it holds after, NULL for DELETE
  user_id INTEGER,              -- who changed it
  created_at TEXT DEFAULT CURRENT_TIMESTAMP  -- when
);

Meaning: An audit trail records every change to your data. At minimum: who (user_id), what (action), before and after (old_values, new_values), and when (created_at). An INSERT has no old contents, a DELETE has no new contents.

In the exercise, missing contents are still written as null. Don't drop the old_values or new_values key.

⚡ A trigger can't be skipped

Write:

CREATE TRIGGER products_audit_update
AFTER UPDATE ON products
BEGIN
  INSERT INTO audit_logs (table_name, record_id, action, old_values, new_values)
  VALUES ('products', OLD.id, 'UPDATE',
    json_object('name', OLD.name, 'price', OLD.price),
    json_object('name', NEW.name, 'price', NEW.price));
END;

Meaning: A trigger is SQL the database runs automatically every time a table changes. This trigger writes one row to audit_logs every time a row of products is updated, with the old contents (OLD) and the new ones (NEW). A trigger records every change, mass updates (one command that changes many rows) and SQL typed straight into the database included. Its weakness: the database doesn't know which app user is logged in, so user_id stays empty.

⚡ An app log knows who

Guess first: the Laravel package spatie/laravel-activitylog records changes made through Eloquent models. An admin runs DB::table('products')->increment('price', 50), which changes the table without loading any model, and 4 product prices go up. How many audit rows does that package record?

None. A mass update like this loads no model, so no model event (a signal Eloquent sends when a model changes) fires, and the package records nothing.

Meaning: An app log (a record written by the app's code, such as that package) knows who is logged in, but misses mass updates and raw SQL. Important data often uses a trigger and an app log together.

What you will learn