SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRDEX_TEST_DYNAMIC_SQL]
-- =================================================================
-- Central guard for dynamic SQL safety checks
-- 
-- Returns: INTEGER; 0 = ok; 0 <> nicht ok
-- =================================================================
-- Copyright (c) 2025 by Digital Data GmbH
--
-- Digital Data GmbH • Ludwig-Rinn-Strasse 16 • D-35452 Heuchelheim
-- Tel.: 0641/202360 • E-Mail: info-flow@digitaldata.works
-- =================================================================
-- Creation Date / Author:    24.02.2026 / MK
-- Version Date / Editor:     24.02.2026 / MK
-- Version Number:            1.0.0.0
-- =================================================================
-- History:
-- 24.02.2026 / MK - First Version

CREATE OR ALTER PROCEDURE [dbo].[PRDEX_TEST_DYNAMIC_SQL](
	@pQUERY					NVARCHAR(MAX),
	@pRETURN_STATUS			INT,
	@pQUERY_NAME			NVARCHAR(100) = N'@QUERY'
)
AS
BEGIN TRY

	--================================================-- Set session options --===============================================--
	SET NOCOUNT ON;
	----------------------------------------------------------------------------------------------------------------------------

	--=========================================-- declare new vars because of parameter sniffing --===========================--
	DECLARE @QUERY					NVARCHAR(MAX)	= ISNULL(@pQUERY,N''),
			@RETURN_STATUS			INT				= ISNULL(@pRETURN_STATUS,50000),
			@QUERY_NAME				NVARCHAR(100)	= ISNULL(@pQUERY_NAME,N'@QUERY'),
			@HAS_UNRESOLVED_PLACEHOLDER	BIT				= 0,
			@HAS_RESTRICTED_SQL		BIT				= 0,
			@RETURN_ERROR_TEXT		NVARCHAR(MAX)	= N'';
	----------------------------------------------------------------------------------------------------------------------------

	--=========================================-- validate query content --====================================================--
	SET @HAS_UNRESOLVED_PLACEHOLDER = CASE WHEN PATINDEX('%[%][A-Z_][A-Z0-9_][A-Z0-9_][A-Z0-9_][%]%',UPPER(@QUERY)) > 0 THEN 1 ELSE 0 END;
	SET @HAS_RESTRICTED_SQL = CASE WHEN
		(PATINDEX('%;--%',UPPER(@QUERY)) > 0) OR
		(PATINDEX('%XP_CMDSHELL%',UPPER(@QUERY)) > 0) OR
		(PATINDEX('%SP_CONFIGURE%',UPPER(@QUERY)) > 0) OR
		(PATINDEX('%ALTER LOGIN%',UPPER(@QUERY)) > 0) OR
		(PATINDEX('%CREATE LOGIN%',UPPER(@QUERY)) > 0) OR
		(PATINDEX('%DROP DATABASE%',UPPER(@QUERY)) > 0)
	THEN 1 ELSE 0 END;
	----------------------------------------------------------------------------------------------------------------------------

	IF (@HAS_UNRESOLVED_PLACEHOLDER = 1) OR (@HAS_RESTRICTED_SQL = 1) BEGIN
		SET @RETURN_ERROR_TEXT = CONCAT('Blocked unsafe query content in ',@QUERY_NAME,'. Detected unresolved placeholder tokens (%TOKEN%) or restricted statements.');
		THROW @RETURN_STATUS,@RETURN_ERROR_TEXT,1;
	END;

	RETURN 0;

END TRY BEGIN CATCH
	THROW;
END CATCH;
GO