Files
felhom.eu/hub/internal/store/orphan_rows.go
T

56 lines
2.4 KiB
Go

package store
import "fmt"
// OrphanRows counts what PurgeOrphanRows removed, per table.
type OrphanRows map[string]int64
// Total is the sum.
func (o OrphanRows) Total() int64 {
var n int64
for _, v := range o {
n += v
}
return n
}
// orphanTables are the tables D73 names (`09` §3 decision 293, R-1376) — the ones that had no delete statement — each
// with the column that names its owner and the query that says „the owner still exists”.
//
// A BOX exists while it has a `hosts` row. A HOUSEHOLD exists while it has a config row OR a box: a „ghost” (the
// config row gone, residue left) is exactly what this sweep is for, but a household in the middle of its delete
// cascade (boxes gone, config still there) is not an orphan.
var orphanTables = []struct{ table, where string }{
{"os_host_settings", `host_id NOT IN (SELECT host_id FROM hosts)`},
{"os_reports", `host_id NOT IN (SELECT host_id FROM hosts)`},
{"os_kernel_notices", `host_id NOT IN (SELECT host_id FROM hosts)`},
{"offsite_keys", `customer_id NOT IN (SELECT customer_id FROM customer_configs) AND customer_id NOT IN (SELECT customer_id FROM hosts)`},
{"offsite_windows", `customer_id NOT IN (SELECT customer_id FROM customer_configs) AND customer_id NOT IN (SELECT customer_id FROM hosts)`},
{"offsite_abandon_requests", `customer_id NOT IN (SELECT customer_id FROM customer_configs) AND customer_id NOT IN (SELECT customer_id FROM hosts)`},
}
// PurgeOrphanRows removes, in ONE transaction, the rows of boxes and households that no longer exist from the six
// tables that had no delete statement (D73). It is the daily clean-up for what was left BEFORE DeleteHost and
// PurgeCustomerResidue learned those tables (Peti's box, the test boxes of 2026-11): from now on a delete leaves
// nothing for it. It never touches the delete journal (`host_deletions`, `customer_resets`), `events`,
// `notification_log` or `operator_actions` (those go by the one-year rule). Idempotent.
// Pinned by TestD73_PurgeOrphanRows_OnlyTheGone.
func (s *Store) PurgeOrphanRows() (OrphanRows, error) {
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
out := OrphanRows{}
for _, t := range orphanTables {
res, err := tx.Exec(`DELETE FROM ` + t.table + ` WHERE ` + t.where)
if err != nil {
return nil, fmt.Errorf("PurgeOrphanRows %s: %w", t.table, err)
}
if n, _ := res.RowsAffected(); n > 0 {
out[t.table] = n
}
}
return out, tx.Commit()
}