Skip to content

Commit

Permalink
[v15] pgevents: fix retention_period and disable_cleanup on crdb (#46148
Browse files Browse the repository at this point in the history
)

* pgevents: fix retention_period and disable_cleanup on crdb

* avoid integer to INTERVAL casts
  • Loading branch information
espadolini authored Sep 3, 2024
1 parent a1d52ec commit 22882cf
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/events/pgevents/pgevents.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,22 @@ const (
);
CREATE INDEX events_search_session_events_idx ON events (session_id, event_time, event_id)
WHERE session_id != '00000000-0000-0000-0000-000000000000';`
dateIndex = "CREATE INDEX events_creation_time_idx ON events USING brin (creation_time);"
schemaV1TableWithDateIndex = schemaV1Table + "\n" + dateIndex
schemaV1CockroachSetRowExpiry = "ALTER TABLE events SET (ttl_expiration_expression = '((creation_time AT TIME ZONE ''UTC'') + (%d * INTERVAL ''1 microsecond'')) AT TIME ZONE ''UTC'' ');"
schemaV1CockroachUnsetRowExpiry = "ALTER TABLE events RESET (ttl_expiration_expression);"
dateIndex = "CREATE INDEX events_creation_time_idx ON events USING brin (creation_time);"
schemaV1TableWithDateIndex = schemaV1Table + "\n" + dateIndex

// the 'n'::INTERVAL expression will saturate at around 292 years (which is
// perfectly acceptable for a retention period of the audit log), and the
// sum between a TIMESTAMPTZ set around 2024 and an INTERVAL of up to 292
// years is always representable
//
// the string to INTERVAL cast should be stable, unlike any integer to
// INTERVAL cast (see https://github.com/cockroachdb/cockroach/issues/57876)
schemaV1CockroachSetRowExpirySeconds = "ALTER TABLE events SET (ttl_expiration_expression = '((creation_time AT TIME ZONE ''UTC'') + (''%d''::INTERVAL)) AT TIME ZONE ''UTC''');"
// the asymmetry here is intended, crdb requires "RESET (ttl)" to disable
// row-level TTL on a table, whereas "RESET (ttl_expiration_expression)"
// would remove the expression in favor of ttl_expire_after (and it will
// error out if ttl_expire_after is unset)
schemaV1CockroachUnsetRowExpiry = "ALTER TABLE events RESET (ttl);"
)

// Config is the configuration struct to pass to New.
Expand Down Expand Up @@ -264,11 +276,10 @@ func configureCockroachDBRetention(ctx context.Context, cfg *Config, pool *pgxpo
expiryQuery = schemaV1CockroachUnsetRowExpiry
} else {
cfg.Log.DebugContext(ctx, "Configuring CockroachDB native row expiry")
expiryQuery = fmt.Sprintf(schemaV1CockroachSetRowExpiry, cfg.RetentionPeriod)
expiryQuery = fmt.Sprintf(schemaV1CockroachSetRowExpirySeconds, int64(cfg.RetentionPeriod.Seconds()))
}
_, err := pool.Exec(ctx, expiryQuery, pgx.QueryExecModeExec)
return trace.Wrap(err)

}

func buildSchema(isCockroach bool, cfg *Config) (schemas []string, err error) {
Expand Down

0 comments on commit 22882cf

Please sign in to comment.