USE [DocumedisLogs]
GO

/*
MDDOC-878

Purge of the table documedisLogs.dbo.DocumedisSecurityLogs

Only records that are more than 7 months old and present as archived in [archivedRowsJournal]
will be purged.

Deletion is made in small batches to avoid locking.
*/
CREATE PROCEDURE [purge_documedisSecurityLogs] AS
BEGIN
    DECLARE @cutoff DATE = DATEADD(MONTH, -7, CURRENT_TIMESTAMP);
    DECLARE @batch INT = 5000;
    DECLARE @row_count INT = 1
    DECLARE @tbl_to_del TABLE([DocumedisSecurityLogId] BIGINT NOT NULL);
    
    WHILE @row_count > 0 BEGIN
        TRUNCATE TABLE @tbl_to_del;
        
        -- region populate filter table
        INSERT INTO @tbl_to_del([DocumedisSecurityLogId])
        SELECT TOP (@batch)
               [s].[DocumedisSecurityLogId]
        FROM [DocumedisSecurityLogs] [s]
        WHERE [s].[LogDateTime] > @cutoff
          AND EXISTS(
            SELECT 1
            FROM [archivedRowsJournal] [j]
            WHERE [j].[tableName] = 'DocumedisSecurityLogs'
              AND [j].[tableRowId] = [s].[DocumedisSecurityLogId]
        );
        
        SELECT @row_count = COUNT(1)
        FROM @tbl_to_del;
        -- endregion
        
        -- region DocumedisSecurityLogs
        DELETE [s]
        FROM @tbl_to_del [d]
            INNER JOIN [dbo].[DocumedisSecurityLogs] [s] ON [s].[DocumedisSecurityLogId] = [d].[DocumedisSecurityLogId];
        -- endregion
        
        -- region archivedRowsJournal
        DELETE [j]
        FROM [archivedRowsJournal] [j]
            INNER JOIN @tbl_to_del [d] ON [d].[DocumedisSecurityLogId] = [j].[tableRowId]
        WHERE [tableName] = 'DocumedisSecurityLogs'
        -- endregion
    END
END
