Skip to content

Delete Records Developer Guide 2

Ed Mozley edited this page Dec 5, 2026 · 1 revision

Delete records - Developer Guide 2: the snapshot and Restore

Part 1: Delete records - Developer Guide. This page walks through the two functions that make a delete reversible: recordDeleteExecute() and recordBinRestore() in includes/record_delete.php.

1. Deleting: snapshot first, then act

Everything happens in one transaction the function owns (it refuses to run inside someone else's - a caller's rollback would otherwise undo the delete but not the bin row, or the other way round). The record is loaded through recordDeleteLoad() (company scope), the typed name checked, recordDeleteBlocked() asked again - the page may be stale.

Then each step of the plan is read whole before it is changed:

        $snap = ['v' => 1, 'record' => $row, 'steps' => []];
        foreach (recordDeletePlan($conn, $type, $id) as $s) {
            $sel = $conn->prepare("SELECT * FROM `{$s['table']}` WHERE `{$s['col']}` = ?{$s['where']}");
            $sel->execute(array_merge([$id], $s['args']));
            $rows = $sel->fetchAll(PDO::FETCH_ASSOC);
            if (!$rows) continue;
            $snap['steps'][] = ['table' => $s['table'], 'col' => $s['col'], 'action' => $s['action'], 'rows' => $rows];
            $sql = $s['action'] === 'delete'
                ? "DELETE FROM `{$s['table']}` WHERE `{$s['col']}` = ?{$s['where']}"
                : "UPDATE `{$s['table']}` SET `{$s['col']}` = NULL WHERE `{$s['col']}` = ?{$s['where']}";
            $conn->prepare($sql)->execute(array_merge([$id], $s['args']));
        }
        $conn->prepare("DELETE FROM `$table` WHERE id = ?")->execute([$id]);

Why whole rows (SELECT *), even for the null steps that only change one column: Restore needs the primary key to find each row again, and a whole row costs nothing extra to keep. The snapshot is {"v": 1, "record": {...}, "steps": [{table, col, action, rows: [...]}]} in record_bin.snapshot (LONGTEXT); v is there so a later shape can still read old entries.

The plan is worked out again inside the transaction, not taken from the preview, so a row added between preview and delete is in the snapshot too.

If a foreign key this tool does not know about refuses the delete (an install that still has its keys), MySQL throws 23000, the transaction rolls back, and the endpoint says "Something else in the database still refers to this record, so nothing has been changed."

2. Restoring: the record, its rows, its references - or nothing

Also one transaction, with the bin row read FOR UPDATE so two people pressing Restore cannot both succeed. In order:

  1. Refusals before any write. Already restored (already_restored), purged (purged), or recordBinClash(): the id is taken, or a live record now has the same identity - a person with the same email or username (typically imported again), an asset in the same company with the same service_tag or asset_tag. These are the clashes a person would notice; the message says what to do (merge or delete that one first).
  2. The record, with its original id, into the columns the table has now (recordBinInsertRow() intersects the snapshot with INFORMATION_SCHEMA.COLUMNS) - so a column dropped since does not break a restore, and one added since takes its default.
  3. Deleted rows back the same way, with their own ids. A duplicate key here (a row made since in the same place) turns into a clash refusal naming the table, and the whole restore rolls back.
  4. Cleared references set again - but only where nothing else has been put there since:
                // Cleared references: set again only where nothing else has been put there since.
                $pk = recordDeletePrimaryKey($conn, $t);
                if (!$pk) continue;
                $where = implode(' AND ', array_map(fn($c) => "`$c` = ?", $pk));
                $u = $conn->prepare("UPDATE `$t` SET `{$step['col']}` = ? WHERE $where AND `{$step['col']}` IS NULL");

The IS NULL matters: if, while the person was in the bin, someone gave their old ticket to a different person, Restore leaves that alone rather than taking the ticket back.

  1. The bin row gets restored_datetime / restored_by_id and its snapshot is dropped - a restored record is live data again; keeping a second copy would only go stale.

⚠️ TRAP: ids are put back as they were. That is only safe because MySQL 8 (and MariaDB 10.2.4+) never hands out an AUTO_INCREMENT value twice, even after a restart - so the deleted id stays free unless someone inserts it by hand (and then recordBinClash() says so). Never reset an AUTO_INCREMENT on a table this tool covers.

3. Purging

recordBinPurge() runs at the start of every call to api/system/delete_records.php (like Knowledge's archive purge) - the bin is only read through this tool, so nothing is kept longer than shown. It sets snapshot = NULL, purged_datetime on entries older than record_bin_days; the row stays as the record that the delete happened.

4. How it was verified

tests/record-delete.php (26) on a throwaway install: an asset with history, a holder and a ticket link; a person with an audit row and a ticket - deleted, everything gone, the ticket kept; a clash refused with nothing half-restored; both restored with every row and reference back; a restored entry refused twice; Retire; a person a live source imports refused until its import is off; a purge past the days; every action logged. Plus the screen: find, preview, typed confirmation, Bin, Restore.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally