Upgrading to 2.0
Migrate from auditor-doctrine-provider 1.x to 2.0
This guide covers upgrading from auditor-doctrine-provider 1.x to 2.0.
Overview
auditor-doctrine-provider 2.0 introduces schema version 2: a revised audit table format
with a unified blame JSON column, a ULID-based transaction_id, and a richer diffs
envelope. audit:schema:migrate converts the existing audit entries to the new format: the
legacy columns are read during the migration, then dropped. There is no command to go back to
the v1 schema: back up your audit tables before migrating (see below).
⚠️ Who is affected?
| Scenario | Impact |
|---|---|
Using damienharper/auditor-bundle 8.x | ✅ Bundle handles wiring automatically |
Using auditor-doctrine-provider standalone | ⚠️ Must migrate audit tables manually |
Custom providers calling persist(LifecycleEvent $event) | ⚠️ Payload keys have changed |
Code reading $entry->transactionHash | ⚠️ Property removed — use $entry->transactionId |
Code importing DH\Auditor\Provider\Doctrine\Auditing\Attribute\{Auditable,Ignore,Security} | ⚠️ Aliases removed — import DH\Auditor\Attribute\* |
Custom Doctrine types implementing NeedsConversionToAuditableType | ⚠️ Implement DH\Auditor\Provider\Doctrine\Transaction\NeedsConversionToAuditableType |
LifecycleEvent listeners rewriting diffs | ⚠️ Write under changes — see Listeners that rewrite diffs |
| Audit tables created by Doctrine migrations | ⚠️ A replayable migration is needed — see Audit tables managed by Doctrine Migrations |
| Raw SQL on the audit tables | ⚠️ Columns and diffs paths changed — see step 10 |
| Code writing audit rows itself (imports) | ⚠️ See Writing audit rows yourself |
🚀 Upgrade Steps
Migrating to 2.0 converts every existing audit table: plan it like a database migration, with a backup, a rehearsal on a copy of your data and a maintenance window. The steps below are in the order to follow.
1️⃣ Check the prerequisites
| Requirement | 2.0 |
|---|---|
| PHP | 8.4 or later |
| Symfony components | 8.1 or later |
doctrine/dbal | 4.6 or later |
doctrine/orm | 3.7 or later |
damienharper/auditor | 5.0 (requires symfony/uid, installed with it) |
damienharper/auditor-bundle (Symfony apps) | 8.0 |
This guide starts from the latest 1.x release. From an older version, upgrade to the latest 1.x first and run
audit:schema:update --force there, so that the audit tables match the last v1 schema before you migrate.
2️⃣ Back up your audit tables
CAUTION
There is no rollback. Once the conversions are done, audit:schema:migrate drops the legacy columns
(transaction_hash, blame_user, blame_user_fqdn, blame_user_firewall, ip) and the indexes that cover
them. A backup taken just before the migration is the only way back to 1.x and to the v1 data.
Back up every audit table (*_audit by default, or your table_prefix / table_suffix), on every connection that
stores audits when you use a storage_mapper. For example:
# MySQL / MariaDB
mysqldump --single-transaction my_database post_audit comment_audit > audit-backup.sql
# PostgreSQL
pg_dump --table='*_audit' my_database > audit-backup.sql
3️⃣ Rehearse on a copy and estimate the duration
Restore a recent copy of your production database on a staging environment, install 2.0 there (step 5) and run the whole procedure. It tells you how long your maintenance window must be, and that the migration goes through on your data.
The migration rewrites every audit row, so its duration grows linearly with the size of the audit tables. As an
order of magnitude, count 3 to 5 minutes per million audit rows (a 1,000,000-row table took 4 min 59 s on
MySQL 8.0 and 3 min 13 s on PostgreSQL 15 on a developer laptop, see
Performance), plus the time audit:schema:update
takes to apply the rest of the schema (step 7).
To measure it on your own data without running the whole migration, convert a sample with --limit, on the
copy:
bin/console audit:schema:migrate --force --convert-all --limit=10000
--limit=N (with a conversion option, not with --drop-transaction-hash) converts N transactions
(--convert-transaction-hash) or N rows (--convert-diffs), prints an
estimate of the remaining time, and keeps the legacy columns, so that a later run resumes where it stopped.
WARNING
Do not run --limit on production while 1.x still writes to it: it already adds the v2 columns and converts
rows. Rehearse and estimate on a copy.
Also check the free disk space: rows are rewritten in place, so the audit tables grow during the migration, up to 4 times their initial size on PostgreSQL in the measurement above, until the space is reused or reclaimed.
4️⃣ Stop writing audits during the migration
1.x writes v1 rows and 2.0 writes v2 rows: neither can write into a table that is half-way between the two. With 2.0, an audit entry that cannot be written makes the flush fail and the transaction roll back.
So, for the duration of the migration, stop everything that modifies audited entities: put the application in
maintenance mode, and stop the Messenger workers, cron jobs and scheduled tasks (including audit retention or
audit:clean). Reading the audits is safe at any time: the Reader handles migrated and non-migrated tables.
Histories across tables only index converted entries: run audit:roots:rebuild once the migration is complete (it
warns about the entries it had to skip).
5️⃣ Update the packages
# Symfony application
composer require damienharper/auditor-bundle:^8.0
# This pulls in damienharper/auditor ^5.0 and damienharper/auditor-doctrine-provider ^2.0.
# Without the bundle
composer require damienharper/auditor:^5.0 damienharper/auditor-doctrine-provider:^2.0
Then clear the cache (bin/console cache:clear) and deploy the code, keeping the application in maintenance mode.
CAUTION
Do not let Doctrine change the audit tables before the migration. The provider declares the v2 audit tables
in the Doctrine schema, so on v1 tables doctrine:schema:update --force and a migration generated by
doctrine:migrations:diff drop the legacy columns without converting their data. Run
audit:schema:migrate first; if your deployment runs doctrine:migrations:migrate automatically, make sure no
pending migration touches the audit tables, and generate new migrations only after step 7.
audit:schema:update refuses to run while an audit table still has the v1 schema.
If your audit tables are created by Doctrine migrations, follow
Audit tables managed by Doctrine Migrations instead: it replaces
this advice.
Audit tables managed by Doctrine Migrations
When your audit tables are created by Doctrine migrations (generated by doctrine:migrations:diff, since the
provider declares them in the Doctrine schema), audit:schema:migrate is not enough:
- it only migrates the databases it runs on: every database built by running the migrations from scratch (test databases, CI, new environments) still ends with v1 audit tables until a migration brings them to v2;
- the migration that
doctrine:migrations:diffgenerates for that drops the legacy columns without converting their data, so it must not run on a database that holds audit entries; - a deployment that runs
doctrine:migrations:migratewhen it starts runs it before you can runaudit:schema:migrate.
Write instead one migration whose every statement can be replayed: it brings an empty v1 table to v2, completes a
table already migrated by audit:schema:migrate as audit:schema:update would, and changes nothing on a table
already at v2. It stops while a table still has transaction_hash and rows, whose data only audit:schema:migrate
can convert. Example for PostgreSQL, with the default index names
(<columns>_<md5 of the audit table name, as written in TABLES>_idx):
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20261201000000 extends AbstractMigration
{
// Every audit table, with your table_prefix / table_suffix. Unqualified names of tables in the current schema
// (the first of search_path) only: the v1 check below does not see the other schemas.
private const array TABLES = ['author_audit', 'post_audit'];
public function up(Schema $schema): void
{
foreach (self::TABLES as $table) {
$isV1 = (bool) $this->connection->fetchOne(
"SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? AND column_name = 'transaction_hash'",
[$table],
);
$this->abortIf(
$isV1 && (bool) $this->connection->fetchOne(sprintf('SELECT EXISTS (SELECT 1 FROM %s)', $table)),
sprintf('%s holds v1 entries: run bin/console audit:schema:migrate --force --convert-all first.', $table),
);
$hash = md5($table);
foreach (['transaction_hash', 'blame_id', 'object_id', 'discriminator'] as $index) {
$this->addSql(sprintf('DROP INDEX IF EXISTS %s_%s_idx', $index, $hash));
}
$this->addSql(sprintf(
'ALTER TABLE %s'
.' ADD COLUMN IF NOT EXISTS schema_version SMALLINT DEFAULT 2 NOT NULL,'
.' ADD COLUMN IF NOT EXISTS transaction_id CHAR(26) DEFAULT NULL,'
.' ADD COLUMN IF NOT EXISTS blame JSONB DEFAULT NULL,'
.' DROP COLUMN IF EXISTS transaction_hash,'
.' DROP COLUMN IF EXISTS blame_user,'
.' DROP COLUMN IF EXISTS blame_user_fqdn,'
.' DROP COLUMN IF EXISTS blame_user_firewall,'
.' DROP COLUMN IF EXISTS ip,'
.' ALTER schema_version SET DEFAULT 2,'
.' ALTER id TYPE BIGINT,'
.' ALTER type TYPE VARCHAR(11)',
$table,
));
$this->addSql(sprintf('CREATE INDEX IF NOT EXISTS transaction_id_%s_idx ON %s (transaction_id)', $hash, $table));
$this->addSql(sprintf('CREATE INDEX IF NOT EXISTS object_id_type_%s_idx ON %s (object_id, type)', $hash, $table));
$this->addSql(sprintf('CREATE INDEX IF NOT EXISTS blame_id_created_at_%s_idx ON %s (blame_id, created_at)', $hash, $table));
}
}
public function down(Schema $schema): void
{
$this->throwIrreversibleMigrationException('The v1 audit schema can only be restored from a backup.');
}
}
On PostgreSQL, the (blame_user, blame_id) index of 1.x goes away with the blame_user column. When at least one
entity declares an #[AuditRoot], generate the creation of the audit_root table as
usual: it is a new, empty table.
On MySQL, the same migration cannot rely on IF EXISTS: MySQL supports neither ADD COLUMN IF NOT EXISTS,
DROP COLUMN IF EXISTS nor DROP INDEX IF EXISTS (MariaDB does, but a migration that must also run on MySQL cannot
rely on it). Introspect each table first ($this->connection->createSchemaManager()->introspectTable($table)) and
add a statement only when hasColumn() or hasIndex() says it is needed; blame is a JSON column there. Drop the
blame_user_blame_id_<md5>_idx index explicitly before the blame_user column: MySQL and MariaDB keep an index on
the remaining columns of a multi-column index, under its legacy name. Compare the result with
audit:schema:update --dump-sql on a copy.
Then deploy in this order:
- Put the application in maintenance mode and stop writing audits (step 4).
- Deploy 2.0 with this migration, without running
doctrine:migrations:migrateat start for this deployment: the migration would stop on the populated v1 tables, and the deployment with it. The other pending migrations of the release then run at item 4: make sure the code does not need them before. - Run
audit:schema:migrate --force --convert-all(step 6). - Run
doctrine:migrations:migrate. On the migrated tables, it does whataudit:schema:updatedoes in step 7. - Check and reopen (step 8):
audit:schema:update --dump-sqlhas nothing left to do, anddoctrine:migrations:diffgenerates nothing more for the audit tables. With#[AuditRoot], runaudit:roots:rebuildfirst (step 4).
Test and CI databases built from the migrations have empty audit tables: the migration brings them to v2 on its own.
6️⃣ Migrate the audit tables
# Preview the DDL (no writes)
bin/console audit:schema:migrate --dump-sql --convert-all
# Run the migration: new columns, transaction hash conversion, diffs conversion, then legacy columns dropped
bin/console audit:schema:migrate --force --convert-all
Always pass --convert-all (or both --convert-transaction-hash and --convert-diffs):
| Command | Result |
|---|---|
--force --convert-all | Recommended. Every row reaches schema_version 2, transactions stay grouped (one ULID per legacy transaction_hash, across all tables), and the legacy columns are dropped. |
--force --convert-transaction-hash | Transactions stay grouped; rows keep their legacy diffs (schema_version 1, still readable). Run --convert-diffs later to finish. |
--force --convert-diffs | Diffs are converted; transaction_hash is kept so that --convert-transaction-hash can run later. The table stays a legacy table until then. |
--force alone | New columns added, blame migrated; transaction_hash is kept and the diffs stay at schema_version 1. The table stays a legacy table until the conversions run. |
--force --drop-transaction-hash | ⚠️ transaction_hash is dropped without conversion: legacy rows lose their transaction grouping for good. Only on request: this option cannot be combined with --convert-transaction-hash or --convert-all. |
The command migrates the audit tables of the entities currently configured as auditable, each on the storage its entity is mapped to. It holds a lock: a second run started meanwhile does nothing and exits with an error. The lock is local to the host: run the migration from a single host, not from every replica or pod of a deployment.
A row whose diffs cannot be converted without losing or misreading them (not valid JSON, not an object, a field entry
that is not an object, an unknown type) is left as it is, at schema_version 1, and listed at the end of the run, which then exits with an error. It
stays readable as a legacy entry; fix or delete it, then run the command again.
On large datasets, the conversions can run in several commands (--convert-transaction-hash, then
--convert-diffs), or in chunks with --limit during the maintenance window: each run resumes where the previous
one stopped, and the legacy columns are only dropped by a run without --limit.
7️⃣ Apply the rest of the v2 schema
bin/console audit:schema:update --dump-sql
bin/console audit:schema:update --force
This adds the indexes of the v2 schema (transaction_id, (object_id, type), (blame_id, created_at)), drops the
object_id, blame_id and discriminator indexes of 1.x, and
aligns the column types and defaults (id becomes a BIGINT, which rebuilds the table on MySQL and MariaDB and
rewrites it on PostgreSQL). It is much shorter than the migration itself, about 20 seconds per million rows on
MySQL 8.4 and 8 seconds on PostgreSQL 17 in a test container, but include it in the window.
8️⃣ Check, then reopen
# Both must report that there is nothing left to do
bin/console audit:schema:migrate
bin/console audit:schema:update --dump-sql
audit:schema:migrate without options exits with an error while a table still has a legacy column or rows with
unconverted diffs (schema_version 1), and tells which. A run that only does a step of the migration (--limit, or
a single conversion option) ends with "Step done. The migration is not complete" instead of the success message.
Open a few audit entries (in the bundle's viewer, or through the Reader): the user, IP and transaction grouping
of the migrated entries must be there. Then restart the workers and scheduled tasks, and leave maintenance mode.
Optionally, reclaim the disk space used during the migration: OPTIMIZE TABLE on MySQL / MariaDB,
VACUUM FULL on PostgreSQL (both lock the table while they run).
9️⃣ Update code reading $entry->transactionHash
// Before (1.x)
$entry->transactionHash; // SHA-1 VARCHAR(40) string
// After (2.0)
$entry->transactionId; // ULID CHAR(26) string
See Breaking Changes for the other changes that may affect your code.
🔟 Update raw SQL queries on the audit tables
Reader and Query handle both schemas, but SQL written by hand against the audit tables does not: repositories
that UNION several audit tables, reports, views, BI dashboards, Doctrine migrations or scripts. After
audit:schema:migrate, any query naming transaction_hash, blame_user, blame_user_fqdn, blame_user_firewall
or ip fails with an unknown column error. Search your code base (SQL strings, .sql files, views, migrations) for
these names, and for paths into the diffs JSON, before the maintenance window.
Columns
| 1.x | 2.0, MySQL / MariaDB | 2.0, PostgreSQL | 2.0, SQLite |
|---|---|---|---|
transaction_hash | transaction_id | transaction_id | transaction_id |
blame_user | JSON_VALUE(blame, '$.username') | blame->>'username' | json_extract(blame, '$.username') |
blame_user_fqdn | JSON_VALUE(blame, '$.user_fqdn') | blame->>'user_fqdn' | json_extract(blame, '$.user_fqdn') |
blame_user_firewall | JSON_VALUE(blame, '$.user_firewall') | blame->>'user_firewall' | json_extract(blame, '$.user_firewall') |
ip | JSON_VALUE(blame, '$.ip') | blame->>'ip' | json_extract(blame, '$.ip') |
blame_id, object_id, type, discriminator, extra_data, created_at | unchanged | unchanged | unchanged |
transaction_idholds a ULID, not the SHA-1 of 1.x: the conversion gives one ULID per legacy hash across all audit tables, so joins andGROUP BYbetween audit tables keep working once the column is renamed. A transaction hash stored outside the audit tables (in your own tables, logs, URLs) no longer matches anything.blameisNULLwhen an entry has no blame at all (no user, no IP, no blame context). Otherwise each key is present, set to JSONnullwhen unknown, soblame_user_firewall IS NOT NULLbecomesJSON_VALUE(blame, '$.user_firewall') IS NOT NULL(MySQL / MariaDB).- ⚠️ On MySQL, do not use
blame->>'$.user_firewall'for a null test: on a JSONnullit returns the string'null', not SQLNULL, soIS NOT NULLis true for every row that has a blame.JSON_VALUE()(MySQL 8.0.21+, MariaDB) returns SQLNULL. MariaDB has no->>operator. blamemay also carry aviakey (blame context, see Blame contexts).idbecomes aBIGINT: a column or variable that stores an audit id in anINTmust be widened.
diffs
| Entry | 1.x diffs | 2.0 diffs |
|---|---|---|
| insert / update | {"field": {"old": …, "new": …}, …} (insert: plus @source) | {"source": {…}, "changes": {"field": {"old": …, "new": …}}} |
| remove | {"class": …, "id": …, "label": …, "table": …} | {"source": {"class", "id", "label", "table"}, "changes": {}} (changes filled with full_snapshot_on_remove) |
| associate / dissociate | {"source": …, "target": …, "is_owning_side": …, "table": "<join table>"} | same, table renamed join_table |
A path into a field diff gets a changes level:
| MySQL / MariaDB | PostgreSQL | SQLite | |
|---|---|---|---|
new value of email | JSON_VALUE(diffs, '$.changes.email.new') | diffs->'changes'->'email'->>'new' | json_extract(diffs, '$.changes.email.new') |
email changed | JSON_CONTAINS_PATH(diffs, 'one', '$.changes.email') | diffs->'changes' ? 'email' | json_type(diffs, '$.changes.email') IS NOT NULL |
WARNING
A 1.x path does not fail, it finds nothing. diffs->'email' IS NOT NULL (PostgreSQL),
JSON_EXTRACT(diffs, '$.email') (MySQL) or json_extract(diffs, '$.email') (SQLite) raise no error on a v2 row:
they just never match, since the field is under changes. A query that expects rows returns none, and a query or a
test that checks that no row matches still passes, but no longer checks anything. Look for these paths
before the migration: an error will not point them out.
- A
diffs LIKE '%"email"%'test still matches after the migration, but also matches thesourceblock (itslabel) and fields of a JSON deep diff: prefer the paths above, orChangedFieldFilterthrough theReader. - Until
--convert-diffshas run on every row, a table holds both formats: rows withschema_version1 keep the 1.x diffs. Filter onschema_version = 2, or handle both. diffs,blameandextra_dataare nativeJSONon MySQL / MariaDB andJSONBon PostgreSQL (anINSERTneeds a::jsonbcast there);TEXTon SQLite.
Example
Entries of a user's HTTP requests (firewall known), grouped by transaction, on MySQL:
-- Before (1.x)
SELECT transaction_hash, MIN(created_at)
FROM post_audit
WHERE blame_id = :user AND blame_user_firewall IS NOT NULL
GROUP BY transaction_hash;
-- After (2.0)
SELECT transaction_id, MIN(created_at)
FROM post_audit
WHERE blame_id = :user AND JSON_VALUE(blame, '$.user_firewall') IS NOT NULL
GROUP BY transaction_id;
🩺 Troubleshooting
The migration stopped in the middle (timeout, lost connection, Ctrl+C).
Run the same command again. The added columns are kept, converted rows are skipped, transactions already given a
ULID keep it, and the legacy columns are dropped last, so a new run completes the migration. On MySQL and MariaDB,
DDL statements are not transactional: do not drop or restore anything by hand before the new run. If the run keeps
failing, restore the backup and run it again after fixing the cause.
audit:schema:update says that audit tables are still on the legacy v1 schema.
audit:schema:migrate has not run, or not to the end (for example, only --convert-diffs ran, or a run used
--limit). Run audit:schema:migrate --force --convert-all.
audit:schema:migrate reports nothing to migrate, but a v1 audit table is still there.
Only the audit tables of the entities currently configured as auditable are migrated. A table left by an entity
that is no longer audited is ignored: audit it again for the time of the migration, or keep its backup and drop it.
"The command is already running in another process."
Another audit:schema:migrate holds the lock on this host. Wait for it to finish. The lock does not cover other
hosts: make sure only one host runs the migration.
Some rows "could not be converted".
Their diffs are not valid JSON, do not decode to an object, hold a field entry that is not an object, or their type
is unknown: they were left as they are, at
schema_version 1. Look at them with the ids listed by the command, fix or delete them, then run
audit:schema:migrate --force --convert-diffs again.
A Doctrine migration wants to change or drop the audit columns.
It was generated against v1 audit tables: delete it, run audit:schema:migrate and audit:schema:update, then
generate the migration again. If your audit tables are created by Doctrine migrations, write the migration described
in Audit tables managed by Doctrine Migrations instead.
Test or CI databases still have v1 audit tables after the upgrade.
They are built by running the Doctrine migrations, which created the v1 tables, and audit:schema:migrate never ran
on them. Add the migration described in
Audit tables managed by Doctrine Migrations.
audit:schema:update --dump-sql shows a change of transaction_id to CHAR(26).
Development builds of 2.x created transaction_id as VARCHAR(26). Apply the change once: both
audit:schema:update and doctrine:schema:update then agree.
Disk full during the migration. Free some space, then run the command again: it resumes. Plan for up to 4 times the size of the audit tables on PostgreSQL.
🗄️ Schema Changes
| Column (1.x) | Column (2.0) | Notes |
|---|---|---|
transaction_hash VARCHAR(40) | transaction_id CHAR(26) | SHA-1 replaced by ULID |
blame_user VARCHAR(255) | (removed) | Merged into blame JSON |
blame_user_fqdn VARCHAR(255) | (removed) | Merged into blame JSON |
blame_user_firewall VARCHAR(100) | (removed) | Merged into blame JSON |
ip VARCHAR(45) | (removed) | Merged into blame JSON |
| (new) | blame JSON NULL | {"username","user_fqdn","user_firewall","ip"} |
| (new) | schema_version SMALLINT DEFAULT 2 | 1 = legacy diffs, 2 = v2 format (new or converted rows). audit:schema:migrate adds it with a default of 1, which marks the existing rows, and sets 2 when it drops the last legacy column (a table that keeps transaction_hash keeps 1 until then) |
Indexes:
| Index (1.x) | Index (2.0) |
|---|---|
transaction_hash | transaction_id |
(blame_user, blame_id) (added in 1.x for the viewer's user filter) | (removed), the viewer reads blame_id |
object_id | (removed), covered by (object_id, type) |
blame_id | (removed), covered by (blame_id, created_at) |
discriminator | (removed), always filtered along with object_id or created_at |
(object_id, type) (history of an object) | |
(blame_id, created_at) (timeline of a user) |
audit:schema:migrate drops the 1.x indexes with their columns, and audit:schema:update creates the 2.0 ones and
drops the object_id, blame_id and discriminator indexes: fewer indexes to maintain make each audit INSERT
faster.
🔄 Breaking Changes
Entry::$transactionHash removed
Property removed with no deprecated alias. Replace all reads with $entry->transactionId.
Deprecated attribute aliases removed
DH\Auditor\Provider\Doctrine\Auditing\Attribute\Auditable, Ignore and Security, deprecated since 1.0, are
removed. Import the attributes from the core:
// Before (1.x)
use DH\Auditor\Provider\Doctrine\Auditing\Attribute\Auditable;
// After (2.0)
use DH\Auditor\Attribute\Auditable;
NeedsConversionToAuditableType lives in the provider
The interface of the Doctrine types whose value must be converted before it is audited is now
DH\Auditor\Provider\Doctrine\Transaction\NeedsConversionToAuditableType. Its auditor 4.x counterpart,
DH\Auditor\Transaction\NeedsConversionToAuditableType, is gone from auditor 5.0: a custom type implementing it must
implement the provider's interface instead.
LifecycleEvent payload keys changed
Custom providers must update any code reading the old flat keys from $event->getPayload():
| Key (1.x) | Key (2.0) | Notes |
|---|---|---|
transaction_hash | transaction_id | ULID string |
blame_user | blame → username | Key of the blame JSON string |
blame_user_fqdn | blame → user_fqdn | Key of the blame JSON string |
blame_user_firewall | blame → user_firewall | Key of the blame JSON string |
ip | blame → ip | Key of the blame JSON string |
| (new) | schema_version | 2 for all new entries |
blame, like diffs and extra_data, is a JSON string in the payload:
json_decode($payload['blame'] ?? 'null', true)['username'] ?? null.
Listeners that rewrite diffs
A LifecycleEvent listener that changes $payload['diffs'] before the entry is written (to rewrite, add or remove
field diffs) receives the v2 envelope, not the flat 1.x diff. It must:
- read and write the field diffs under
changes; - keep
source(and, for an association,target,is_owning_sideandjoin_table) as it is; - when it replaces a JSON deep diff by an
{old, new}diff, remove that field fromdeep_diffs, and dropdeep_diffsonce it is empty; - leave the envelope of an association or a dissociation (no
changeskey) as it is: addingchangesto it hides its structure.
// Before (1.x)
$diffs = json_decode($payload['diffs'], true);
$diffs['tags'] = ['old' => $oldTags, 'new' => $newTags];
$payload['diffs'] = json_encode($diffs);
// After (2.0)
$envelope = json_decode($payload['diffs'], true);
if (!\array_key_exists('changes', $envelope)) {
return; // associate / dissociate: no field diffs
}
$envelope['changes']['tags'] = ['old' => $oldTags, 'new' => $newTags];
$envelope['deep_diffs'] = array_values(array_diff($envelope['deep_diffs'] ?? [], ['tags']));
if ([] === $envelope['deep_diffs']) {
unset($envelope['deep_diffs']);
}
$payload['diffs'] = json_encode($envelope);
$event->setPayload($payload);
Nothing checks the envelope when the entry is written, and a wrong one is misread without any error: a v2 envelope
without changes is returned whole by getDiffs(), like an association, so field diffs written next to source
show source as a changed field, and without source the entry loses its summary (getDiffSource() returns
null); a field left in deep_diffs is walked as a tree of changed keys (old, new).
getDiffs() return value for schema v2 rows
For entries written with schema_version >= 2, getDiffs() returns the changes sub-array
from the unified diffs envelope. Legacy v1 rows are unaffected.
// schema_version = 1: raw ['field' => ['old' => x, 'new' => y], ...]
// schema_version >= 2: envelope['changes'] — same shape
$changes = $entry->getDiffs();
Query::count() no longer hides database errors
In 1.x, Query::count() returned 0 when the query failed (missing audit table, lost connection, SQL error),
while execute() on the same query threw. It now lets the exception through, like execute(). Code that worked
around the silent 0 (for example by taking the larger of count() and the number of fetched entries) can drop it.
audit:schema:update now guards against v1 tables
If any audit table still has a legacy column (transaction_hash, blame_user, blame_user_fqdn,
blame_user_firewall or ip), audit:schema:update
will refuse to run and print an error listing the affected tables. Run
audit:schema:migrate --force --convert-all first.
Configured ignored_columns of #[Auditable] entities are applied
In 1.x, the attributes of an #[Auditable] entity replaced its whole configured options (except retention): the
entity ignored_columns given in the configuration (e.g. the bundle YAML) were silently dropped. They are now added
to the #[Ignore] properties, as documented. Check that the properties listed there are really meant to be ignored.
extra_data_provider called once per flush
The extra_data_provider callable takes no argument: it is now called once per flush (and once per batch of
audit:snapshot) instead of once per audit entry, and every entry of the flush gets its value. A provider that
returned a different value on each call (a counter, a timestamp) now returns one value per flush; use a
LifecycleEvent listener for a value that depends on the audited entity.
Query::getSupportedFilters() lists column names only
The filters of a Query used to be derived from the index definitions of the audit table, so that
getSupportedFilters() also returned the __composite_object_id_type and __composite_blame_id_created_at
pseudo-names, which never made a valid filter. It now returns id, type, object_id, discriminator,
transaction_id, blame_id, created_at, json, diffs, transaction_hash, blame, root and cursor.
✨ New Features
None of these features exists in 1.x, except the listener attachment by a container (also in 1.4). They are all optional: a 1.x configuration keeps working unchanged.
Beyond the schema
| Feature | Documentation |
|---|---|
Batch INSERT (batch_size): the audit entries of a transaction are written with multi-row INSERT statements, 10 to 67 % faster flushes with many entities | Batch INSERT |
Per-entity retention: #[Auditable(maxAge: …, maxEntries: …)] or the max_age / max_entries entity options, applied by audit:clean | Retention Policy |
Export with audit:export: NDJSON, JSON or CSV, streamed, filtered by entity, object, period or user, optionally anonymized | audit:export |
Changed field filter (ChangedFieldFilter, changed_field query option): entries whose diff touches a field | Filters |
Readable values in diffs with #[DiffLabel] and a DiffLabelResolverInterface service | #[DiffLabel] |
Masked values with #[Mask]: the change of a field recorded as "***" or as an HMAC keyed with mask_secret | #[Mask] |
JSON deep diffs: a JSON field change can be stored as a tree of the changed keys, listed under deep_diffs in the envelope (read with Entry::isDeepDiff()) | Entry |
Full snapshot on remove (full_snapshot_on_remove): remove entries record the last value of every audited field | Configuration |
Compression (compression): compressed diffs and extra_data columns on MariaDB | Compression |
skip_disabled_entities: no audit table for entities disabled by default | Skipping Disabled Entities |
Initial snapshot with audit:snapshot: an insert entry flagged as a snapshot records the state of the entities that existed before auditing started | audit:snapshot |
Audited properties allowlist (audited_columns) and per-object ignored properties (ignored_columns_resolver) | Ignored Properties |
Blame contexts: how a change was made (console command, import, message…) in the via key of the blame JSON | Blame contexts |
Impersonator (switch user): an impersonator key in the blame JSON, read by $entry->impersonator and filtered by ImpersonatorFilter; user_fqdn is the class given by the user provider | Filters |
Histories across tables: #[AuditRoot] and the audit_root index, Reader::createRootQuery() with cursor pagination, getLastChanges(), getFieldHistory(), BlameOriginFilter, audit:roots:rebuild | Histories |
Pages of transactions: Query::transactions() / countTransactions() (and transactionsOf() / countTransactionsOf() across tables), Query::transactionEntries(), Query::countTransactionsByDay(), RootQuery::fetchTransactions() / countTransactions(): pages of whole actions instead of entries | Pages of transactions |
New indexes (object_id, type) and (blame_id, created_at), for the history of an object and the timeline of a user, and a lighter flush pipeline | Performance |
$entry->transactionId — ULID
$entry->transactionId; // '01JXXXXXXXXXXXXXXXXXXXXXXXXX' (26 chars)
$entry->blame — full blame context
$entry->blame; // ['username' => '...', 'user_fqdn' => '...', 'user_firewall' => '...', 'ip' => '...']
user_fqdn and the impersonator
user_fqdn is the fqdn of the user returned by the user provider (the class of the user in the application), no
longer the class of that object, which was DH\Auditor\User\User whenever the built-in class was used: null when
the user provider gives none. When that user has an impersonator (switch user), the blame JSON gets an
impersonator key, {"id": "1", "username": "admin", "fqdn": "App\\Entity\\Admin"}, read by
$entry->impersonator and filtered by ImpersonatorFilter (see Filters).
Blame contexts — $entry->via
The blame context current when the entities are flushed (see the core
Blame Context page) is written in
the via key of the blame JSON: {"type": "import", "label": "Import batch #42"}. It is captured at flush time,
so it still applies when the database transaction is committed after the context was popped. A context carrying
a user blames that user (blame_id, username, user_fqdn) instead of the user provider's one.
$entry->schemaVersion
$entry->schemaVersion; // 1 (legacy) or 2 (current)
Entry::getDiffSource() — entity metadata
$source = $entry->getDiffSource();
// ['id' => '42', 'class' => 'App\Entity\Post', 'label' => 'My post', 'table' => 'post']
// Returns null for schema_version = 1 entries.
Entry::getDiffTarget() — association target
$target = $entry->getDiffTarget();
// ['id' => '7', 'class' => 'App\Entity\Tag', 'label' => 'PHP', 'table' => 'tag']
// Returns null for non-association entries or schema_version = 1.
audit:snapshot — initial state of existing entities
When auditing is enabled on a database that already holds data, the history of an entity used to start
at its first change. audit:snapshot writes one insert entry flagged with "snapshot": true per existing
entity, in batches, and skips the entities that already have an audit history:
php bin/console audit:snapshot --all
Entry::isSnapshot() (auditor 5.0) tells these entries from real insertions. See
Schema Management.
Reader backwards compatibility
The Reader automatically adapts queries to use transaction_id or transaction_hash
depending on which column exists in each table. Mixed environments (some tables migrated,
some not) are fully supported.
audited_columns and ignored_columns_resolver
- The
audited_columnsentity option audits only the listed properties (an allowlist, instead of ignoring all the others). - The
ignored_columns_resolveroption takes a callable (seeIgnoredColumnsResolverInterface) that returns the properties to ignore for a given entity object.
Ignoring always wins over the allowlist. See Configuration.
Listeners attached by a container
disableListenerAttachment() leaves the Doctrine listeners to a dependency injection container, which declares
getDoctrineSubscriber() as a lazy listener: flushes made before the provider is built are audited (auditor-bundle
does it). One subscriber is now shared by all the auditing entity managers: auditing entity managers sharing an event
manager no longer write each audit entry twice. Also in 1.4. See Services.
❓ Need Help?
- Check GitHub Issues
- Open a new issue with details about your error