﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[fds__getUpdateableTables]
(
)
RETURNS @RET TABLE 
(
	[entity_name] varchar(255)
	,[table_name] varchar(255)
	,[proc_name] varchar(255)
	,[locked] bit
	,[locked_reset] bit
	,[updateneed] tinyint
	,[datebased] bit
)
AS
BEGIN
	DECLARE @threshold_minutes_full int = 60, @threshold_minutes_short int = 8;
	
	DECLARE @utcnow datetime = GETUTCDATE();
	DECLARE @UTCTimeInMinutes int = DATEDIFF(MINUTE, CAST(CAST(@utcnow as date) as datetime), @utcnow);

	DECLARe @AS XML = [dbo].[mfr__schema]();

	DECLARE @EntityTypes TABLE([#] int, [typ] varchar(50), [name] varchar(255), [set] varchar(255), [EntitySet] varchar(255), [tablename] varchar(255), [url] varchar(500), [DateColumn] varchar(25));		
		WITH XMLNAMESPACES 
		(  
			'http://schemas.microsoft.com/ado/2007/06/edmx' as edmx,
			'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' as m
		), et as (
			SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#'
					, xD.value('local-name(.)', 'varchar(50)') as [type]
					, xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' 
					, xS.value('@Name', 'varchar(255)') as [Set]
					, o.[name] as [tablename]
				from @as.nodes('/Schema[1]/EntityType') as xm(xD)
					JOIN @as.nodes('/Schema/EntityContainer/EntitySet') as xn(xS) ON (xS.value('@EntityType', 'varchar(255)')) like ('MFR.%[.]' + (xD.value('@Name', 'varchar(255)')))
					JOIN sys.objects as o ON o.[name] like ('mfr__' + (LOWER(xS.value('@Name', 'varchar(255)'))))
			union
			SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as '#'
					, xD.value('local-name(.)', 'varchar(50)') as [type]
					, xD.value('@Name', 'varchar(255)') as [EntityType] --, xD.query('.') as 'q' 
					, '' as [Set]
					, o.[name] as [tablename]
				from @as.nodes('/Schema[1]/ComplexType') as xm(xD)
					JOIN sys.objects as o ON o.[name] like ('mfr__[#]' + (LOWER(xD.value('@Name', 'varchar(255)'))) + 's')
		)
		INSERT INTO @EntityTypes  SELECT [#],[type],[EntityType],[set] = LOWER([set]), [EntitySet] = [set], [tablename], null, null FROM et;

	WITH tbl as(
		SELECT
			  --QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.[name]) AS [TABLE_NAME]
			  sOBJ.[name] AS [TABLE_NAME]
			  , SUM(sPTN.Rows) AS [RowCount]
			  ,sOBJ.[create_date]
		FROM 
			  sys.objects AS sOBJ
			  INNER JOIN sys.partitions AS sPTN
					ON sOBJ.object_id = sPTN.object_id
						AND sOBJ.[name] like 'mfr__%'
		WHERE
			  sOBJ.[type] = 'U'
			  AND sOBJ.is_ms_shipped = 0x0
			  AND index_id < 2 -- 0:Heap, 1:Clustered
		GROUP BY 
			  sOBJ.schema_id
			  , sOBJ.name
			  , sObj.[create_date]
	), pro as (SELECT *
		FROM   sys.procedures WHERE LEFT([name], 11) = 'mfr__updt__')
	, lu as (SELECT [table], MAX([timestamp]) as 'lu' FROM [dbo].[fds__status] WHERE [action] like 'update%' group by [table])
	, luf as (SELECT [table], MAX([timestamp]) as 'luf' FROM [dbo].[fds__status] WHERE [action] like 'update_full' group by [table])
	, lur as (SELECT [table], MAX([timestamp]) as 'lur' FROM [dbo].[fds__status] WHERE [action] like 'update_reset' group by [table])
	, luc as (SELECT lu.[table], [lu], [luf], [lur]
					, DATEDIFF(MINUTE, [lu], @utcnow) as [dlu]
					, DATEDIFF(MINUTE, [lur], @utcnow) as [dlr]
					, DATEDIFF(MINUTE, [luf], @utcnow) as [dluf]
					, CASE --WHEN [dbo].[ctm__getUpdateLockStatus] () = Cast(1 as bit) THEN 0
								WHEN [lu] is null then 5
								--WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_full 
								--	OR DATEDIFF(MINUTE, [luf], @utcnow) > @threshold_minutes_full 
								--	THEN 2 
								WHEN DATEDIFF(MINUTE, [lu], @utcnow) > @threshold_minutes_short THEN 1
								ELSE 0
							END as 'need'
			 from lu LEFT JOIN luf on lu.[table] = luf.[table] LEFT JOIN lur on lu.[table] = lur.[table]
	), cols as (SELECT DISTINCT [TABLE_NAME] FROM INFORMATION_SCHEMA.COLUMNS 
					WHERE LEFT(TABLE_NAME, 5) = N'mfr__' AND ([column_name] COLLATE Latin1_General_CI_AS in ('DateModified', 'DateCreated', 'DateOfCreation')))
	INSERT INTO @RET
		SELECT DISTINCT [entity_name] = et.[name]
				, 'table_name' = tbl.[table_name]
				, 'temp_table' = pro.[name]
				, 'locked' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0)
				, 'locked_reset' = 0 --ISNULL([dbo].[ctm__getUpdateLockStatus_reset_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')), 0)
				, 'updateneed' = CASE 
									--WHEN [dbo].[ctm__getUpdateLockStatus_tbl](REPLACE(tbl.[TABLE_NAME], 'mfr__', '')) = Cast(1 as bit) THEN 0
									WHEN et.[name] COLLATE Latin1_General_CI_AS  IN ('Attachment','Comment','Item','StepListTemplateInstance','Step') THEN 0
									WHEN tbl.[RowCount] = 0 THEN 5
									WHEN NOT EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 0
									WHEN luc.need is null then 5
									WHEN tbl.[TABLE_NAME] COLLATE Latin1_General_CI_AS in ('') AND ISNULL(luc.[dlr], 1440) >= 720 AND @UTCTimeInMinutes BETWEEN 45 AND 90 THEN 5  -- once every day, between 02:45 and 03:30 in the morning
									ELSE luc.[need]--ISNULL(luc.[need], 0)
								END
				, 'datebased' = CASE WHEN EXISTS (SELECT * FROM cols WHERE tbl.[TABLE_NAME] = cols.[TABLE_NAME]) THEN 1 ELSE 0 END
			FROM tbl
				JOIN @EntityTypes as et on tbl.[TABLE_NAME] = et.[tablename] 
				JOIN pro on REPLACE(pro.[name], 'mfr__updt__', 'mfr__') = tbl.[TABLE_NAME]
				LEFT JOIN luc on tbl.[table_name] = luc.[table];
	
	RETURN 
END