@@ -2,14 +2,21 @@ package icingadb
22
33import (
44 "context"
5+ "fmt"
6+ "github.com/icinga/icinga-go-library/com"
57 "github.com/icinga/icinga-go-library/database"
8+ "github.com/icinga/icinga-go-library/logging"
9+ "github.com/icinga/icinga-go-library/periodic"
610 "github.com/icinga/icinga-go-library/types"
711 v1 "github.com/icinga/icingadb/pkg/icingadb/v1"
812 "github.com/pkg/errors"
913 "golang.org/x/sync/errgroup"
1014 "time"
1115)
1216
17+ // tableName defines the table name of v1.SlaLifecycle type.
18+ var tableName = database .TableName (v1 .NewSlaLifecycle ())
19+
1320// GetCheckableFromSlaLifecycle returns the original checkable from which the specified sla lifecycle were transformed.
1421// When the passed entity is not of type *SlaLifecycle, it is returned as is.
1522func GetCheckableFromSlaLifecycle (e database.Entity ) database.Entity {
@@ -86,3 +93,42 @@ func CreateSlaLifecyclesFromCheckables(
8693
8794 return slaLifecycles
8895}
96+
97+ // StreamIDsFromUpdatedSlaLifecycles updates the `delete_time` of the sla lifecycle table for each of the Checkables
98+ // consumed from the provided "entities" chan and upon successful execution of the query streams the original IDs
99+ // of the entities into the returned channel.
100+ //
101+ // It's unlikely, but when a given Checkable doesn't already have a `create_time` entry in the database, the update
102+ // query won't update anything. Either way the entities IDs are streamed into the returned chan.
103+ func StreamIDsFromUpdatedSlaLifecycles (
104+ ctx context.Context , db * database.DB , g * errgroup.Group , logger * logging.Logger , entities <- chan database.Entity , bulkSize int ,
105+ ) <- chan any {
106+ deleteEntityIDs := make (chan any , 1 )
107+
108+ g .Go (func () error {
109+ defer close (deleteEntityIDs )
110+
111+ var counter com.Counter
112+ defer periodic .Start (ctx , logger .Interval (), func (_ periodic.Tick ) {
113+ if count := counter .Reset (); count > 0 {
114+ logger .Infof ("Updated %d sla lifecycles" , count )
115+ }
116+ }).Stop ()
117+
118+ sem := db .GetSemaphoreForTable (tableName )
119+ stmt := fmt .Sprintf (`UPDATE %s SET delete_time = :delete_time WHERE "id" = :id AND "delete_time" = 0` , tableName )
120+
121+ if bulkSize <= 0 {
122+ bulkSize = db .Options .MaxPlaceholdersPerStatement
123+ }
124+
125+ // extractEntityId is used as a callback for the on success mechanism to extract the checkables id.
126+ extractEntityId := func (e database.Entity ) any { return e .(* v1.SlaLifecycle ).SourceEntity .ID () }
127+
128+ return db .NamedBulkExec (
129+ ctx , stmt , bulkSize , sem , CreateSlaLifecyclesFromCheckables (ctx , g , entities , true ),
130+ com .NeverSplit [database .Entity ], OnSuccessApplyAndSendTo [database.Entity , any ](deleteEntityIDs , extractEntityId ))
131+ })
132+
133+ return deleteEntityIDs
134+ }
0 commit comments