USE [Elyse_DB] GO /****** Object: UserDefinedFunction [internal].[ufn_SEL_files_by_doc_TVF] Script Date: Sun 22-11-2026 9:04:48 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Silkwood Software -- Create date: 14-06-2024 -- Description: Retrieves the file ids of a document for a given filter group. /* The logic works as follows. Files are listed which: - the user has viewing rights to, - are linked to the document id via the table xref.file_to_document_links Same as internal.ufn_SEL_file_by_doc_fgroup_TVF but without the filter group check. */ /* COPYRIGHT NOTICE This database schema and contained code, including this function are protected by copyright. Copyright. Silkwood Software Pty. Ltd. 2024 */ -- ============================================= CREATE FUNCTION [internal].[ufn_SEL_files_by_doc_TVF] ( @documentid nvarchar(50) ) RETURNS @FileID TABLE ( file_id bigint ) AS BEGIN DECLARE @connectedusersid varbinary(100) = SUSER_SID(ORIGINAL_LOGIN()), -- The SID of the connected user @username nvarchar(150) = ORIGINAL_LOGIN(), -- The username @now datetime2(7) = SYSDATETIME(); -- Create a CTE containing files linked to the given document ID -- and which the user has permission to view. WITH DocFiles AS ( SELECT DISTINCT fm.file_id AS fi FROM base.file_metadata AS fm FULL JOIN xref.file_to_document_links AS ftdl ON fm.file_id = ftdl.file_id FULL JOIN xref.doc_group_links AS dgl ON ftdl.doc_id = dgl.doc_id FULL JOIN xref.doc_group_names AS dgn ON dgl.doc_group_id = dgn.doc_group_id FULL JOIN user_restr.doc_group_view_permissions AS dgvp ON dgn.doc_group_id = dgvp.doc_group_id FULL JOIN user_restr.sid_list AS sl ON dgvp.sid_id = sl.sid_id WHERE ftdl.doc_id = @documentid AND fm.file_id IS NOT NULL AND ( -- No users are linked to any document group: -- therefore the file is unrestricted. NOT EXISTS ( SELECT dgl2.doc_group_id FROM xref.doc_group_links AS dgl2 INNER JOIN user_restr.doc_group_view_permissions AS dgvp2 ON dgl2.doc_group_id = dgvp2.doc_group_id WHERE dgl2.doc_id = ftdl.doc_id ) OR -- Only retrieve file data for files which the user has permission to access. -- The user's permission must also be currently valid. ( EXISTS ( SELECT dgl2.doc_group_id FROM xref.doc_group_links AS dgl2 INNER JOIN user_restr.doc_group_view_permissions AS dgvp2 ON dgl2.doc_group_id = dgvp2.doc_group_id INNER JOIN user_restr.sid_list AS sl2 ON dgvp2.sid_id = sl2.sid_id WHERE dgl2.doc_id = ftdl.doc_id AND sl2.sid = @connectedusersid -- Permission is active from valid_from onwards. AND ( dgvp2.valid_from IS NULL OR dgvp2.valid_from <= @now ) -- Permission remains active until valid_until. AND ( dgvp2.valid_until IS NULL OR dgvp2.valid_until >= @now ) ) ) ) ) -- Add the final results to the return table INSERT INTO @FileID (file_id) SELECT df.fi FROM DocFiles df; RETURN; END; GO