|
| 1 | +package retention |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/icinga/icinga-go-library/backoff" |
| 8 | + "github.com/icinga/icinga-go-library/com" |
| 9 | + "github.com/icinga/icinga-go-library/database" |
| 10 | + "github.com/icinga/icinga-go-library/retry" |
| 11 | + "github.com/icinga/icinga-go-library/types" |
| 12 | + "github.com/jmoiron/sqlx" |
| 13 | +) |
| 14 | + |
| 15 | +// TimeBoundPruner defines the configuration for pruning rows from a table based on a time column. |
| 16 | +// |
| 17 | +// This struct is designed to be flexible and reusable for different tables with varying time columns and |
| 18 | +// primary keys. It also supports maintaining referential integrity by allowing the definition of related |
| 19 | +// tables that reference the primary keys of the main table, ensuring that any related rows are also pruned |
| 20 | +// accordingly. |
| 21 | +type TimeBoundPruner struct { |
| 22 | + Table string |
| 23 | + PK string |
| 24 | + TimeColumn string |
| 25 | + |
| 26 | + Referrers []ReferencingRowPruner |
| 27 | +} |
| 28 | + |
| 29 | +// Exec prunes rows from the specified table that are older than the given time threshold. |
| 30 | +// |
| 31 | +// If Referrers are defined, it first retrieves the primary keys of the rows to be deleted and then executes the |
| 32 | +// corresponding DELETE statements for each [ReferencingRowPruner] before finally deleting the rows from the main |
| 33 | +// table. If no Referrers are defined, it directly deletes rows based on the time column. |
| 34 | +// |
| 35 | +// The method returns only the total number of deleted rows from the main table. |
| 36 | +func (tbp *TimeBoundPruner) Exec(ctx context.Context, db *database.DB, olderThan types.UnixMilli, limit uint64) (uint64, error) { |
| 37 | + deleteStmt := tbp.assembleDelete(db.DriverName(), limit, len(tbp.Referrers) > 0) |
| 38 | + if len(tbp.Referrers) == 0 { |
| 39 | + return exec(ctx, db, deleteStmt, limit, olderThan) |
| 40 | + } |
| 41 | + |
| 42 | + selectStmt := tbp.assembleSelect(limit) |
| 43 | + var total uint64 |
| 44 | + for { |
| 45 | + var ids []any |
| 46 | + err := retry.WithBackoff( |
| 47 | + ctx, |
| 48 | + func(ctx context.Context) error { |
| 49 | + if err := db.SelectContext(ctx, &ids, db.Rebind(selectStmt), olderThan); err != nil { |
| 50 | + return database.CantPerformQuery(err, selectStmt) |
| 51 | + } |
| 52 | + return nil |
| 53 | + }, |
| 54 | + retry.Retryable, |
| 55 | + backoff.DefaultBackoff, |
| 56 | + db.GetDefaultRetrySettings(), |
| 57 | + ) |
| 58 | + if err != nil { |
| 59 | + return 0, err |
| 60 | + } |
| 61 | + |
| 62 | + if len(ids) == 0 { |
| 63 | + // No rows to delete, so we can skip executing the referrers and the final delete statement. |
| 64 | + return total, nil |
| 65 | + } |
| 66 | + |
| 67 | + for _, referrer := range tbp.Referrers { |
| 68 | + if _, err := referrer.Exec(ctx, db, ids...); err != nil { |
| 69 | + return 0, err |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if affected, err := exec(ctx, db, deleteStmt, 0, ids...); err != nil { |
| 74 | + return 0, err |
| 75 | + } else { |
| 76 | + total += affected |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +// assembleSelect constructs a select stmt to retrieve primary keys of this pruner based on the time column and limit. |
| 82 | +func (tbp *TimeBoundPruner) assembleSelect(limit uint64) string { |
| 83 | + return fmt.Sprintf(`SELECT %s FROM %s WHERE %[3]s IS NOT NULL AND %[3]s < ? LIMIT %d`, tbp.PK, tbp.Table, tbp.TimeColumn, limit) |
| 84 | +} |
| 85 | + |
| 86 | +// assembleDelete constructs a delete stmt for this pruner based on the database driver and whether we are |
| 87 | +// deleting by primary keys or by time column. |
| 88 | +func (tbp *TimeBoundPruner) assembleDelete(driverName string, limit uint64, byPKs bool) string { |
| 89 | + if byPKs { |
| 90 | + // The limit doesn't apply when deleting by PKs, as the number of PKs is already limited by the provided arguments. |
| 91 | + return fmt.Sprintf(`DELETE FROM %s WHERE %s IN (?)`, tbp.Table, tbp.PK) |
| 92 | + } |
| 93 | + |
| 94 | + switch driverName { |
| 95 | + case database.MySQL: |
| 96 | + return fmt.Sprintf(`DELETE FROM %s WHERE %[2]s IS NOT NULL AND %[2]s < ? LIMIT %d`, tbp.Table, tbp.TimeColumn, limit) |
| 97 | + case database.PostgreSQL: |
| 98 | + return fmt.Sprintf(` |
| 99 | +WITH rows AS (SELECT %[1]s FROM %[2]s WHERE %[3]s IS NOT NULL AND %[3]s < ? LIMIT %[4]d) |
| 100 | +DELETE FROM %[2]s WHERE %[1]s IN (SELECT * FROM rows)`, |
| 101 | + tbp.PK, tbp.Table, tbp.TimeColumn, limit) |
| 102 | + default: |
| 103 | + panic(fmt.Sprintf("invalid database type %s", driverName)) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// ReferencingRowPruner defines the configuration for pruning rows that reference the primary keys of another table. |
| 108 | +// |
| 109 | +// This struct is used to maintain referential integrity when pruning rows from a main table by ensuring that |
| 110 | +// any related rows in other tables are also pruned accordingly. In other words, it allows to explicitly define |
| 111 | +// cascading deletes for related tables without relying on database-level foreign key constraints. |
| 112 | +type ReferencingRowPruner struct { |
| 113 | + Table string |
| 114 | + FK string |
| 115 | +} |
| 116 | + |
| 117 | +// Exec performs the pruning operation by deleting rows from the specified table that reference the given primary keys. |
| 118 | +func (rrp *ReferencingRowPruner) Exec(ctx context.Context, db *database.DB, pks ...any) (uint64, error) { |
| 119 | + return exec(ctx, db, rrp.assembleDelete(), 0, pks...) |
| 120 | +} |
| 121 | + |
| 122 | +// assembleDelete constructs the delete statement for the ReferencingRowPruner based on the foreign key. |
| 123 | +func (rrp *ReferencingRowPruner) assembleDelete() string { |
| 124 | + return fmt.Sprintf(`DELETE FROM %s WHERE %s IN (?)`, rrp.Table, rrp.FK) |
| 125 | +} |
| 126 | + |
| 127 | +// exec executes the given delete statement with the provided arguments and limit, handling retries and counting affected rows. |
| 128 | +func exec(ctx context.Context, db *database.DB, query string, limit uint64, args ...any) (uint64, error) { |
| 129 | + stmt, expandedArgs, err := sqlx.In(query, args) |
| 130 | + if err != nil { |
| 131 | + return 0, err |
| 132 | + } |
| 133 | + |
| 134 | + var counter com.Counter |
| 135 | + defer db.Log(ctx, query, &counter).Stop() |
| 136 | + |
| 137 | + for { |
| 138 | + var affected uint64 |
| 139 | + err = retry.WithBackoff( |
| 140 | + ctx, |
| 141 | + func(ctx context.Context) error { |
| 142 | + res, err := db.ExecContext(ctx, db.Rebind(stmt), expandedArgs...) |
| 143 | + if err != nil { |
| 144 | + return database.CantPerformQuery(err, query) |
| 145 | + } |
| 146 | + |
| 147 | + n, err := res.RowsAffected() |
| 148 | + if err == nil && n > 0 { |
| 149 | + affected = uint64(n) |
| 150 | + } |
| 151 | + return err |
| 152 | + }, |
| 153 | + retry.Retryable, |
| 154 | + backoff.DefaultBackoff, |
| 155 | + db.GetDefaultRetrySettings(), |
| 156 | + ) |
| 157 | + if err != nil { |
| 158 | + return 0, err |
| 159 | + } |
| 160 | + |
| 161 | + counter.Add(affected) |
| 162 | + // If limit is set to 0, it means we are deleting matching rows by primary keys, so the limit check can be skipped. |
| 163 | + if limit == 0 || affected < limit { |
| 164 | + break |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + return counter.Total(), nil |
| 169 | +} |
0 commit comments