USE [Elyse_DB] GO /****** Object: StoredProcedure [editing].[usp_INS_file_binary_input] Script Date: Sun 22-11-2026 9:04:49 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Silkwood Software -- Create date: 26-06-2023 -- Description: Initial creation /* Inserts files into the filestream container Input is a binary file, filename of the record to be saved, an optional transaction group id, an optional document id, an optional document id autogenerate flag, an optional thumbnail and an optional full text content string. The autogenerate flag instructs the code to automatically generate a document id if none was supplied. @docidautogen must be 'YES' to initiate autogeneration of a document ID. The filename does not have to be the same as the filename of the record to be saved, but it must be a valid filename. Filename is optional. The transaction id is retrieved by the application from a different stored procedure and passed back to this one. For example, a group of files being added at the same time can be grouped by the same transaction id. The optional document id allows a file to be immediately restricted via document view group permissions. Output is a status message, a transaction status and the id of the new record. COPYRIGHT NOTICE This database schema and stored procedures are protected by copyright. Copyright. Silkwood Software Pty. Ltd. 2023 */ -- ============================================= CREATE PROCEDURE [editing].[usp_INS_file_binary_input] -- Add the parameters for the stored procedure here @file_content_bin varbinary(max) = NULL, -- Mandatory @stored_filename nvarchar(255) = NULL, -- Optional @full_text_content nvarchar(max) = NULL, -- Optional @thumbnail varbinary(max) = NULL, -- Optional @transactiongroup bigint = NULL, -- Optional @documentid nvarchar(50) = NULL, -- Optional @docidautogen nvarchar(5) = NULL, -- Optional. Automatically generates a document ID if none supplied. @filegroupid bigint = NULL, -- Optional @docgroupid bigint = NULL, -- Optional @duplicate_check nvarchar(3) = NULL, -- Optional. Checks if a duplicate file exists. @retention_months int = NULL, -- Optional. Number of months of retention. Is converted to the retention date @releaseid bigint = NULL, -- Optional. A release ID linked to a document @notes nvarchar(1000) = '', -- Optional. Notes for the audit log. @app_reference nvarchar(1000) = '', -- Optional. Application reference text @message nvarchar(1000) = NULL OUTPUT, @transaction_status nvarchar(50) = NULL OUTPUT, @fileid bigint = NULL OUTPUT, @newdocumentid nvarchar(50) = NULL OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @next_doc_number bigint = NULL, @file_hash varbinary(32), @temptransmessage nvarchar(300) = '', @filename_validation_status nchar(10), @tempmessage nvarchar(300) = '', @sanitised_text NVARCHAR(MAX) = '', @tempuserauth_status nchar(10) = '', -- Temporary value for authentication sp. @connectedusersid varbinary(100) = SUSER_SID(ORIGINAL_LOGIN()), -- The SID of the connected user @username nvarchar(150) = ORIGINAL_LOGIN(), -- The username @sidid bigint = NULL, @retention_date datetime2(7) = NULL, @release_docid nvarchar(50) = '', -- The document ID associated with the release id. @release_identifier nvarchar(50) = '', -- The release identifier string associated with the release id. @userauthentication_status nchar(10) = 'Fail', -- The outcome of the authentication check of the user @docauthenticationstatus nchar(10) = '', -- Communicates if the user is not authorised to access the document -- or alternatively if the document does not exist. The result does not distinguish either. @maxiterationcount int = NULL, -- Maximum number of attempts to autogenerate a document ID @match_count int = NULL, -- Count of the number of duplicate files. @existing_releaseid bigint = NULL, @release_update_required bit = 0, @release_conflict bit = 0, @docid_generated bit = 0, @fileauthenticationstatus nchar(10) = '', -- Communicates if the user is not authorised to access the file -- or alternatively if the file does not exist. The result does not distinguish either. @filegroupauthstatus nchar(10) = '', -- Status of the authentication status for the connected user for the given file group. @file_doc_change_log_status nchar(3) = 'Off', @transaction_ready nchar(10) = 'Ready', @data_validation_status nchar(10) = 'Pass'; -- Parameters which have been initialised at declaration but not explicitly set might be output as null to calling functions. SET @transaction_status = 'Transaction not attempted'; SET @fileid = NULL; SET @newdocumentid = NULL; SET @message = NULL; SET @maxiterationcount = (SELECT doc_autogen_max_tries FROM base.global_settings_groups AS gsg WHERE gsg.setting_group_name = 'Master'); -- Connected user authentication EXEC [internal].[usp_AUTHENTICATE_user_role] @role_to_check = 'Controller', @user_authentication_result = @tempuserauth_status OUTPUT; IF @tempuserauth_status = 'Pass' SET @userauthentication_status = 'Pass'; EXEC [internal].[usp_AUTHENTICATE_user_role] @role_to_check = 'Editor', @user_authentication_result = @tempuserauth_status OUTPUT; IF @tempuserauth_status = 'Pass' SET @userauthentication_status = 'Pass'; EXEC [internal].[usp_AUTHENTICATE_user_role] @role_to_check = 'Reviewer', @user_authentication_result = @tempuserauth_status OUTPUT; IF @tempuserauth_status = 'Pass' SET @userauthentication_status = 'Pass'; IF @userauthentication_status = 'Fail' BEGIN -- The user does not have permission for this action SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'NoPermission', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', ISNULL(@username, ''), ' ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on NoPermission'); END IF @userauthentication_status = 'Pass' -- Don't do anything if the user is not authorised. BEGIN -- Select the SID ID for the connected user SELECT @sidid = sl.sid_id FROM user_restr.sid_list AS sl WHERE sl.sid = @connectedusersid; SET @file_doc_change_log_status = (SELECT gsg.file_doc_change_log FROM base.global_settings_groups AS gsg WHERE gsg.setting_group_name = 'Master' AND gsg.file_doc_change_log = 'On') -- Data validation -- Stored filename must be a valid filename SET @stored_filename = LTRIM((RTRIM(@stored_filename))) -- A filename can't be all spaces. EXEC internal.usp_VALIDATE_filename @filename_to_validate = @stored_filename, @filename_validation_result = @filename_validation_status OUTPUT; IF @filename_validation_status = 'Invalid' BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'InvalidFilename', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on InvalidFilename.'); END -- End filename validation -- Stored filename length must be less than 255 IF LEN(@stored_filename) > 254 BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'FilenameTooLong', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on FilenameTooLong.'); END -- End filename length validation -- Check that the transaction group exists. NULL is allowed. IF @transactiongroup IS NOT NULL BEGIN IF NOT EXISTS (SELECT transaction_group_id FROM base.transaction_groups WHERE transaction_group_id = @transactiongroup) BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'TGNotExist', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on TGNotExist.'); END END -- End checking transaction group reference -- If thumbnail storage is on then theck the thumbnail IF EXISTS (SELECT gsg.store_thumbnails FROM base.global_settings_groups AS gsg WHERE gsg.setting_group_name = 'Master' AND gsg.store_thumbnails = 'On') BEGIN -- Thumbnail must be smaller than 1MB IF DATALENGTH(@thumbnail) > 1048576 BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'ThumbnailTooBig', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on ThumbnailTooBig.'); END END ELSE SET @thumbnail = NULL; -- If full thumbnail is off then delete any thumbnail supplied. -- End thumbnail size validation -- Document id validation SET @documentid = LTRIM(RTRIM(@documentid)) IF @documentid = '' SET @documentid = NULL; SET @docidautogen = UPPER(@docidautogen); SET @docid_generated = 0; -- Document ID auto-generation (Transaction 1) -- This runs in the validation phase where @transaction_ready is still effective. IF @documentid IS NULL BEGIN IF @docidautogen = 'YES' AND @transaction_ready = 'Ready' BEGIN BEGIN TRANSACTION; WHILE @maxiterationcount > 0 BEGIN SET @maxiterationcount = @maxiterationcount - 1; IF (SELECT doc_id_format FROM base.global_settings_groups WHERE setting_group_name = 'Master') = 'Integer' BEGIN -- Atomic increment inside Transaction 1. -- Rolls back on collision — no permanent gaps from retries. UPDATE gsg SET @next_doc_number = gsg.doc_id_last_integer = ISNULL(gsg.doc_id_last_integer, 0) + 1 FROM base.global_settings_groups AS gsg WHERE gsg.setting_group_name = 'Master'; SET @documentid = CONVERT(NVARCHAR(50), @next_doc_number); END ELSE EXEC internal.usp_SEL_random_doc_id @randomdocumentid = @documentid OUTPUT; -- Apply prefix if configured IF (SELECT is_register_code_applied FROM base.global_settings_groups WHERE setting_group_name = 'Master') = 'Yes' SET @documentid = (SELECT register_code FROM base.global_settings_groups WHERE setting_group_name = 'Master') + '-' + @documentid; -- Attempt immediate insert. -- Uniqueness enforced by PK/unique constraint. BEGIN TRY INSERT INTO base.document_id_list (doc_id, transaction_group_id) VALUES (@documentid, @transactiongroup); -- Success SET @docid_generated = 1; SET @newdocumentid = @documentid; -- Write audit log inside Transaction 1 IF @file_doc_change_log_status = 'On' BEGIN INSERT INTO base.file_doc_data_log (created_by_username, created_by_sid_id, change_type, change_field, file_id, doc_id, record_id, record_name, original_value, new_value, notes, app_reference) VALUES (@username, @sidid, 'Insert', 'Document ID', NULL, @newdocumentid, NULL, NULL, NULL, NULL, @notes, @app_reference); END BREAK; -- Exit the WHILE loop END TRY BEGIN CATCH IF ERROR_NUMBER() IN (2601, 2627) BEGIN -- Duplicate key collision — retry with next candidate SET @documentid = NULL; CONTINUE; END ELSE BEGIN -- Unexpected error — capture details, roll back, and stop SET @documentid = NULL; SET @newdocumentid = NULL; SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; -- Capture error details before ROLLBACK clears them SET @tempmessage = CONCAT_WS(' | ', CONVERT(nvarchar(10), ERROR_NUMBER()), 'Procedure', ERROR_PROCEDURE(), 'Line', CONVERT(nvarchar(10), ERROR_LINE()), ERROR_MESSAGE()); IF XACT_STATE() <> 0 ROLLBACK TRANSACTION; SET @message = CONCAT_WS(' | ', @message, @tempmessage); BREAK; -- Exit the WHILE loop END END CATCH END -- WHILE -- After the WHILE loop: commit, roll back, or already handled IF @docid_generated = 1 AND XACT_STATE() = 1 BEGIN COMMIT TRANSACTION; -- Transaction 1 committed END ELSE IF @docid_generated = 0 AND XACT_STATE() = 1 BEGIN -- Exhausted all retries — roll back counter increments ROLLBACK TRANSACTION; SET @documentid = NULL; SET @newdocumentid = NULL; SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'MaxDocTries', @message_text = @tempmessage OUTPUT; SET @message = CONCAT_WS(' | ', @message, ISNULL(@tempmessage, 'A database level message error occurred on MaxDocTries.')); END -- ELSE: XACT_STATE() = 0 means the unexpected-error path -- already rolled back and set @transaction_ready = 'Fail'. END -- IF @docidautogen = 'YES' END -- IF @documentid IS NULL ELSE -- Supplied @documentid is not NULL BEGIN -- Check if the document ID exists and the user has edit permission for the document EXEC [internal].[usp_AUTHENTICATE_doc_ed_perm] @doc_id_to_check_ep = @documentid, @user_authentication_result_dep = @docauthenticationstatus OUTPUT; IF @docauthenticationstatus = 'Fail' BEGIN -- Doc id does not exist or the user does not have permission to access it SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'DocIDNotExist', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT(@message, ' | ', 'Document ID: ', LEFT(@documentid, 20), '... ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DocIDNotExist.'); END END -- End document id validation /* Using OPENROWSET(BULK... is an unsuitable approach in this context because it requires BULK ADMIN privileges, which introduces security issues. Hence the approach used is that the application must open the file and place it into an object which is passed to the stored procedure. */ -- File length validation -- varbinary(max) as a maximum storage of 2 GB" Test at one less than maximum. IF DATALENGTH(@file_content_bin) > 2147483647 BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'FileTooLarge', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on FileTooLarge.'); END -- End file length validation -- Don't load empty or null files. IF (DATALENGTH(@file_content_bin) = 0) OR (@file_content_bin IS NULL) BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'NoFileSupplied', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on NoFileSupplied.'); END -- End empty file validation -- Check the file group id IF @filegroupid = 0 SET @filegroupid = NULL; IF @filegroupid IS NOT NULL -- A file group id was supplied. Check that file group id exists BEGIN -- Check the file group id IF NOT EXISTS (SELECT file_group_id FROM xref.file_group_names WHERE file_group_id = @filegroupid) BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'FileGroupIdNotExist', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT(@message, ' | ', 'File Group ID: ', ISNULL(CONVERT(nvarchar(10), @filegroupid), 'NULL'), '. ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on FileGroupIdNotExist'); END ELSE -- The file group ID does exist. Check that the user has edit permission for the file group BEGIN EXEC [internal].[usp_AUTHENTICATE_fl_grp_ed_pm] @filegroupid_tocheck = @filegroupid, @user_authentication_reslt_fgep = @filegroupauthstatus OUTPUT; IF @filegroupauthstatus = 'Fail' BEGIN -- The user does not have edit permission for the file group SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'NoFileGrpEdPerm', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT(@message, ' | ', 'File Group ID: ', CONVERT(nvarchar(20), @filegroupid), '. ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on NoFileGrpEdPerm'); END END -- End checking if the user has edit permission for the file group. END -- End checking the file group id. -- Check document group id IF @docgroupid = 0 SET @docgroupid = NULL; IF @docgroupid IS NOT NULL BEGIN -- Authenticate the user for the given document group -- This also returns fail if the id does not exist EXEC [internal].[usp_AUTHENTICATE_user_doc_grp] @docgroupid_to_check_vp = @docgroupid, @user_authentication_result = @tempuserauth_status OUTPUT; IF @tempuserauth_status = 'Fail' BEGIN -- The user does not have permission for this action SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'NoDocGroupPermission', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', 'Document group ID: ', ISNULL(CONVERT(nvarchar(10), @docgroupid), 'NULL'), ' ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on NoDocGroupPermission.'); END END -- END if @docgroupid IS NOT NULL IF @docgroupid IS NOT NULL AND @documentid IS NULL AND @docid_generated = 0 AND ISNULL(@docidautogen, '') <> 'YES' BEGIN -- If a doc group ID has been supplied then an associated document ID must also be supplied. SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'NoDocForGroup', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', 'Document group ID: ', ISNULL(CONVERT(nvarchar(10), @docgroupid), 'NULL'), ' ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on NoDocForGroup.'); END -- END if @docgroupid IS NOT NULL -- Determine if duplicate check is required -- Carry out duplicate check. IF @duplicate_check IS NULL OR @duplicate_check = '' BEGIN SET @duplicate_check = (SELECT duplicate_management FROM base.global_settings_groups WHERE setting_group_name = 'Master') END IF UPPER(@duplicate_check) <> 'ON' SET @match_count = 0; SET @file_hash = HASHBYTES('SHA2_256', @file_content_bin); IF UPPER(@duplicate_check) = 'ON' BEGIN -- Check if a duplicate file exists. -- Count the number of matches of duplicate files SELECT @match_count = COUNT(*) FROM base.file_metadata WHERE content_hash = @file_hash; -- Fail if there is more than one match. IF (@match_count > 1 AND @documentid IS NOT NULL) -- Message mentions unable to link to doc id. BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'MultiDuplFiles', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on MultiDuplFiles.'); END -- Fail if there is more than 0 matches and a document ID has not been supplied. IF (@match_count > 0 AND @documentid IS NULL) -- Message does not mention unable to link to doc ID. BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'DuplicateFile', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DuplicateFile.'); END -- If there is exactly one match AND a document ID has been supplied then extract the file_id to @fileid. IF (@match_count = 1 AND @documentid IS NOT NULL) BEGIN SELECT @fileid = file_id, @existing_releaseid = release_id_pk FROM base.file_metadata WHERE content_hash = @file_hash; EXEC internal.usp_SEL_message @message_id = 'DuplicateFile', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DuplicateFile.'); -- Determine what to do with an incoming release ID. IF @releaseid IS NOT NULL BEGIN -- Existing duplicate has no release: assign the incoming release. IF @existing_releaseid IS NULL BEGIN SET @release_update_required = 1; END -- Existing duplicate already has a different release: -- do not change the existing release. ELSE IF @existing_releaseid <> @releaseid BEGIN SET @release_conflict = 1; END END END -- If there is a single matching file, then check if the user has edit rights to it. IF @match_count = 1 BEGIN -- Check if the the user has permission to access the duplicate file EXEC [internal].[usp_AUTHENTICATE_file_ed_perm] @file_id_to_check_ep = @fileid, @user_authentication_result_fep = @fileauthenticationstatus OUTPUT; IF @fileauthenticationstatus = 'Fail' BEGIN -- File id does not exist or the user does not have permission to access it SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'DuplFileNoAccess', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT(@message, ' | ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DuplFileNoAccess.'); END END END -- END IF UPPER(@duplicate_check) = 'ON' -- If full text storage is on then sanitise the string IF EXISTS (SELECT gsg.store_plain_text_content FROM base.global_settings_groups AS gsg WHERE gsg.setting_group_name = 'Master' AND gsg.store_plain_text_content = 'On') BEGIN -- Sanitise the full text content string and truncate to 1 million characters. SET @sanitised_text = internal.ufn_CHK_sanitise_file_text_SVF(@full_text_content); END ELSE SET @sanitised_text = NULL; -- If full text indexing is off then ignore any full text content supplied. -- Validate the retention period IF @retention_months < 0 OR @retention_months > 9999 BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'InvalidRetention', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage, ' ', @retention_months); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on InvalidRetention.'); END -- Check the release ID IF @releaseid = 0 SET @releaseid = NULL; IF @releaseid IS NOT NULL BEGIN IF NOT EXISTS (SELECT release_id_pk FROM base.release_identifiers WHERE release_id_pk = @releaseid) BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'ReleaseIDNotExist', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on ReleaseIDNotExist.'); END ELSE -- Release ID exists. BEGIN -- Check that the user has edit permission for the associated document ID. SET @release_docid = (SELECT doc_id FROM base.release_identifiers WHERE release_id_pk = @releaseid) EXEC [internal].[usp_AUTHENTICATE_doc_ed_perm] @doc_id_to_check_ep = @release_docid, @user_authentication_result_dep = @docauthenticationstatus OUTPUT; IF @docauthenticationstatus = 'Fail' BEGIN -- Doc id does not exist or the user does not have permission to edit it SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'ReleaseIDNotExist', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on ReleaseIDNotExist.'); END ELSE BEGIN -- User has permission for the document id associated with the release -- Check that the document ID associated with the release matches the linked document id, if a document id has been supplied. IF @release_docid <> @documentid AND @documentid IS NOT NULL AND @documentid <> '' BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'RelDocIDNoMatch', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on RelDocIDNoMatch.'); END ELSE BEGIN -- Check if the release is Authoritative or Historical IF EXISTS (SELECT release_state_type_id FROM base.release_identifiers AS ri WHERE ri.release_id_pk = @releaseid AND (ri.release_state_type_id = 'Authoritative' OR ri.release_state_type_id = 'Historical')) BEGIN SET @data_validation_status = 'Fail'; SET @transaction_ready = 'Fail'; EXEC internal.usp_SEL_message @message_id = 'RelIdChgNotPermitted', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on RelIdChgNotPermitted.'); END END END -- END User has permission for the document id associated with the release END -- End ELSE Release ID Exists END IF @data_validation_status = 'Fail' BEGIN EXEC internal.usp_SEL_message @message_id = 'FailedDataValidation', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on FailedDataValidation.'); END -- End data validation END -- End IF user authentication = Pass -- Execute the insert query IF @transaction_ready = 'Ready' BEGIN BEGIN TRY BEGIN TRANSACTION; -- Transaction 2 -- Calculate retention date IF @retention_months IS NOT NULL SET @retention_date = CAST(DATEADD(MONTH, @retention_months, SYSDATETIME()) AS DATE); -- Noting that docid is not case sensitive, the code should store the docid -- with the same letter case as is stored rather than what was supplied. IF @documentid IS NOT NULL SET @documentid = (SELECT doc_id FROM base.document_id_list AS dil WHERE dil.doc_id = @documentid); IF UPPER(@duplicate_check) = 'ON' BEGIN -- UPDLOCK prevents the classic shared-lock deadlock that occurs -- when multiple parallel file-upload sessions each acquire a -- shared HOLDLOCK and then try to escalate to exclusive for INSERT. -- UPDLOCK ensures only one session at a time holds the lock on -- the hash range, while still allowing plain SELECT readers through. SELECT @match_count = COUNT(*) FROM base.file_metadata WITH (UPDLOCK, HOLDLOCK) WHERE content_hash = @file_hash; -- Re-fetch @fileid inside the transaction when a single duplicate exists IF @match_count = 1 BEGIN SELECT @fileid = file_id, @existing_releaseid = release_id_pk FROM base.file_metadata WITH (HOLDLOCK) WHERE content_hash = @file_hash; END ELSE BEGIN SET @fileid = NULL; SET @existing_releaseid = NULL; END END -- Detect race condition: validation phase saw no duplicates, -- but another session inserted one before Transaction 2 started. IF @match_count > 0 AND @fileid IS NULL BEGIN -- A duplicate appeared since validation passed. -- Cannot proceed — roll back and report. ROLLBACK TRANSACTION; EXEC internal.usp_SEL_message @message_id = 'DuplicateFile', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DuplicateFile.'); SET @transaction_status = 'Bad'; END ELSE BEGIN -- Load the file if duplicate checking is not on, or if there are no duplicates. IF (UPPER(@duplicate_check) <> 'ON' OR @match_count = 0) BEGIN EXEC internal.usp_INS_file @f_ins_file_content = @file_content_bin, @f_ins_stored_filename = @stored_filename, @f_ins_transaction_group = @transactiongroup, @f_ins_created_by_id = @sidid, @f_ins_plain_text_content = @sanitised_text, @f_ins_thumbnail = @thumbnail, @f_ins_retention_date = @retention_date, @f_ins_message = @message OUTPUT, @f_ins_transaction_status = @transaction_status OUTPUT, @f_ins_file_id = @fileid OUTPUT; -- If the inner procedure reported failure, abort Transaction 2. -- The inner proc now uses a savepoint so the outer transaction -- is still open; we must roll it back ourselves. IF @transaction_status = 'Bad' OR @fileid IS NULL BEGIN IF XACT_STATE() <> 0 ROLLBACK TRANSACTION; -- Transfer control to the outer CATCH block. ;THROW 50000, 'Internal file insert failed.', 1; END END -- If a release ID has been supplied then insert it IF @releaseid IS NOT NULL AND @fileid IS NOT NULL BEGIN -- Create the file to document link for the document related to the release ID BEGIN TRY IF @release_conflict = 0 BEGIN INSERT INTO xref.file_to_document_links (doc_id, file_id) VALUES (@release_docid, @fileid); END IF @release_update_required = 1 BEGIN UPDATE base.file_metadata SET release_id_pk = @releaseid WHERE file_id = @fileid AND release_id_pk IS NULL; END -- Create an audit log entry -- Select the SID ID for the connected user SELECT @release_identifier = ri.release_identifier FROM base.release_identifiers AS ri WHERE ri.release_id_pk = @releaseid; -- Write to the log IF @release_update_required = 1 AND @fileid IS NOT NULL BEGIN SELECT @release_identifier = ri.release_identifier FROM base.release_identifiers AS ri WHERE ri.release_id_pk = @releaseid; IF @file_doc_change_log_status = 'On' BEGIN INSERT INTO base.file_doc_data_log (created_by_username, created_by_sid_id, change_type, change_field, file_id, doc_id, record_id, record_name, original_value, new_value, notes, app_reference) VALUES (@username, @sidid, 'Insert', 'File-Doc Release', @fileid, @release_docid, @releaseid, @release_docid, NULL, @release_identifier, @notes, @app_reference) END END IF @release_conflict = 1 BEGIN EXEC internal.usp_SEL_message @message_id = 'ReleaseConflict', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage, CONVERT(nvarchar(20), @existing_releaseid)); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on ReleaseConflict.'); END END TRY BEGIN CATCH IF ERROR_NUMBER() NOT IN (2601, 2627) THROW; -- else: extremely rare collision ? ignore END CATCH END -- Insert the file to document ID link if it does not already exist. IF @documentid IS NOT NULL AND @fileid IS NOT NULL BEGIN BEGIN TRY INSERT INTO xref.file_to_document_links (doc_id, file_id, transaction_group_id) VALUES (@documentid, @fileid, @transactiongroup); END TRY BEGIN CATCH IF ERROR_NUMBER() NOT IN (2601, 2627) THROW; -- else: duplicate link ? ignore END CATCH END --Insert the file to file group link if it does not already exist IF @filegroupid IS NOT NULL AND @fileid IS NOT NULL BEGIN BEGIN TRY INSERT INTO xref.file_group_links (file_group_id, file_id) VALUES (@filegroupid, @fileid); END TRY BEGIN CATCH IF ERROR_NUMBER() NOT IN (2601, 2627) THROW; -- else: duplicate link ? ignore END CATCH END -- END inserting file group id link -- Insert the document to document group link if it does not already exist IF @docgroupid IS NOT NULL AND @documentid IS NOT NULL BEGIN BEGIN TRY INSERT INTO xref.doc_group_links (doc_id, doc_group_id) VALUES (@documentid, @docgroupid); END TRY BEGIN CATCH IF ERROR_NUMBER() NOT IN (2601, 2627) THROW; -- else: duplicate link already exists ? ignore END CATCH END COMMIT TRANSACTION; EXEC internal.usp_SEL_message @message_id = 'Success', @message_text = @tempmessage OUTPUT; IF @tempmessage IS NOT NULL SET @message = CONCAT_WS(' | ', @message, @tempmessage); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on Success.'); SET @transaction_status = 'Good'; END -- END IF @match_count > 0 AND @fileid IS NULL > ELSE (No race-condition duplicate) END TRY BEGIN CATCH IF XACT_STATE() <> 0 ROLLBACK TRANSACTION; -- Roll back Transaction 2 SET @fileid = NULL; -- The file insert will be rolled back. SET @transaction_status = 'Bad'; EXEC internal.usp_SEL_message @message_id = 'InsertError', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage, ' | ', CONVERT(nvarchar(10),ERROR_NUMBER()), ' | Procedure ', ERROR_PROCEDURE(), ' | Line ', CONVERT(nvarchar(10), ERROR_LINE()), ' | ', ERROR_MESSAGE()); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on InsertError.'); -- Transaction 3: Clean up the orphaned auto-generated doc-ID IF @newdocumentid IS NOT NULL BEGIN BEGIN TRY BEGIN TRANSACTION; DELETE FROM base.document_id_list WHERE doc_id = @newdocumentid; -- Write an audit log entry for the reversal IF @file_doc_change_log_status = 'On' BEGIN INSERT INTO base.file_doc_data_log (created_by_username, created_by_sid_id, change_type, change_field, file_id, doc_id, record_id, record_name, original_value, new_value, notes, app_reference) VALUES (@username, @sidid, 'Delete', 'Document ID', NULL, @newdocumentid, NULL, NULL, @newdocumentid, NULL, 'Auto-generated document ID removed: file insert (Transaction 2) failed.', @app_reference); END COMMIT TRANSACTION; -- Transaction 3 committed SET @newdocumentid = NULL; -- Cleaned up successfully END TRY BEGIN CATCH -- Transaction 3 failed — orphaned doc-ID remains. -- Log a warning but do not mask the original error. IF XACT_STATE() <> 0 ROLLBACK TRANSACTION; EXEC internal.usp_SEL_message @message_id = 'DocIdAutoGenFail', @message_text = @tempmessage OUTPUT; IF (@tempmessage IS NOT NULL) SET @message = CONCAT(@message, ' | ', @tempmessage, ' | Document ID ', @newdocumentid, CONVERT(nvarchar(10),ERROR_NUMBER()), ' | Procedure ', ERROR_PROCEDURE(), ' | Line ', CONVERT(nvarchar(10), ERROR_LINE()), ' | ', ERROR_MESSAGE()); ELSE SET @message = CONCAT_WS(' | ', @message, 'A database level message error occurred on DocIdAutoGenFail.'); END CATCH END -- END IF @newdocumentid IS NOT NULL END CATCH END END GO