diff --git a/.direct-version b/.direct-version index 0476155..ecf00d9 100644 --- a/.direct-version +++ b/.direct-version @@ -1 +1 @@ -2.2.4 \ No newline at end of file +2.2.5 \ No newline at end of file diff --git a/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdGetConsistencyTimestampTests.cs b/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdGetConsistencyTimestampTests.cs new file mode 100644 index 0000000..72425f0 --- /dev/null +++ b/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdGetConsistencyTimestampTests.cs @@ -0,0 +1,124 @@ +namespace IntegrationTests.Tests.StoredProcedureTests; + +/// +/// Integration tests for [omd].[GetConsistencyTimestamp]. Two Modules each load a target from their own +/// source table. Both latest load windows carry changes, as right after a load that brought new data. +/// +[TestClass] +public class OmdGetConsistencyTimestampTests : BaseTestContainer +{ + private const string SpName = "[omd].[GetConsistencyTimestamp]"; + private const string TableList = "TGT_CONSISTENCY_A,TGT_CONSISTENCY_B"; + + private static readonly DateTime FirstLoadEnd = new(2026, 1, 1, 10, 0, 0); + private static readonly DateTime SecondLoadEnd = new(2026, 1, 1, 10, 5, 0); + + [TestInitialize] + public async Task TestInitialize() + { + await ContainerManager.InitializeAsync(); + await ContainerManager.PopulateDatabaseAsync(); + await ArrangeTwoLoadedSourcesAsync(); + } + + [TestCleanup] + public async Task TestCleanup() + { + await ContainerManager.DisposeAsync(); + } + + /// + /// Source A was loaded up to and source B up to , each by + /// a succeeded Module Instance whose load window ends at the latest row of its source. + /// + private async Task ArrangeTwoLoadedSourcesAsync() + { + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + await conn.ExecuteAsync(@" + CREATE TABLE dbo.SRC_CONSISTENCY_A (KEY_VALUE INT NOT NULL, LOAD_DATETIME DATETIME2(7) NOT NULL, MODULE_INSTANCE_ID BIGINT NOT NULL); + CREATE TABLE dbo.SRC_CONSISTENCY_B (KEY_VALUE INT NOT NULL, LOAD_DATETIME DATETIME2(7) NOT NULL, MODULE_INSTANCE_ID BIGINT NOT NULL); + + INSERT INTO omd.MODULE (MODULE_CODE, MODULE_TYPE, DATA_OBJECT_SOURCE, DATA_OBJECT_TARGET, AREA_CODE, FREQUENCY_CODE, MODULE_DESCRIPTION, ACTIVE_INDICATOR, EXECUTABLE) + VALUES (N'm_CONSISTENCY_A', N'Ingestion', N'dbo.SRC_CONSISTENCY_A', N'TGT_CONSISTENCY_A', N'STG', N'On-demand', N'Consistency test module A', 'Y', N'SELECT 1'), + (N'm_CONSISTENCY_B', N'Ingestion', N'dbo.SRC_CONSISTENCY_B', N'TGT_CONSISTENCY_B', N'STG', N'On-demand', N'Consistency test module B', 'Y', N'SELECT 1'); + + INSERT INTO omd.MODULE_INSTANCE (MODULE_ID, BATCH_INSTANCE_ID, START_TIMESTAMP, END_TIMESTAMP, INTERNAL_PROCESSING_CODE, NEXT_RUN_STATUS_CODE, EXECUTION_STATUS_CODE) + SELECT MODULE_ID, 0, SYSUTCDATETIME(), SYSUTCDATETIME(), N'Proceed', N'Proceed', N'Succeeded' + FROM omd.MODULE + WHERE MODULE_CODE IN (N'm_CONSISTENCY_A', N'm_CONSISTENCY_B'); + + INSERT INTO dbo.SRC_CONSISTENCY_A (KEY_VALUE, LOAD_DATETIME, MODULE_INSTANCE_ID) + SELECT 1, @FirstLoadEnd, mi.MODULE_INSTANCE_ID + FROM omd.MODULE_INSTANCE mi JOIN omd.MODULE m ON m.MODULE_ID = mi.MODULE_ID + WHERE m.MODULE_CODE = N'm_CONSISTENCY_A'; + + INSERT INTO dbo.SRC_CONSISTENCY_B (KEY_VALUE, LOAD_DATETIME, MODULE_INSTANCE_ID) + SELECT 1, @SecondLoadEnd, mi.MODULE_INSTANCE_ID + FROM omd.MODULE_INSTANCE mi JOIN omd.MODULE m ON m.MODULE_ID = mi.MODULE_ID + WHERE m.MODULE_CODE = N'm_CONSISTENCY_B'; + + INSERT INTO omd.SOURCE_CONTROL (MODULE_ID, MODULE_INSTANCE_ID, START_VALUE, END_VALUE) + SELECT mi.MODULE_ID, mi.MODULE_INSTANCE_ID, N'1900-01-01 00:00:00.0000000', + CONVERT(NVARCHAR(100), CASE m.MODULE_CODE WHEN N'm_CONSISTENCY_A' THEN @FirstLoadEnd ELSE @SecondLoadEnd END, 121) + FROM omd.MODULE_INSTANCE mi JOIN omd.MODULE m ON m.MODULE_ID = mi.MODULE_ID + WHERE m.MODULE_CODE IN (N'm_CONSISTENCY_A', N'm_CONSISTENCY_B');", + new { FirstLoadEnd, SecondLoadEnd }); + } + + private static async Task<(int ReturnCode, DateTime? ConsistencyDateTime, string? SuccessIndicator)> GetConsistencyTimestampAsync(SqlConnection conn) + { + var parameters = new DynamicParameters(); + parameters.Add("@TableList", TableList, dbType: System.Data.DbType.String, size: -1); + parameters.Add("@ConsistencyDateTime", dbType: System.Data.DbType.DateTime2, direction: System.Data.ParameterDirection.Output); + parameters.Add("@SuccessIndicator", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: 1); + parameters.Add("@MessageLog", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: -1); + parameters.Add("@ReturnCode", dbType: System.Data.DbType.Int32, direction: System.Data.ParameterDirection.ReturnValue); + + await conn.ExecuteAsync(SpName, parameters, commandType: System.Data.CommandType.StoredProcedure); + + return ( + parameters.Get("@ReturnCode"), + parameters.Get("@ConsistencyDateTime"), + parameters.Get("@SuccessIndicator")); + } + + [TestMethod] + public async Task OmdGetConsistencyTimestamp_ReturnsLatestWindowEnd_WhenEverySourceIsFullyLoaded() + { + // Arrange + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + + // Act + var (returnCode, consistencyDateTime, successIndicator) = await GetConsistencyTimestampAsync(conn); + + // Assert + Assert.AreEqual(0, returnCode, "Stored procedure should return 0 on success."); + Assert.AreEqual("Y", successIndicator); + Assert.AreEqual(SecondLoadEnd, consistencyDateTime, + "Both sources are fully loaded, so all data up to the latest load window end is consistent; the earlier window end of source A must not hold it back."); + } + + [TestMethod] + public async Task OmdGetConsistencyTimestamp_ReturnsLaggingWindowEnd_WhenASourceHasOutstandingRows() + { + // Arrange: source A receives a row after its latest load window, which has not been processed yet. + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + await conn.ExecuteAsync(@" + INSERT INTO dbo.SRC_CONSISTENCY_A (KEY_VALUE, LOAD_DATETIME, MODULE_INSTANCE_ID) + SELECT 2, DATEADD(MINUTE, 10, @FirstLoadEnd), MAX(MODULE_INSTANCE_ID) + FROM dbo.SRC_CONSISTENCY_A;", + new { FirstLoadEnd }); + + // Act + var (returnCode, consistencyDateTime, successIndicator) = await GetConsistencyTimestampAsync(conn); + + // Assert + Assert.AreEqual(0, returnCode, "Stored procedure should return 0 on success."); + Assert.AreEqual("Y", successIndicator); + Assert.AreEqual(FirstLoadEnd, consistencyDateTime, + "Source A has outstanding rows, so its load window end is the consistency timestamp."); + } +} + +// See references for test to code for assistants +// See: Direct_Framework\Stored Procedures\omd.GetConsistencyTimestamp.sql diff --git a/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdRunModuleTests.cs b/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdRunModuleTests.cs index 1141a18..b76e303 100644 --- a/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdRunModuleTests.cs +++ b/Direct_Framework.Integration.Tests/Tests/StoredProcedureTests/OmdRunModuleTests.cs @@ -49,5 +49,100 @@ await conn.ExecuteAsync( "SELECT COUNT(*) FROM [omd].[EVENT_LOG] WHERE [EVENT_DETAIL] LIKE '%m_DOES_NOT_EXIST%';"); Assert.IsTrue(eventCount > 0, "A failed run of an unknown module code must appear in omd.EVENT_LOG."); + + var eventDetail = await conn.ExecuteScalarAsync( + "SELECT TOP 1 [EVENT_DETAIL] FROM [omd].[EVENT_LOG] WHERE [EVENT_DETAIL] LIKE '%m_DOES_NOT_EXIST%' ORDER BY [EVENT_ID] DESC;"); + StringAssert.Contains(eventDetail, "is not registered in [omd].[MODULE], so there is nothing to run.", + "The event log must say why the module could not run, not only that no module instance was registered."); + + var messageLog = parameters.Get("@MessageLog"); + StringAssert.Contains(messageLog, "is not registered in [omd].[MODULE]"); + Assert.IsFalse(messageLog.Contains("The executable code retrieved is", StringComparison.Ordinal), + "An unknown module code must be reported before an (empty) executable code is retrieved."); + } + + /// + /// With auto-registration on (the default), an unknown Module Code without a @Query has nothing to + /// run either. It must fail with the same clear reason instead of attempting a registration. + /// + [TestMethod] + public async Task RunModule_UnknownModuleCodeWithAutoRegistration_ReportsThatItIsNotRegistered() + { + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + + var parameters = new DynamicParameters(); + parameters.Add("@ModuleCode", "m_DOES_NOT_EXIST_EITHER"); + parameters.Add("@Debug", "N"); + parameters.Add("@SuccessIndicator", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: 1); + parameters.Add("@MessageLog", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: -1); + + await conn.ExecuteAsync( + "EXEC [omd].[RunModule] @ModuleCode = @ModuleCode, @Debug = @Debug, @SuccessIndicator = @SuccessIndicator OUTPUT, @MessageLog = @MessageLog OUTPUT", + parameters); + + Assert.AreEqual("N", parameters.Get("@SuccessIndicator")); + StringAssert.Contains(parameters.Get("@MessageLog"), "is not registered in [omd].[MODULE], so there is nothing to run."); + + var registered = await conn.ExecuteScalarAsync( + "SELECT COUNT(*) FROM [omd].[MODULE] WHERE [MODULE_CODE] = N'm_DOES_NOT_EXIST_EITHER';"); + Assert.AreEqual(0, registered, "An unknown Module Code without code to run must not be registered."); + } + + /// + /// A Module registered without a target data object carries the 'N/A' marker. After a failed run, the next + /// run rolls back first; that rollback has nothing to delete and must not run a DELETE against a table called + /// 'N/A'. The next run must fail for the same reason as the first one: the code it executes. + /// + [TestMethod] + public async Task RunModule_RerunAfterFailureWithoutTargetDataObject_FailsOnTheCodeAgain() + { + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + await conn.ExecuteAsync( + "EXEC [omd].[RegisterModule] @ModuleCode = N'm_FAILS_WITHOUT_TARGET', @ModuleAreaCode = N'STG', @Executable = N'SELECT 1/0';"); + + for (var run = 1; run <= 2; run++) + { + var parameters = new DynamicParameters(); + parameters.Add("@SuccessIndicator", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: 1); + parameters.Add("@MessageLog", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: -1); + + await conn.ExecuteAsync( + "EXEC [omd].[RunModule] @ModuleCode = N'm_FAILS_WITHOUT_TARGET', @Query = N'SELECT 1/0', @SuccessIndicator = @SuccessIndicator OUTPUT, @MessageLog = @MessageLog OUTPUT", + parameters); + + Assert.AreEqual("N", parameters.Get("@SuccessIndicator"), $"Run {run} executes a division by zero and must fail."); + } + + var invalidObjectEvents = await conn.ExecuteScalarAsync( + "SELECT COUNT(*) FROM [omd].[EVENT_LOG] WHERE [EVENT_DETAIL] LIKE N'%Invalid object name%';"); + Assert.AreEqual(0, invalidObjectEvents, "The rollback must not address a target data object called 'N/A'."); + + var divideByZeroEvents = await conn.ExecuteScalarAsync( + "SELECT COUNT(*) FROM [omd].[EVENT_LOG] WHERE [EVENT_DETAIL] LIKE N'%Divide by zero%';"); + Assert.AreEqual(2, divideByZeroEvents, "Both runs must fail on the executed code."); + } + + /// + /// With auto-registration on (the default), an unregistered Module Code with a @Query is registered on the + /// fly in the maintenance area (MAINT), because the area is required and nothing else names one. + /// + [TestMethod] + public async Task RunModule_UnknownModuleCodeWithQuery_IsAutoRegisteredInTheMaintenanceArea() + { + using var conn = new SqlConnection(ContainerManager.DirectConnectionString); + + var parameters = new DynamicParameters(); + parameters.Add("@SuccessIndicator", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: 1); + parameters.Add("@MessageLog", dbType: System.Data.DbType.String, direction: System.Data.ParameterDirection.Output, size: -1); + + await conn.ExecuteAsync( + "EXEC [omd].[RunModule] @ModuleCode = N'm_AUTO_REGISTERED', @Query = N'SELECT 1', @SuccessIndicator = @SuccessIndicator OUTPUT, @MessageLog = @MessageLog OUTPUT", + parameters); + + Assert.AreEqual("Y", parameters.Get("@SuccessIndicator"), parameters.Get("@MessageLog")); + + var areaCode = await conn.ExecuteScalarAsync( + "SELECT [AREA_CODE] FROM [omd].[MODULE] WHERE [MODULE_CODE] = N'm_AUTO_REGISTERED';"); + Assert.AreEqual("MAINT", areaCode); } } diff --git a/Direct_Framework/DeploymentScripts/3-PostDeployment/omd_metadata.FRAMEWORK_METADATA.sql b/Direct_Framework/DeploymentScripts/3-PostDeployment/omd_metadata.FRAMEWORK_METADATA.sql index 511736a..647bca4 100644 --- a/Direct_Framework/DeploymentScripts/3-PostDeployment/omd_metadata.FRAMEWORK_METADATA.sql +++ b/Direct_Framework/DeploymentScripts/3-PostDeployment/omd_metadata.FRAMEWORK_METADATA.sql @@ -27,7 +27,7 @@ DECLARE @tblMerge TABLE( INSERT INTO @tblMerge([CODE], [VALUE], [GROUP], [DESCRIPTION], [ACTIVE_INDICATOR]) VALUES - (N'DIRECT_VERSION', N'2.2.4', N'SYSTEM_METADATA', + (N'DIRECT_VERSION', N'2.2.5', N'SYSTEM_METADATA', N'The current version of the DIRECT Framework and database', 'Y') ,(N'LOG_TO_EVENT_LOG', N'Y', N'SETTINGS', diff --git a/Direct_Framework/Stored Procedures/omd.CreateModuleInstance.sql b/Direct_Framework/Stored Procedures/omd.CreateModuleInstance.sql index 3bbe2e7..24d1a96 100644 --- a/Direct_Framework/Stored Procedures/omd.CreateModuleInstance.sql +++ b/Direct_Framework/Stored Procedures/omd.CreateModuleInstance.sql @@ -5,7 +5,7 @@ * optionally linked to a Batch Instance, and captures executed code hash. * * @package DIRECT Framework - * @version 2.1.0 + * @version 2.2.5 * @see https://github.com/data-solution-automation-engine/DIRECT * * @param {NVARCHAR(500)} @ModuleCode [in] (required) @@ -178,8 +178,10 @@ BEGIN [omd].[AddLogMessage](DEFAULT, DEFAULT, DEFAULT, @LogMessage, @MessageLog); DECLARE @RegisterSuccessIndicator CHAR(1); + -- The area is required; an auto-registered Module has no known layer, so it lands in maintenance (MAINT). EXEC [omd].[RegisterModule] @ModuleCode = @ModuleCode, + @ModuleAreaCode = N'MAINT', @Debug = @Debug, @ModuleId = @ModuleId OUTPUT, @SuccessIndicator = @RegisterSuccessIndicator OUTPUT, diff --git a/Direct_Framework/Stored Procedures/omd.GetConsistencyTimestamp.sql b/Direct_Framework/Stored Procedures/omd.GetConsistencyTimestamp.sql index e0d7b56..5b4e824 100644 --- a/Direct_Framework/Stored Procedures/omd.GetConsistencyTimestamp.sql +++ b/Direct_Framework/Stored Procedures/omd.GetConsistencyTimestamp.sql @@ -1,9 +1,10 @@ /** * @procedure [omd].[GetConsistencyTimestamp] - * @description Compute the consistency timestamp across target tables as the minimum end-value of latest successful load windows. + * @description Compute the consistency timestamp across target tables as the minimum end-value of latest successful load windows + * of the sources that still have outstanding rows, or the maximum end-value when no source lags behind. * * @package DIRECT Framework - * @version 2.2.0 + * @version 2.2.5 * @see https://github.com/data-engine-thinking/DIRECT * * @param {NVARCHAR(MAX)} @TableList [in] (required) @@ -15,7 +16,7 @@ * @param {NVARCHAR(128)} @SourceModuleInstanceColumn [in] (optional, default='MODULE_INSTANCE_ID') * Name of the column in the source data objects that holds the module instance id that loaded the row. * @param {CHAR(1)} @SourceDataLookupIndicator [in] (optional, default='Y') - * 'Y' checks the source data objects for outstanding rows when a logical source group reports no changes. + * 'Y' checks the source data objects of every logical source group for outstanding rows beyond its load window. * 'N' relies on the control tables only and treats such a group as up to date; use this when the data * objects live in another engine (external orchestration) and the load windows are maintained explicitly. * @param {CHAR(1)} @Debug [in] (optional, default='N') @@ -451,7 +452,8 @@ WHERE COALESCE(INTERVAL_END_TIMESTAMP_ORDER, 0) = 1 PRINT CHAR(10) + 'Working on ' + @localDataObjectSource + ' with change for logical group change indicator ' + @localChangeForLogicalGroup + ' an local load window end datetime ' + CONVERT(VARCHAR(20), @localIntervalEndDatetime); END - IF @localChangeForLogicalGroup = 'Y' + -- Without source data lookups, a change in the logical group means it may still be catching up. + IF @localChangeForLogicalGroup = 'Y' AND UPPER(COALESCE(@SourceDataLookupIndicator, 'Y')) <> 'Y' BEGIN INSERT INTO @ConsistencyDateTimeTable VALUES @@ -476,8 +478,11 @@ WHERE COALESCE(INTERVAL_END_TIMESTAMP_ORDER, 0) = 1 END END - -- If the logical group is up to date, e.g. there are no changes then lookups to the sources are required to assert if there are any outstanding rows. - IF @localChangeForLogicalGroup = 'N' AND UPPER(COALESCE(@SourceDataLookupIndicator, 'Y')) = 'Y' + -- Look up the source to assert if there are any outstanding rows, whether or not the latest load window had changes. + -- A change only says that data was loaded, not that the source holds more: right after a load that brought data, + -- each source is typically complete up to its own load window end. Treating such a group as lagging would make + -- the earliest window end win and leave out the data that other sources loaded moments later. + IF UPPER(COALESCE(@SourceDataLookupIndicator, 'Y')) = 'Y' BEGIN DECLARE @localSourceMaxDateTime DATETIME2(7); @@ -556,6 +561,20 @@ END FROM @ConsistencyDateTimeTable WHERE COALESCE(UP_TO_DATE_INDICATOR, '') = 'N' + + -- When no logical group lags behind its source, every target is complete up to its latest load window. + IF @ConsistencyDateTime IS NULL + BEGIN + SELECT + @ConsistencyDateTime = MAX(CONSISTENCY_DATETIME) + FROM + @ConsistencyDateTimeTable + + IF @Debug = 'Y' + BEGIN + PRINT 'No logical group has outstanding rows, so the max load window end is used.'; + END + END END TRY BEGIN CATCH diff --git a/Direct_Framework/Stored Procedures/omd.ModuleEvaluation.sql b/Direct_Framework/Stored Procedures/omd.ModuleEvaluation.sql index 3b08e84..cb5f5a7 100644 --- a/Direct_Framework/Stored Procedures/omd.ModuleEvaluation.sql +++ b/Direct_Framework/Stored Procedures/omd.ModuleEvaluation.sql @@ -3,7 +3,7 @@ * @description Determine whether a Module Instance can proceed based on current and prior instance states. * * @package DIRECT Framework - * @version 2.2.0 + * @version 2.2.5 * @see https://github.com/data-engine-thinking/DIRECT * * @param {BIGINT} @ModuleInstanceId [in] (required) @@ -427,7 +427,8 @@ BEGIN DECLARE @LocalAreaCode NVARCHAR(100) = (SELECT omd.GetModuleAreaByModuleId(@ModuleId)); - IF @TableCodeSafe <> 'N/A' + -- Compare the raw target: the quoted @TableCodeSafe reads '[N/A]' and never matches the 'no target' marker. + IF TRIM(COALESCE(@TableCode, N'')) NOT IN (N'', N'N/A') BEGIN --IF @LocalAreaCode = 'INT' --SET @SqlStatement = 'DELETE FROM '+@TableCodeSafe+' WHERE (omd_module_instance_id IN '+@ModuleInstanceIdList+') OR (omd_update_module_instance_id IN '+@ModuleInstanceIdList+')'; diff --git a/Direct_Framework/Stored Procedures/omd.PrintLog.sql b/Direct_Framework/Stored Procedures/omd.PrintLog.sql index 508141b..09bab02 100644 --- a/Direct_Framework/Stored Procedures/omd.PrintLog.sql +++ b/Direct_Framework/Stored Procedures/omd.PrintLog.sql @@ -3,7 +3,7 @@ * @description Pretty-print a structured JSON message log to the Messages output pane. * * @package DIRECT Framework - * @version 2.1.0 + * @version 2.2.5 * @see https://github.com/data-solution-automation-engine/DIRECT * * @param {NVARCHAR(MAX)} @MessageLog [in] (required) @@ -80,7 +80,7 @@ BEGIN ) DECLARE - @TableLine NVARCHAR(200) = REPLICATE('-', 170), + @TableLine NVARCHAR(200) = REPLICATE('-', 180), @PrintSeverity NVARCHAR(100), @PrintTimestamp NVARCHAR(100), @PrintKey NVARCHAR(1000), @@ -94,7 +94,7 @@ BEGIN PRINT '| ' + LEFT('Severity' + SPACE(8), 8) + ' | ' + LEFT('Timestamp' + SPACE(19), 19) + ' | ' + - LEFT('Key' + SPACE(30), 30) + ' | ' + + LEFT('Key' + SPACE(40), 40) + ' | ' + LEFT('Message' + SPACE(100), 100) + ' |'; PRINT @TableLine; @@ -113,17 +113,17 @@ BEGIN PRINT '| ' + LEFT(ISNULL(@PrintSeverity, 'NULL') + SPACE(8), 8) + ' | ' + LEFT(ISNULL(@PrintTimestamp, 'NULL') + SPACE(19), 19) + ' | ' + - LEFT(ISNULL(@PrintKey, 'NULL') + SPACE(30), 30) + ' | ' + + LEFT(ISNULL(@PrintKey, 'NULL') + SPACE(40), 40) + ' | ' + LEFT(ISNULL(@PrintMessage, 'NULL') + SPACE(100), 100) + ' |'; - IF LEN(@PrintKey) > 30 OR LEN(@PrintMessage) > 100 + IF LEN(@PrintKey) > 40 OR LEN(@PrintMessage) > 100 BEGIN -- Print Formatted Table Contents Line 2 for longer messages -- For even longer messages, review the contents of the log directly PRINT '| ' + SPACE(8) + ' | ' + SPACE(19) + ' | ' + - LEFT(ISNULL(SUBSTRING(@PrintKey, 31, 30) , 'NULL') + SPACE(30), 30) + ' | ' + + LEFT(ISNULL(SUBSTRING(@PrintKey, 41, 40) , 'NULL') + SPACE(40), 40) + ' | ' + LEFT(ISNULL(SUBSTRING(@PrintMessage, 101, 100), 'NULL') + SPACE(100), 100) + ' |'; END diff --git a/Direct_Framework/Stored Procedures/omd.RegisterModule.sql b/Direct_Framework/Stored Procedures/omd.RegisterModule.sql index e670a90..9845f2c 100644 --- a/Direct_Framework/Stored Procedures/omd.RegisterModule.sql +++ b/Direct_Framework/Stored Procedures/omd.RegisterModule.sql @@ -3,7 +3,7 @@ * @description Create (register) a new Module by code, or update existing attributes if changed. * * @package DIRECT Framework - * @version 2.1.0 + * @version 2.2.5 * @see https://github.com/data-solution-automation-engine/DIRECT * * @param {NVARCHAR(500)} @ModuleCode [in] (required) @@ -263,10 +263,11 @@ BEGIN SET @MessageLog = [omd].[AddLogMessage](DEFAULT, DEFAULT, N'Status Update', @LogMessage, @MessageLog) END - - SET @SuccessIndicator = 'Y' END + -- A new and an existing Module both end with a valid Module Id. + SET @SuccessIndicator = 'Y' + -- End of procedure label EndOfProcedure: diff --git a/Direct_Framework/Stored Procedures/omd.RunModule.sql b/Direct_Framework/Stored Procedures/omd.RunModule.sql index 2d9a4a1..9dc22f7 100644 --- a/Direct_Framework/Stored Procedures/omd.RunModule.sql +++ b/Direct_Framework/Stored Procedures/omd.RunModule.sql @@ -6,7 +6,7 @@ * in a DIRECT wrapper in the local database context of the DIRECT database. * * @package DIRECT Framework - * @version 2.1.0 + * @version 2.2.5 * @see https://github.com/data-solution-automation-engine/DIRECT * * @param {NVARCHAR(500)} @ModuleCode [in] (required) @@ -150,7 +150,7 @@ BEGIN SET @MessageLog = [omd].[AddLogMessage]('DEBUG', DEFAULT, N'Start Timestamp', @StartTimestampString, @MessageLog); /* Log parameters */ - SET @MessageLog = [omd].[AddLogMessage]('INFO', DEFAULT, N'Parameter @BModuleCode', + SET @MessageLog = [omd].[AddLogMessage]('INFO', DEFAULT, N'Parameter @ModuleCode', @ModuleCode, @MessageLog); SET @MessageLog = [omd].[AddLogMessage]('INFO', DEFAULT, N'Parameter @Query', @Query, @MessageLog); @@ -162,6 +162,21 @@ BEGIN /* ----- Start of main process ---------------------------------------------- */ + /* A Module Code that is not registered can only run when auto-registration creates it, and that + is only meaningful when @Query provides the code to run: a registered Module carries its own. */ + IF [omd].[GetModuleIdByName](@ModuleCode) IS NULL + AND ([omd_metadata].[GetSettingFlag]('AUTO_REGISTER_MODULES') <> 'Y' OR TRIM(COALESCE(@Query, N'')) = N'') + BEGIN + SET @SuccessIndicator = 'N'; + SET @LogMessage = CONCAT(N'Module Code ''', @ModuleCode, + N''' is not registered in [omd].[MODULE], so there is nothing to run. ', + N'Register the Module first, or check the Module Code.'); + IF @ProcessMessageLog = 'Y' SET @MessageLog = + [omd].[AddLogMessage]('ERROR', DEFAULT, 'Module Validation', @LogMessage, @MessageLog); + IF @ThrowOnFailure = 'Y' THROW 50000, @LogMessage, 1; + GOTO EndOfProcedureFailure; + END + /* Retrieve the code to execute, if not overridden by the @query parameter. */ IF @Query IS NULL OR TRIM(@Query) = '' BEGIN diff --git a/Directory.Build.props b/Directory.Build.props index 5b43346..418c9d8 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,9 +3,9 @@ - 2.2.4-preview.1 + 2.2.5-preview.1 - 2.2.4.0 + 2.2.5.0 diff --git a/Documentation/ReleaseNotes.md b/Documentation/ReleaseNotes.md index 6c148c1..7e0a8dc 100644 --- a/Documentation/ReleaseNotes.md +++ b/Documentation/ReleaseNotes.md @@ -1,5 +1,18 @@ # Release Notes +## Release 2.2.5 + +This release makes the consistency timestamp independent of whether the latest load windows brought new data, and tidies up how `omd.RunModule` reports a Module that is not registered or that failed before. The repository database schema is unchanged, so no migration is needed. + +Changes: + +* Fixed: `omd.GetConsistencyTimestamp` treated every logical source group whose latest load window had changes as still catching up, without looking at the source. Straight after a load that brought data, each source is typically complete up to its own load window end, yet the earliest window end of all sources was returned. Snapshots taken at that moment left out the rows that other sources had loaded moments later; a Point-In-Time table on a Link could even end up empty. The result only became complete after a later cycle without changes. The procedure now checks every logical source group for outstanding rows beyond its load window (when `@SourceDataLookupIndicator` is `Y`, the default), uses the earliest window end of the groups that still lag behind, and the latest window end when none does. With `@SourceDataLookupIndicator = 'N'` the behaviour is unchanged. Covered by new integration tests. +* `omd.RunModule` stops with a clear message when the Module Code is not registered in `omd.MODULE` and cannot be auto-registered (auto-registration is off, or no `@Query` provides the code to run): ''Module Code 'X' is not registered in [omd].[MODULE], so there is nothing to run.'' The same message is written to `omd.EVENT_LOG`, instead of the earlier generic ''Failed to register a module instance''. The debug output no longer names a non-existent `@BModuleCode` parameter. +* Fixed: the rollback in `omd.ModuleEvaluation` compared the bracketed target name (`[N/A]`) with the 'no target' marker `N/A`, so it never matched. A rerun of a failed Module registered without a target data object then ran `DELETE FROM [N/A]` and failed with ''Invalid object name 'N/A''' instead of running the Module again. The rollback now skips Modules without a target data object, so the rerun fails or succeeds on its own code. +* Fixed: auto-registration (`AUTO_REGISTER_MODULES`, on by default) never worked. `omd.RegisterModule` reported a failure for every newly created Module (`@SuccessIndicator` was only set for an existing one), and `omd.CreateModuleInstance` passed no area, which is required. A Module that is auto-registered from `omd.RunModule` with a `@Query` is now created in the maintenance area (`MAINT`) and runs. +* `omd.PrintLog` prints keys of up to 40 characters on one line, so longer keys such as the column name in a debug print are no longer wrapped. +* The framework version is 2.2.5 (`DIRECT_VERSION` in `omd_metadata.FRAMEWORK_METADATA`). + ## Release 2.2.4 This release makes the standard Fabric pipelines close a Batch or Module cleanly when no Module proceeds. The repository database schema is unchanged, so no migration is needed. diff --git a/Releases.Direct_Framework/next/version.json b/Releases.Direct_Framework/next/version.json index 9b1248e..c0ceaac 100644 --- a/Releases.Direct_Framework/next/version.json +++ b/Releases.Direct_Framework/next/version.json @@ -1,5 +1,5 @@ { - "directFrameworkVersion": "2.2.4", + "directFrameworkVersion": "2.2.5", "sqlServerVersion": "2022", "compatibilityMode": "160", "defaultCollation": "SQL_Latin1_General_CP1_CS_AS",