68 lines
2.6 KiB
PL/PgSQL
68 lines
2.6 KiB
PL/PgSQL
-- One-off: delete ALL incidents (and children) and every user with role <> 'admin'.
|
|
-- Usage: psql -p 5433 -d ims -v mode=dryrun -f cleanup-test-data.sql (counts only)
|
|
-- psql -p 5433 -d ims -v mode=run -f cleanup-test-data.sql (deletes, one transaction)
|
|
-- Evidence files on disk are NOT touched (5-year retention).
|
|
|
|
\set ON_ERROR_STOP on
|
|
|
|
\if :{?mode}
|
|
\else
|
|
\echo 'Set -v mode=dryrun or -v mode=run'
|
|
\quit
|
|
\endif
|
|
|
|
BEGIN;
|
|
|
|
\echo '--- admins kept ---'
|
|
SELECT id, name, email FROM users WHERE role = 'admin' ORDER BY email;
|
|
|
|
\echo '--- row counts to delete ---'
|
|
SELECT 'incidents' AS tbl, count(*) FROM incidents
|
|
UNION ALL SELECT 'evidence_files', count(*) FROM evidence_files
|
|
UNION ALL SELECT 'investigations', count(*) FROM investigations
|
|
UNION ALL SELECT 'capa_actions', count(*) FROM capa_actions
|
|
UNION ALL SELECT 'dosh_reports', count(*) FROM dosh_reports
|
|
UNION ALL SELECT 'incident_addenda', count(*) FROM incident_addenda
|
|
UNION ALL SELECT 'notifications_log', count(*) FROM notifications_log
|
|
UNION ALL SELECT 'audit_log (all)', count(*) FROM audit_log
|
|
UNION ALL SELECT 'users (non-admin)', count(*) FROM users WHERE role <> 'admin';
|
|
|
|
SELECT (:'mode' = 'run') AS do_delete \gset
|
|
\if :do_delete
|
|
-- Closed incidents are locked by triggers; disable them for this transaction only.
|
|
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_delete;
|
|
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_update;
|
|
|
|
DELETE FROM notifications_log;
|
|
DELETE FROM incident_addenda;
|
|
DELETE FROM dosh_reports;
|
|
DELETE FROM evidence_files;
|
|
DELETE FROM capa_actions;
|
|
DELETE FROM investigations;
|
|
DELETE FROM incidents;
|
|
|
|
-- audit_log: remove rows about deleted incident-side tables and about non-admin users.
|
|
DELETE FROM audit_log
|
|
WHERE table_name IN ('incidents','evidence_files','investigations','capa_actions','dosh_reports','incident_addenda')
|
|
OR changed_by IN (SELECT id FROM users WHERE role <> 'admin')
|
|
OR (table_name = 'users' AND record_id IN (SELECT id FROM users WHERE role <> 'admin'));
|
|
|
|
UPDATE app_settings SET updated_by = NULL
|
|
WHERE updated_by IN (SELECT id FROM users WHERE role <> 'admin');
|
|
|
|
DELETE FROM password_reset_tokens WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin');
|
|
DELETE FROM users WHERE role <> 'admin';
|
|
|
|
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_delete;
|
|
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_update;
|
|
|
|
\echo '--- after ---'
|
|
SELECT 'incidents' AS tbl, count(*) FROM incidents
|
|
UNION ALL SELECT 'users', count(*) FROM users
|
|
UNION ALL SELECT 'admins', count(*) FROM users WHERE role = 'admin';
|
|
COMMIT;
|
|
\else
|
|
ROLLBACK;
|
|
\echo 'dry run: nothing changed'
|
|
\endif
|