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.
Only 1 iteration is made, the job calling this procedure will handle the calls and be executed several times.
it will also handle the hours the deletion should run from / to
*/
CREATE OR ALTER PROCEDURE [purge_documedisSecurityLogs] AS
BEGIN
    DECLARE @cutoff DATE = DATEADD(MONTH, -7, CURRENT_TIMESTAMP);
    DECLARE @batch INT = 5000;
    DECLARE @tbl_to_del TABLE([DocumedisSecurityLogId] BIGINT NOT NULL);
    
    BEGIN TRANSACTION;

    -- 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]
    );
    -- endregion

    -- region DocumedisSecurityLogs
    DELETE [s]
    FROM @tbl_to_del [d]
        INNER JOIN [dbo].[DocumedisSecurityLogs] [s] ON [s].[DocumedisSecurityLogId] = [d].[DocumedisSecurityLogId];
    PRINT CONVERT(VARCHAR(20), CURRENT_TIMESTAMP, 114)+' - Deleted from DocumedisSecurityLogs. '+REPLACE(REPLACE(CONVERT(VARCHAR(100), CONVERT(MONEY, @@rowcount), 1),',',''''),'.00','')+' row(s) affected.';
    -- endregion

    -- region archivedRowsJournal
    DELETE [j]
    FROM [archivedRowsJournal] [j]
        INNER JOIN @tbl_to_del [d] ON [d].[DocumedisSecurityLogId] = [j].[tableRowId]
    WHERE [tableName] = 'DocumedisSecurityLogs';
    PRINT CONVERT(VARCHAR(20), CURRENT_TIMESTAMP, 114)+' - Deleted from archivedRowsJournal. '+REPLACE(REPLACE(CONVERT(VARCHAR(100), CONVERT(MONEY, @@rowcount), 1),',',''''),'.00','')+' row(s) affected.';
    -- endregion

    COMMIT TRANSACTION;
END
