PRINT N'Creating [dbo].[WmiServer.BackupProxiesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupProxiesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupProxiesView]
GO
	CREATE VIEW  [dbo].[WmiServer.BackupProxiesView]
	AS
		SELECT 
			p.*,
            [dbo].[fn.IsHostUpgradeRequired](p.[host_id]) AS [component_is_out_of_date],
			c.[version] as component_version,
			(
				SELECT 
					COUNT(*) 
				FROM 
					[dbo].[Backup.Model.ResourceUsages] u 
				WHERE 
					p.[id] = u.[resource_id] AND 
					u.[resource_type] = 2								-- u.[resource_type] = ResourceTypes.Proxy
			) as curr_usage,
			dbo.MaxValue4(p.usn, h.usn, c.usn, ph.usn) as real_usn,
			CASE WHEN p.[type] = 0 THEN ISNULL(p.options.value('(/ViProxyOptions/IsAutoDetectDisks)[1]', 'bit'), 0)
			ELSE ISNULL(p.options.value('(/HvProxyOptions/IsAutoDetectVolumes)[1]', 'bit'), 0) 
			END as auto_detect_disks,
			CAST((
				CASE WHEN p.[type] = 0 THEN
				(
					SELECT ISNULL(t.data, '<Datastores/>')
					FROM
					(
						SELECT phd.datastore_name as name
						FROM 
							[dbo].[PhysHost_Disk] phd
						WHERE 
							phd.[physhost_id] = c.[physical_host_id] AND
							phd.[is_manual_added] = 1
						FOR XML RAW ('Datastore'), ROOT ('Datastores')
					) AS t(data)
				)
				WHEN p.[type] = 1 OR p.[type] = 2 THEN 
				(
					SELECT ISNULL(t.data, '<Datastores/>')
					FROM
					(
						SELECT phd.mount_point as name
						FROM 
							[dbo].[PhysHost_Volume] phd
						WHERE 
							phd.[physhost_id] = c.[physical_host_id] AND
							phd.[add_type] = 1
						FOR XML RAW ('Datastore'), ROOT ('Datastores')
					) AS t(data)
				)
				ELSE NULL
				END
				) as XML) as connected_datastores,
			ph.chassis_type
		FROM
			[dbo].[BackupProxies] p,
			[dbo].[Hosts] h,
			[dbo].[HostComponents] c,
			[dbo].[PhysicalHosts] ph
		WHERE
			c.[physical_host_id] = h.[physical_host_id] AND
			c.[type] = 0 AND											-- c.[type] = EComponentType.Transport
			h.[id] = p.[host_id] AND
			h.[physical_host_id] = ph.[id] AND
			p.[type] IN (0, 1, 2, 3)	
GO

--------------------------------------------------------------------------------
PRINT N'Creating [dbo].[WmiServer.BackupRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.BackupRepositoriesView]
	AS	
		SELECT 
			r.id as repo_id,
			r.name as repo_name,
			r.total_space,
			r.free_space,
			r.type as repo_type,
			r.options as repo_options,
			r.path as path,
			CASE 
				WHEN r.type = 4 THEN cr.is_available
				ELSE ~r.is_unavailable 
			END as is_repo_available,
			(SELECT [dbo].[fn.IsHostUpgradeRequired](r.[host_id])
                  | [dbo].[fn.IsHostUpgradeRequired](r.[mount_host_id])
            ) AS [component_is_out_of_date],
			c.[version] as component_version,
			(
				SELECT 
					COUNT(*) 
				FROM 
					[dbo].[Backup.Model.ResourceUsages] u 
				WHERE 
					r.[id] = u.[resource_id] AND 
					u.[resource_type] = 1								-- u.[resource_type] = ResourceTypes.Repository
			) as curr_usage,
			ISNULL(c.[type], -1) as comp_type,
			r.[host_id],			
			nfsComponent.[id] as nfs_component_id,
			cr.[cloud_repository_id],
			[status],
			location.[location_id],
			CAST(ISNULL(wr.[is_refs_synthetic_enabled], 0) as BIT) as is_refs_synthetic_enabled,
			CAST(ISNULL(wr.[is_refs_synthetic_available], 0) as BIT) as is_refs_synthetic_available,
			CAST(ISNULL(cifs.[is_virtual_synthetic_enabled], 0) as BIT) as is_virtual_synthetic_enabled,
			CAST(ISNULL(cifs.[is_virtual_synthetic_available], 0) as BIT) as is_virtual_synthetic_available,			
			[dbo].[MaxValue3](
				r.usn, 
				location.usn,
				(SELECT max(c1.usn) FROM [dbo].[HostComponents] c1 JOIN [dbo].[Hosts] h1 ON c1.[physical_host_id] = h1.[physical_host_id] WHERE h1.[id] IN (r.[host_id], r.[mount_host_id]))
			) as usn
		FROM
			[dbo].[BackupRepositories] r 
			LEFT JOIN [dbo].[Hosts] h ON r.[host_id] = h.[id]
			LEFT JOIN [dbo].[HostComponents] c ON h.[physical_host_id] = c.[physical_host_id]
			LEFT JOIN [dbo].[HostComponents] nfsComponent ON h.[physical_host_id] = nfsComponent.[physical_host_id] AND nfsComponent.[type] = 1
			LEFT JOIN [dbo].[Backup.Model.CloudRepositories] cr ON cr.repository_id = r.id
			LEFT JOIN [dbo].[EntityLocations] location ON r.id = location.[entity_id] AND location.[entity_type] = 4
			LEFT JOIN [dbo].[Backup.Model.WindowsRepositories] wr ON wr.[repository_id] = r.[id]
			LEFT JOIN [dbo].[Backup.Model.CifsRepositories] cifs ON cifs.[repository_id] = r.[id]
		WHERE ISNULL(c.[type], -1) IN (-1, 0) -- c.[type] = EComponentType.Transport
		AND r.[type] IN (0, 1, 2, 3, 4, 6, 9, 10, 18)
GO



--------------------------------------------------------------------------------
-- [GetJobsWmiInfo]
PRINT N'Creating [dbo].[WmiServer.JobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.JobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.JobsView]
GO
	CREATE VIEW [dbo].[WmiServer.JobsView]
	AS
		SELECT
			jobs.[id],
			jobs.[name],
			jobs.[type],
			jobs.[latest_result],
			jobs.[job_source_type],
			CASE jobs.[type]
				WHEN 51 THEN ISNULL(jobs.[options].value('(/JobOptionsRoot/GenerationPolicy/SimpleRetentionRestorePoints)[1]', 'int'), 0)
				ELSE ISNULL(jobs.[options].value('(/JobOptionsRoot/RetainCycles)[1]', 'int'), 0)
			END as retain_cycles,
			jobs.schedule_enabled, 
			jobs.schedule AS schedule_options, 
			ISNULL(jobs.options.value('(/*/RunManually)[1]', 'bit'), 1) AS run_manually,
			jobs.options,
			jobs.[usn],
			jobs.[parent_schedule_id],
			jobs.[platform],
			jobs.[vss_options],
			jobs.[modified_by],
			jobs.[created_by],
			jobs.[creation_date],
			jobs.[repository_id],
			file_to_tape_job.options as file_to_tape_options,
			parent_schedule_job.[name] as previous_job_name
		FROM [dbo].[BJobs] jobs	
		LEFT JOIN [dbo].[Tape.jobs] AS file_to_tape_job ON jobs.id = file_to_tape_job.id AND jobs.[type] = 24
		LEFT JOIN [dbo].[BJobs] parent_schedule_job ON jobs.[parent_schedule_id] = parent_schedule_job.[id]
		WHERE
			jobs.[type] IN (
			0,
			1,
			2,
			8,--QuickMigration
			24,--FileTapeBackup
			28,--VmTapeBackup
			51,--BackupSync,
			52,--SqlLogBackupJob
			54,--OracleLogBackup
			64, --SimpleBackupCopyPolicy
			202,--FailoverPlan,
			4000,--EndpointBackup
			12000,--EpAgentManagement
			12002,--EpAgentPolicy
			12003--EpAgentBackup
			)
GO


--------------------------------------------------------------------------------
-- FailoverPlanJobsView
PRINT N'Creating [dbo].[WmiServer.FailoverPlanJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.FailoverPlanJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.FailoverPlanJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.FailoverPlanJobsView]
	AS
		SELECT 
			bj.id,
			bj.usn
		FROM 
			[BJobs] bj
		WHERE
			bj.type = 202
GO


--------------------------------------------------------------------------------
PRINT N'Creating [dbo].[WmiServer.SqlLogBackupJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SqlLogBackupJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SqlLogBackupJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.SqlLogBackupJobsView]
	AS
		SELECT 
			bj.id,
			bj.parent_job_id,
			bj.usn
		FROM 
			[BJobs] bj
		WHERE
			bj.type = 52
GO

--------------------------------------------------------------------------------
PRINT N'Creating [dbo].[WmiServer.OracleBackupJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.OracleBackupJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.OracleBackupJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.OracleBackupJobsView]
	AS
		SELECT 
			bj.id,
			bj.parent_job_id,
			bj.usn
		FROM 
			[BJobs] bj
		WHERE
			bj.type = 54
GO

--------------------------------------------------------------------------------
-- [WmiServer.ObjectsInJobsView]
PRINT N'Creating [dbo].[WmiServer.ObjectsInJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ObjectsInJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ObjectsInJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.ObjectsInJobsView]
	AS
		SELECT
			j.[id] as id,
			s.[object_name] as obj_name,
			o.[object_id] as obj_reference,
			j.job_id,
			j.order_no,
			j.approx_size,
			j.vss_options,
			j.[disk_filter],
			j.[platform],
			o.[host_id],
			CASE 
				WHEN o.[platform] = 0 AND o.[viobject_type] = N'VirtualMachine' THEN 1 --VM
				WHEN o.[platform] = 1 THEN o.[type] 
				WHEN o.[platform] = 4 AND o.[type] = 4 THEN 1--VM
				ELSE 0
			END as obj_type,
			o.[platform] as obj_platform,
			o.[type] as src_obj_type,
			o.[viobject_type],
			j.[type] as oij_type,
			jv.[type] as job_type,
			jv.[job_source_type],
			[dbo].[MaxValue3](j.usn, o.usn, jv.usn) as usn
		FROM [dbo].[ObjectsInJobs] j
		JOIN [dbo].[BObjects] o ON j.[object_id] = o.[id] 
		JOIN [dbo].[BObjectsSensitiveInfo] s ON s.[bObject_id] = o.id
		JOIN [dbo].[WmiServer.JobsView] jv ON jv.[id] = j.[job_id]
		WHERE j.[type] IN (0, 1, 2, 3) AND 
			jv.[platform] IN (0, 1, 4) AND
			jv.[type] IN (0, 1, 2, 3, 51, 202)
GO

--------------------------------------------------------------------------------
-- [WmiServer.HostsView]
PRINT N'Creating [dbo].[WmiServer.HostsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.HostsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.HostsView]
GO
	CREATE VIEW [dbo].[WmiServer.HostsView]
	AS
		SELECT
			h.id,
			h.type,
			h.name,
			h.info,
			h.dns_name,
			h.host_unique_id,
			ISNULL(ph.os_type, 0) as os_type,
			h.[parent_id],
			ph.[hardware_info],
			el.[location_id],			
			[dbo].[MaxValue3](h.usn, ph.usn, el.usn) as usn
		FROM 
			[dbo].[fn.VisibleHosts]() h
		LEFT JOIN [PhysicalHosts] ph ON ph.id = h.physical_host_id
		LEFT JOIN [EntityLocations] el ON h.[id] = el.[entity_id] AND el.[entity_type] IN (0, 1, 2)
		WHERE h.[type] IN (0, 1, 2, 3, 5, 6, 7,8 ,9, 10, 11, 12, 13, 14)
GO

-----------------
-- 
PRINT N'Creating [dbo].[WmiServer.BackupToVmInBackupAssociationView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupToVmInBackupAssociationView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupToVmInBackupAssociationView]
GO

	CREATE VIEW  [dbo].[WmiServer.BackupToVmInBackupAssociationView]
	AS
			
		SELECT left_id, right_id
		FROM 
		(
			SELECT 
				pnts.backup_id as left_id,
				oibs.id as right_id,
				ROW_NUMBER() OVER (PARTITION BY pnts.backup_id,oibs.object_id ORDER BY pnts.num DESC, oibs.[creation_time] DESC) rn 
			FROM  
				[dbo].[Backup.Model.Points] pnts,
				[dbo].[Backup.Model.OIBs] oibs
			WHERE				
				pnts.id = oibs.point_id and
				oibs.is_corrupted = 0
		) q
		WHERE q.rn = 1
GO



-----------------
PRINT N'Creating [dbo].[WmiServer.VmInBackupToVmAssociationView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInBackupToVmAssociationView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInBackupToVmAssociationView]
GO

	CREATE VIEW [dbo].[WmiServer.VmInBackupToVmAssociationView]
	AS
		SELECT left_id, right_id
		FROM 
		(
			SELECT 
				oibs.id as left_id,
				vms.id as right_id,
				ROW_NUMBER() OVER (PARTITION BY pnts.backup_id,oibs.object_id ORDER BY pnts.num DESC, oibs.[creation_time] DESC) rn 
			FROM  
				[dbo].[Backup.Model.Points] pnts,
				[dbo].[Backup.Model.OIBs] oibs,
				[dbo].[BObjects] vms
			WHERE				
				pnts.id = oibs.point_id and
				oibs.is_corrupted = 0 and
				oibs.object_id = vms.id
		) q
		WHERE q.rn = 1 
GO



-----------------
PRINT N'Creating [dbo].[WmiServer.LatestOibsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.LatestOibsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.LatestOibsView]
GO

	CREATE VIEW [dbo].[WmiServer.LatestOibsView]
	AS
		SELECT q.id, q.creation_time, q.backup_id, q.object_id, q.usn,
			CAST(
				CASE 
					WHEN q.[platform] = 0 AND q.[viobject_type] = N'VirtualMachine' THEN 1 --VM
					WHEN q.[platform] = 1 THEN q.[type] 
					WHEN q.[platform] = 4 AND q.[type] = 4 THEN 1--VM
					ELSE 0
				END as bit
			) as is_vm
		FROM
	    (
	    SELECT 
			oibs.id,
			oibs.creation_time,
			oibs.object_id,
			oibs.usn,
			oibs.parent_id,
			pnts.backup_id,
			o.[platform],
			o.[type],
			o.[viobject_type],
			ROW_NUMBER() OVER (PARTITION BY pnts.backup_id, oibs.object_id ORDER BY pnts.num DESC, oibs.[creation_time] DESC) rn
		 FROM 
			[dbo].[Backup.Model.OIBs] oibs 
			JOIN [dbo].[Backup.Model.Points] pnts ON pnts.id = oibs.point_id
			JOIN [dbo].[BObjects] o ON oibs.[object_id] = o.[id]
		 WHERE 
			oibs.is_corrupted = 0
		) q
		WHERE 
			q.rn = 1
GO


-----------------
PRINT N'Creating [dbo].[WmiServer.VmInBackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInBackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInBackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInBackupsView]
	AS
			
		--CREATE TABLE #PartitionedOibs (vm_in_backup_id uniqueidentifier, last_backup_date datetime, backup_id uniqueidentifier, obj_id uniqueidentifier, vm_in_backup_usn bigint )
		--INSERT INTO #PartitionedOibs
		--SELECT * FROM #PartitionedOibs
		
		SELECT 			
			loibs.vm_in_backup_id,
			loibs.vm_in_backup_usn as usn,
			loibs.last_backup_date,
			loibs.is_vm,
			loibs.obj_id as object_id,
			qq.first_backup_date, 
			qq.restore_points,
			qq.backup_id,
			s.has_ad,
			s.has_exchange,
			s.has_sharepoint,
			s.has_sql
		FROM
		(
			SELECT
				 q.backup_id,
				 q.object_id,
				 MIN(q.creation_time) as first_backup_date,
				 MAX(q.rn) as restore_points
			FROM		
			(
					SELECT 
						oibs.id,
						oibs.object_id,
						--oibs.vmname,
						pnts.backup_id,
						pnts.link_id,
						oibs.creation_time,
						ROW_NUMBER() OVER (PARTITION BY pnts.backup_id, oibs.object_id ORDER BY pnts.num DESC, oibs.[creation_time] DESC) rn
					 FROM 
						[dbo].[Backup.Model.OIBs] oibs 
						JOIN [dbo].[Backup.Model.Points] pnts ON pnts.id = oibs.point_id
					 WHERE 
						oibs.is_corrupted = 0
			)q
			GROUP BY q.backup_id, q.object_id
		) qq
		INNER JOIN 
		(SELECT 
			id as vm_in_backup_id
			,creation_time as last_backup_date
			,backup_id as backup_id
			,object_id as obj_id
			,usn as vm_in_backup_usn
			,is_vm
		 FROM [dbo].[WmiServer.LatestOibsView] 
		--WHERE (id = '00000000-0000-0000-0000-000000000000' OR id = q.id)
		) loibs ON loibs.backup_id = qq.backup_id AND loibs.obj_id = qq.object_id
		JOIN [Backup.Model.OIBs] oibs1 ON loibs.vm_in_backup_id = oibs1.id
		JOIN dbo.[Backup.Model.OIBsSensitiveInfo] s ON s.oib_id = oibs1.id
GO


---------------------------------
PRINT N'Creating [dbo].[WmiServer.JobSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.JobSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.JobSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.JobSessionsView]
    AS
          SELECT 
                  js.id,
                  js.job_id,
				  js.job_type,
                  js.state,
                  js.result,
				  js.reason,
                  js.creation_time,
                  js.end_time,
				  js.orig_session_id,
                  js.log_xml.value('(/Root/Log)[1]', 'nvarchar(max)') as last_log_entry,
				  js.job_name,
                  CASE 
                        WHEN js.usn > ISNULL(bjs.usn, 0) THEN js.usn
                        ELSE bjs.usn
                  END as usn,
				  bjs.[cur_point_id],
				  ISNULL(bjs.will_be_retried, 0) as will_be_retried,
                  ISNULL(bjs.processed_size, 0) as processed_size,
				  ISNULL(bjs.source_storage, -1) as src_stg_load,
				  ISNULL(bjs.source_proxy, -1) as src_proxy_load,
				  ISNULL(bjs.source_network, -1) as src_network_load,
				  ISNULL(bjs.target_network, -1) as tgt_network_load,
				  ISNULL(bjs.target_storage, -1) as tgt_stg_load,
				  ISNULL(bjs.source_wan, -1) as src_wan_load,
				  ISNULL(bjs.target_wan, -1) as tgt_wan_load,
				  ISNULL(bjs.[backup_total_size], 0) as total_backed_up_size,
				  ISNULL(bjs.[stored_size], 0) as stored_size,
				  ISNULL(bjs.[avg_speed], 0) as processing_rate,
				  ISNULL(bjs.[job_algorithm], 0) as job_alg,
				  ISNULL(bjs.[session_algorithm], 0) as session_alg
          FROM [dbo].[Backup.Model.JobSessions] js 
          LEFT JOIN [dbo].[Backup.Model.BackupJobSessions] bjs ON bjs.id = js.id
		  WHERE js.job_type IN (
			  0, 
			  1, 
			  2, 
			  8, 
			  24,
			  28,
			  50,
			  51,
			  52,
			  54,
			  202,--FailoverPlan
			  203,--UndoFailoverPlan
			  4000,
			  12000,
			  12002,
			  12003
			  ) AND
			  js.[state] IN (-1, 3, 4, 5, 8, 9, 10, 11)
GO


---------------------------------
PRINT N'Creating [dbo].[WmiServer.SqlLogBackupJobSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SqlLogBackupJobSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SqlLogBackupJobSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.SqlLogBackupJobSessionsView]
    AS
		SELECT 
			js.id,
			js.creation_time,
			js.usn as usn
        FROM [dbo].[Backup.Model.JobSessions] js
		WHERE js.job_type  = 52
GO

---------------------------------
PRINT N'Creating [dbo].[WmiServer.SqlLogBackupSessionTasksView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SqlLogBackupSessionTasksView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SqlLogBackupSessionTasksView]
GO
	CREATE VIEW [dbo].[WmiServer.SqlLogBackupSessionTasksView]
    AS
		SELECT 
			bts.id,
			bts.creation_time,
			bts.usn
        FROM [dbo].[Backup.Model.JobSessions] js 
		INNER JOIN [dbo].[Backup.Model.BackupTaskSessions] bts ON bts.session_id = js.id
		WHERE js.job_type  = 52
GO

--------------------------------------------------------------------------------
-- [WmiServer.VPowerServersView]
PRINT N'Creating [dbo].[WmiServer.VPowerServersView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VPowerServersView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VPowerServersView]
GO
	CREATE VIEW [dbo].[WmiServer.VPowerServersView]
	AS
		SELECT 
			c.[id] as component_id,
			ph.[name] as host_name,
			c.[is_up_to_date] as component_is_up_to_date,
			c.[version] as component_version,			
			[dbo].[MaxValue](ph.[usn], c.[usn]) AS usn
		FROM
			[dbo].[PhysicalHosts] ph,
			[dbo].[HostComponents] c
		WHERE
			c.[physical_host_id] = ph.[id] AND
			c.[type] = 1 						-- c.[type] = EComponentType.Nfs			
GO



-- [WmiServer.VmsView]
PRINT N'Creating [dbo].[WmiServer.VmsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmsView]
GO
	CREATE VIEW [dbo].[WmiServer.VmsView]
	AS
		SELECT 
			o.[id],
			sb.[object_name],
			o.[object_id],
			o.[platform],
			o.[host_id],
			o.[usn],
			sb.[guest_os],
			hosts.name as hierarchy_root_name
		FROM
			[dbo].[BObjects] o
			JOIN dbo.BObjectsSensitiveInfo sb ON sb.bobject_id = o.id
			INNER JOIN [dbo].[fn.VisibleHosts]() hosts ON o.host_id = hosts.id
		WHERE
			(o.[platform] = 0 AND o.[viobject_type] = N'VirtualMachine') OR
			(o.[platform] = 1 AND o.[type] = 1) OR
			(o.[platform] = 4 AND o.[type] = 4) 
GO

--------------------------------------------------------------------------------
-- [WmiServer.BackupTaskSessionsView]
PRINT N'Creating [dbo].[WmiServer.BackupTaskSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupTaskSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupTaskSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.BackupTaskSessionsView]
	AS
		SELECT 
			bts.[id],
			bts.[status],
			bts.[object_id],
			bts.[object_name],
			bts.[work_details],
			bts.[creation_time],
			bts.[end_time],
			bts.[stored_size],
			bts.[reason],
			bts.[total_size] as total_vm_size,
			bts.[read_size] as read_size,
			bts.[processed_used_size] as processed_used_size,
			bts.[avg_speed] as processing_rate,
			bts.[source_storage] as src_stg_load,
			bts.[source_proxy] as src_proxy_load,
			bts.[source_network] as src_network_load,
			bts.[target_network] as tgt_network_load,
			bts.[target_storage] as tgt_stg_load,
			bts.[usn],
			bts.[total_objects] as total_objects,
			bts.[processed_objects] as processed_objects,
			bts.[session_id] as job_session_id
		FROM
			[dbo].[Backup.Model.BackupTaskSessions] bts WITH (NOLOCK)
GO



--------------------------------------------------------------------------------
-- [WmiServer.BackupsView]
PRINT N'Creating [dbo].[WmiServer.BackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.BackupsView]
	AS
		SELECT
			backups.id,
			backups.job_target_type as job_type,
			backups.job_name,
			CONVERT(BIT, CASE WHEN backups.[job_target_type] = 1 THEN 1 ELSE 0 END) as is_replica,
			backups.usn,
			backups.platform,
			backups.job_id,
			backups.repository_id
		FROM
			[dbo].[Backup.Model.Backups] backups WITH (NOLOCK)
		WHERE [job_target_type] IN (
			0,
			1,
			2,
			8,--QuickMigration
			24,--FileTapeBackup
			28,--VmTapeBackup
			51,--BackupSync,
			52,--SqlLogBackupJob
			54,--OracleLogBackup
			202,--FailoverPlan,			
			4000,--EndpointBackup
			12000--EpAgentManagement
			)
		AND [platform] IN (
			0, --Vmwware
			1, --HV
			4, -- VCD
			5, --tape
			6, -- win agent
			7, --linux agent
			8  --external backup
		)
GO



--------------------------------------------------------------------------------
-- [WmiServer.SbJobVmSessionsView]
PRINT N'Creating [dbo].[WmiServer.SbJobVmSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SbJobVmSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SbJobVmSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.SbJobVmSessionsView]
	AS
		SELECT 
			s.[id],
			s.[drsession_id] as session_id,
			oibs.[creation_time] as verification_date,
			s.[start_time],
			s.[ping_status],
			s.[heartbeat_status],
			s.[test_script_status],
			s.[overall_status],
			s.[state],
			s.[finish_time],
			o.[options],
			p.[backup_id],
			s.[object_id],
			s.[test_scripts_results],
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = s.id AND ats.[state] <> 2 /*EAntivirusScanState.Finished*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_incompleted,
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = s.id AND ats.result = 2 /*EAntivirusScanResult.Infected*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_infected,
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = s.id AND ats.result = 3 /*EAntivirusScanResult.Failed*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_failed,
			(
				SELECT TOP 1 ats.antivirusName
				FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
				JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
				WHERE js2as.initiator_session_id = s.id AND ats.[antivirusName] IS NOT NULL
			) as antivirus_name,
			CASE 
				WHEN s.usn > ISNULL(o.usn, 0) THEN s.usn
				ELSE ISNULL(o.usn, 0)
			END as usn
		FROM
			[dbo].[Backup.Model.SbTaskSessions] s
			LEFT JOIN [dbo].[Backup.Model.OIBs] oibs ON s.[oib_id] = oibs.[id]
			LEFT JOIN [dbo].[Backup.Model.Points] p ON oibs.[point_id] = p.[id]
			LEFT JOIN [dbo].[ObjectsInApplicationGroups] o ON s.[oiag_id] = o.[id]
GO


--------------------------------------------------------------------------------
-- [WmiServer.SbJobsView]
PRINT N'Creating [dbo].[WmiServer.SbJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SbJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SbJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.SbJobsView]
	AS
		SELECT 
			[id],
			[name],
			schedule_enabled, 
			schedule AS schedule_options,
			ISNULL(options.value('(/*/RunManually)[1]', 'bit'), 1) AS run_manually,
			[usn],
			[parent_schedule_id],
			[platform],
			[created_by],
			[creation_date]
		FROM
			[dbo].[BJobs]
		WHERE 
			[type] = 3
GO


--------------------------------------------------------------------------------
PRINT N'Creating [dbo].[WmiServer.RestoreSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RestoreSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RestoreSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.RestoreSessionsView]
	AS
		SELECT 
			js.[id] AS id,
			js.[job_type] AS type,
			js.[job_id],
			js.[creation_time] AS start_time,
			js.[end_time] AS end_time,
            js.[state],
            js.[result],
			js.[initiator_name],
			rjs.[oib_creation_time] AS restore_point_date,
			rjs.[oib_display_name] as vm_display_name,
			rjs.[parent_session_id],
			rjs.[reason] as restore_reason,
			rjs.[sub_type] as sub_type,
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = js.id AND ats.[state] = 2 /*EAntivirusScanState.Finished*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_incompleted,
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = js.id AND ats.result = 2 /*EAntivirusScanResult.Infected*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_infected,
			CAST((CASE 
				WHEN EXISTS(SELECT js2as.antivirus_task_session_id 
							FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
							JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
							WHERE js2as.initiator_session_id = js.id AND ats.result = 3 /*EAntivirusScanResult.Failed*/) THEN 1
				ELSE 0 
			END) AS BIT) as are_some_tasks_failed,
			(
				SELECT TOP 1 ats.antivirusName
				FROM [dbo].[Backup.Model.AntivirusTaskSessionsByInitiatorSession] js2as 
				JOIN [dbo].[Backup.Model.AntivirusTaskSessions] ats ON js2as.antivirus_task_session_id = ats.id 
				WHERE js2as.initiator_session_id = js.id AND ats.antivirusName IS NOT NULL
			) as antivirus_name,
			oibs.[storage_id] as restore_point_id,
			[dbo].[MaxValue](js.[usn], rjs.[usn]) AS usn
		FROM [dbo].[Backup.Model.JobSessions] js
		INNER JOIN [dbo].[Backup.Model.RestoreJobSessions] rjs ON js.[id] = rjs.[id]
		LEFT JOIN [dbo].[Backup.Model.OIBs] oibs ON rjs.[oib_id]=oibs.[id]
		WHERE js.[job_type] IN (
					4, --EDbJobType.RestoreVm
					5, --EDbJobType.RestoreVmFiles
					6, --EDbJobType.RestoreFiles
					7, --EDbJobType.Failover
					10, --EDbJobType.FileLevelRestore
					11, --EDbJobType.LinuxFileLevelRestore
					12, --EDbJobType.InstantRecovery
					13, --EDbJobType.RestoreHdd
					25, --EDbJobType.FileTapeRestore
					29, --EDbJobType.VmTapeRestore
					41, --EDbJobType.VcdVAppRestore
					42, --EDbJobType.VcdVmRestore
					48, --EDbJobType.ApplicationLevelRestore
					8000 --EDbJobType.FileLevelRestoreByEnterprise
				)
GO


--------------------------------------------------------------------------------
PRINT N'Creating [dbo].[WmiServer.RestoreItemsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RestoreItemsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RestoreItemsView]
GO
	CREATE VIEW [dbo].[WmiServer.RestoreItemsView]
	AS
		SELECT 
		   ra.[id]
		  ,ra.[restore_session_id]
		  ,ra.[restore_state] as state
		  ,ra.[item_type]
		  ,ra.[item_name]
		  ,ra.[item_size]
		  ,ra.[dest_type]
		  ,ra.[dest_host]
		  ,ra.[destination] as destination
		  ,ra.[start_time]
		  ,ra.[finish_time]
		  ,ra.[message]
		  ,ra.[source]
		  ,ra.[operation_type]
		  ,ra.[usn]
		FROM
			[dbo].[ItemRestoreAudits] ra
GO



PRINT N'Creating [dbo].[WmiServer.ServiceComponentsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ServiceComponentsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ServiceComponentsView]
GO
	CREATE VIEW [dbo].[WmiServer.ServiceComponentsView]
	AS
		SELECT 
			c.[id] AS service_id,
			c.[type] AS component_type,
			h.*
		FROM [dbo].[HostComponents] c
		JOIN [dbo].[Hosts] h ON h.[physical_host_id] = c.[physical_host_id]
		LEFT JOIN [dbo].[BackupProxies] bp ON h.id = bp.[host_id] AND c.[type] = 6 -- only for Tape components
		WHERE
		c.[type] IN (0, 1, 2, 3, 4, 5, 7)
		OR (c.[type] = 6 AND bp.[type] = 3) -- CBackupProxyInfo.EType.Tape
GO



PRINT N'Creating [dbo].[WmiServer.SbAppGroupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SbAppGroupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SbAppGroupsView]
GO
	CREATE VIEW [dbo].[WmiServer.SbAppGroupsView]
	AS
		SELECT 
			f.[id],
			f.[name] as name,
			f.[usn] as usn
		FROM		
			[dbo].[Folders] f
		WHERE
			f.[parent_id] = '32E53DC4-62EA-47b4-8E02-88509707D587'--app groups root
GO

---------------------------------
PRINT N'Creating [dbo].[WmiServer.SbJobSessionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SbJobSessionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SbJobSessionsView]
GO
	CREATE VIEW [dbo].[WmiServer.SbJobSessionsView]
    AS
		SELECT 
			js.id,
			js.job_id,
			js.state,
			js.result,
			js.[creation_time],
			js.[end_time],
			js.[job_name],
			js.[job_type],
			js.[initiator_name],
			js.[reason],
            CASE 
				WHEN js.usn > bjs.usn THEN js.usn
				ELSE bjs.usn
			END as usn
		FROM [dbo].[Backup.Model.SbSessions] bjs
		INNER JOIN [dbo].[Backup.Model.JobSessions] js ON bjs.id = js.id
		WHERE js.[job_type] IN (3, 17000) --SureBackup + Staged Restore
GO


PRINT N'Creating [dbo].[WmiServer.CifsSharesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CifsSharesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CifsSharesView]
GO
	CREATE VIEW [dbo].[WmiServer.CifsSharesView]
	AS
		SELECT 
			repo.[id] as id,
			repo.[id] as repo_id,
			repo.[path] as path
		FROM
			[dbo].[BackupRepositories] repo
		WHERE
			repo.[type] = 2 -- CIFS
GO



PRINT N'Creating [dbo].[WmiServer.LinuxRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.LinuxRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.LinuxRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.LinuxRepositoriesView]
	AS
		SELECT 
			repo.[id] as id,
			repo.[id] as repo_id,
			repo.[path] as path
		FROM
			[dbo].[BackupRepositories] repo
		WHERE
			repo.[type] = 1 -- Linux
GO


PRINT N'Creating [dbo].[WmiServer.RestorePointsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RestorePointsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RestorePointsView]
GO
	CREATE VIEW [dbo].[WmiServer.RestorePointsView]
	AS
		SELECT 
			points.[id] as id,
			points.[file_path] as file_path,
			ISNULL(points.backup_size, 0) as backup_size,
			points.[creation_time] as restore_point_date,
			points.backup_id,
			ISNULL(points.dedup_ratio, 100) as dedup_ratio,
			ISNULL(points.compress_ratio, 100) as compress_ratio,
			points.[usn] as usn,
			points.[gfs_period],
			CAST(CASE WHEN PATINDEX('%.vbk', points.[file_path]) > 0 THEN 0 ELSE 1 END AS BIT) AS is_incremental,
			bj.[options],
			(SELECT COUNT(*) FROM [dbo].[Backup.Model.OIBs] oib WHERE oib.[storage_id]=points.[id] AND oib.[is_corrupted]=0) as oibs_count,
			er.dependant_repo_id as repo_extent_id
		FROM [dbo].[Backup.Model.Storages] points WITH ( NOLOCK )
		LEFT JOIN [dbo].[Backup.Model.Backups] backups WITH ( NOLOCK ) ON points.backup_id = backups.id
		LEFT JOIN [dbo].[BJobs] bj WITH ( NOLOCK ) ON backups.job_id = bj.id
		LEFT JOIN [dbo].[Backup.ExtRepo.Storages] es WITH ( NOLOCK ) ON es.[storage_id] = points.[id]
		LEFT JOIN [dbo].[Backup.ExtRepo.ExtRepos] er WITH ( NOLOCK ) ON es.dependant_repo_id = er.id
		WHERE backups.[job_target_type] IN (
			0,--Backup
			2,--Copy
			8,--QuickMigration
			24,--FileTapeBackup
			28,--VmTapeBackup
			51,--BackupSync,
			4000,--EndpointBackup
			12000--EpAgentManagement
			)
GO

PRINT N'Creating [dbo].[WmiServer.ReplicaRestorePointsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ReplicaRestorePointsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ReplicaRestorePointsView]
GO
	CREATE VIEW [dbo].[WmiServer.ReplicaRestorePointsView]
	AS
		SELECT 
			oib.[id] as id,
			oib.[creation_time] as creation_date,
			oib.object_id,
			points.backup_id,
			oib.[usn] as usn
		FROM [dbo].[Backup.Model.OIBs] oib 
		JOIN [dbo].[Backup.Model.Points] points ON oib.point_id = points.id
		JOIN [dbo].[Backup.Model.Backups] b ON points.backup_id = b.id
		WHERE b.[job_target_type] = 1
GO


PRINT N'Creating [dbo].[WmiServer.VmRestorePointsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmRestorePointsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmRestorePointsView]
GO
	CREATE VIEW [dbo].[WmiServer.VmRestorePointsView]
	AS
		SELECT 
			vmRestorePoints.[id] as id,
			s.[display_name] as display_vm_name,
			vmRestorePoints.[storage_id] as storage_id,
			vmRestorePoints.[object_id],
			vmRestorePoints.[product_version_flags],
			vmRestorePoints.[creation_time_utc],
			vmRestorePoints.[point_id],
			CAST(CASE WHEN bobj.[viobject_type] = N'Vapp' THEN 1 ELSE 0 END AS BIT) AS is_vapp,
			vmRestorePoints.[usn] as usn
		FROM [dbo].[Backup.Model.OIBs] vmRestorePoints
		LEFT JOIN [dbo].[Backup.Model.OIBsSensitiveInfo] s ON s.oib_id = vmRestorePoints.id
		JOIN [dbo].[BObjects] bobj ON vmRestorePoints.[object_id] = bobj.[id]
		WHERE vmRestorePoints.[is_corrupted]=0
GO

PRINT N'Creating [dbo].[WmiServer.WanAcceleratorsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.WanAcceleratorsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.WanAcceleratorsView]	
GO
	CREATE VIEW [dbo].[WmiServer.WanAcceleratorsView]
	AS
		SELECT
			wa.[id],
			wa.[name],
			wa.[description],
			wa.[host_id],
			wa.[usn],
			hc.[type],
			[dbo].[fn.IsHostUpgradeRequired](wa.[host_id]) AS [is_out_of_date],
			hc.[version],
			hc.options.value('(/WanAcceleratorClientOptions/MaxCacheSize)[1]', 'int') as maxCacheSize,
			hc.options.value('(/WanAcceleratorClientOptions/SizeUnit)[1]', 'nvarchar(10)') as sizeUnit,
			hc.options.value('(/WanAcceleratorClientOptions/TrafficPort)[1]', 'int') as trafficPort,
			hc.options.value('(/WanAcceleratorClientOptions/CachePath)[1]', 'nvarchar(max)') as cachePath,
			hc.options.value('(/WanAcceleratorClientOptions/DownloadStreamCount)[1]', 'int') as connectionsCount
		FROM [dbo].[WanAccelerators] wa
		JOIN [dbo].[Hosts] h ON wa.[host_id] = h.[id]
		JOIN [dbo].[HostComponents] hc ON hc.[physical_host_id] = h.[physical_host_id]
		WHERE hc.[type] = 5
GO

PRINT N'Creating [dbo].[WmiServer.JobProcessesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.JobProcessesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.JobProcessesView]	
GO
	CREATE VIEW [dbo].[WmiServer.JobProcessesView]
	AS
		SELECT 
			js.[id],
			js.[pid],
			(SELECT TOP 1 Name FROM [dbo].[Hosts] WHERE id = '6745a759-2205-4cd2-b172-8ec8f7e60ef8') as host_name,
			0 as process_type --manager process
		FROM [dbo].[Backup.Model.JobSessions] js
		WHERE EXISTS(SELECT id FROM [dbo].[Backup.Model.BackupJobSessions] bjs WHERE bjs.[id] = js.[id])
		AND js.state = 5
		UNION
		SELECT 
			pa.[session_id] as id, 
			pa.[pid], 
			pa.[host_name], 
			1 as process_type --agent process
		FROM [dbo].[ProxyAgents] pa
GO


PRINT N'Creating [dbo].[WmiServer.TapeJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeJobsView]	
GO
	CREATE VIEW [dbo].[WmiServer.TapeJobsView]
	AS
		SELECT
			tjobs.[id],
			tjobs.[usn],
			tjobs.[full_mediapool_id],
			tjobs.[incremental_mediapool_id],
			tjobs.[options]
		FROM
			[dbo].[Tape.jobs] tjobs		

GO

PRINT N'Creating [dbo].[WmiServer.TapeProxiesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeProxiesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeProxiesView]	
GO
	CREATE VIEW [dbo].[WmiServer.TapeProxiesView]
	AS
		SELECT
			p.[id],
			p.[name],
			c_tape.[version],
			dbo.MaxValue4(p.usn, h.usn, c_tape.usn, ph.usn) as usn,
            [dbo].[fn.IsHostUpgradeRequired](p.[host_id]) AS [component_is_out_of_date]
			--p.[options]
		FROM
			[dbo].[BackupProxies] p
		JOIN [dbo].[Hosts] h ON h.[id] = p.[host_id]
		JOIN [dbo].[HostComponents] c_tape ON c_tape.[physical_host_id] = h.[physical_host_id] AND c_tape.[type] = 6
		JOIN [dbo].[PhysicalHosts] ph ON h.[physical_host_id] = ph.[id]
		WHERE 
			p.type = 3 --Tape

GO

PRINT N'Creating [dbo].[WmiServer.BackupCopyJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupCopyJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupCopyJobsView]	
GO
	CREATE VIEW [dbo].[WmiServer.BackupCopyJobsView]
	AS
		SELECT
			jobs.[id],
			jobs.[usn],
			jobs.[options],
			source_wan.[accelerator_id] as source_wan_id,
			target_wan.[accelerator_id] as target_wan_id
		FROM
			[dbo].[BJobs] jobs
		LEFT JOIN [dbo].[Backup.Model.JobWanAccelerators] source_wan ON jobs.id = source_wan.job_id AND source_wan.type = 0 AND source_wan.[accelerator_id] <> '00000000-0000-0000-0000-000000000000'
		LEFT JOIN [dbo].[Backup.Model.JobWanAccelerators] target_wan ON jobs.id = target_wan.job_id AND target_wan.type = 1 AND target_wan.[accelerator_id] <> '00000000-0000-0000-0000-000000000000'
		WHERE
			jobs.[type] IN (
				51,--BackupSync
				64 --SimpleBackupCopyPolicy
				)
GO

PRINT N'Creating [dbo].[WmiServer.MediaPoolsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.MediaPoolsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.MediaPoolsView]	
GO
	CREATE VIEW [dbo].[WmiServer.MediaPoolsView]
	AS
		SELECT
			mps.[id],
			mps.[name],
			mps.[options],
			mps.[usn]
		FROM
			[dbo].[Tape.media_pools] mps

GO

PRINT N'Creating [dbo].[WmiServer.GfsMediaPoolsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.GfsMediaPoolsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.GfsMediaPoolsView]	
GO
	CREATE VIEW [dbo].[WmiServer.GfsMediaPoolsView]
	AS
		SELECT
			mps.[id],
			mps.[options],
			mps.[usn]
		FROM
			[dbo].[Tape.media_pools] mps
		WHERE 
			[type] = 5

GO

--see Tape.report_media_changes
PRINT N'Creating [dbo].[WmiServer.TapesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapesView]	
GO
	CREATE VIEW [dbo].[WmiServer.TapesView]
	AS
		SELECT
			tapes.[id],
			tapes.[name],
			tapes.[barcode],
			tapes.[location_type],
			tapes.[media_family_id],
			tapes_familes.[name] as media_family,
			media_pools.name as media_pool_name,
			ln.name as library_name,
			tapes.[location_library_id] as library_uid,
			tapes.[media_pool_id],
			tapes.[media_id],
			tapes.[capacity],
			tapes.[remaining],
			tapes.[protected],
			tapes.[location_address] + 1 AS location_number,
			tapes.[last_write_time],
			CAST(tapes.[media_set_type] AS INT) as media_set_type,
			exp_date.expiration_date,
			mv.[name] as vault_name,
			exp_date.job_name as written_by_job,
			miv.vault_id,
			[dbo].[MaxValue5](tapes.[usn], media_pools.[usn], lib.[usn], mv.[usn], exp_date.usn) as usn
		FROM
			[dbo].[Tape.tape_mediums] tapes
		LEFT JOIN [dbo].[Tape.media_families] tapes_familes ON (tapes.[media_family_id] = tapes_familes.[id])
		LEFT JOIN [dbo].[Tape.media_pools] media_pools ON (tapes.media_pool_id = media_pools.id)
		LEFT JOIN [dbo].[Tape.library_names] ln ON tapes.location_library_id = ln.id 
		LEFT JOIN [dbo].[Tape.libraries] lib ON ln.id = lib.id
		LEFT JOIN [Tape.media_in_vaults] miv ON miv.media_id = tapes.id 
		LEFT JOIN [Tape.media_vaults] mv ON miv.vault_id = mv.id
		LEFT JOIN
		(			
			SELECT 
				tm.id as tape_id,
				tbs.expiration_date,
				tb.name as job_name,
				ROW_NUMBER() OVER (PARTITION BY tm.id ORDER BY tbs.expiration_date DESC) rn,
				[dbo].[MaxValue2](tbs.usn, tb.usn) as usn
			FROM [dbo].[Tape.tape_mediums] tm
			LEFT JOIN [dbo].[Tape.tape_medium_backup_sets] tmbs ON tmbs.tape_medium_id = tm.id
			LEFT JOIN [dbo].[Tape.backup_sets] tbs ON tmbs.backup_set_id = tbs.id
			LEFT JOIN [dbo].[Tape.backups] tb ON tbs.backup_id = tb.id
		) as exp_date ON tapes.id = exp_date.tape_id AND exp_date.rn = 1
GO



PRINT N'Creating [dbo].[WmiServer.TombstonesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TombstonesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TombstonesView]	
GO
	CREATE VIEW [dbo].[WmiServer.TombstonesView]
	AS
		SELECT
			ts.[uid] as id,
			ts.[table_name],
			ts.[date],
			ts.[usn]
		FROM
			[dbo].[TombStones] ts
GO


PRINT N'Creating [dbo].[WmiServer.TapeStorageToTapeAssociationsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeStorageToTapeAssociationsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeStorageToTapeAssociationsView]	
GO
	CREATE VIEW [dbo].[WmiServer.TapeStorageToTapeAssociationsView]
	AS
		SELECT
			tm.id, 
			ts.tape_storage_id as storage_id
		    FROM    dbo.[Tape.storages] ts WITH ( NOLOCK )
            JOIN [Tape.file_versions] fv WITH ( NOLOCK ) ON ts.file_version_id = fv.id
            JOIN [Tape.file_parts] fp WITH ( NOLOCK ) ON fv.id = fp.file_version_id
            JOIN [Tape.backup_sets] bs WITH ( NOLOCK ) ON fv.backup_set_id = bs.id
            JOIN [Tape.tape_mediums] tm WITH ( NOLOCK ) ON tm.media_family_id = bs.media_family_id AND tm.media_sequence_number = fp.media_sequence_number;
			
			
GO


PRINT N'Creating [dbo].[WmiServer.TapeStoragesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeStoragesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeStoragesView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeStoragesView]
	AS
			SELECT 
			s.id, 
			s.creation_time, 
			s.file_path, 
			s.backup_id,
			ISNULL(s.backup_size, 0) as size,
			mf.[type_id] as media_set_type,
			s.usn
		FROM dbo.[Backup.Model.Storages] s WITH (NOLOCK)
		JOIN dbo.[Tape.storages] ts WITH (NOLOCK) on s.id = ts.tape_storage_id 
		JOIN dbo.[Tape.file_versions] fv ON ts.file_version_id = fv.id
		JOIN dbo.[Tape.backup_sets] bs ON fv.backup_set_id = bs.id
		JOIN dbo.[Tape.media_families] mf ON bs.media_family_id = mf.id
GO


PRINT N'Creating [dbo].[WmiServer.TapeBackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeBackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeBackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeBackupsView]
	AS
		SELECT 
			id, 
			job_name, 
			job_target_type, 
			usn
		FROM [dbo].[Backup.Model.Backups]
		WHERE job_target_type = 28 --VmTapeBackup
		--OR job_target_type = 24 --FileTapeBackup

GO

PRINT N'Creating [dbo].[WmiServer.TapeOibsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeOibsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeOibsView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeOibsView]
	AS
		SELECT 
			vmRestorePoints.[id] as id,	
			s.[vmname] as vm_name,
			vmRestorePoints.[object_id],
			s.[display_name] as display_vm_name,
			vmRestorePoints.[storage_id] as storage_id,
			vmRestorePoints.[usn]
		FROM [dbo].[Backup.Model.OIBs] vmRestorePoints
		JOIN dbo.[Backup.Model.OIBsSensitiveInfo] s ON s.oib_id = vmRestorePoints.id
		JOIN dbo.[Tape.storages] ts on vmRestorePoints.[storage_id] = ts.tape_storage_id
		WHERE vmRestorePoints.[is_corrupted] = 0

GO

PRINT N'Creating [dbo].[WmiServer.JobSessionEventsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.JobSessionEventsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.JobSessionEventsView]
GO
	CREATE VIEW [dbo].[WmiServer.JobSessionEventsView]
	AS
		SELECT *
		FROM [dbo].[Events.JobSessionEvents]

GO

PRINT N'Creating [dbo].[WmiServer.TaskSessionEventsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TaskSessionEventsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TaskSessionEventsView]
GO
	CREATE VIEW [dbo].[WmiServer.TaskSessionEventsView]
	AS
		SELECT *
		FROM [dbo].[Events.TaskSessionEvents]

GO

PRINT N'Creating [dbo].[WmiServer.VmInVMwareReplicaView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInVMwareReplicaView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInVMwareReplicaView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInVMwareReplicaView]
	AS
		SELECT 
			oibs.id,
			oibs.object_id,
			b.id as backup_id,
			s.aux_data.value('(/COibAuxData/SnapReplicaAuxData/ReplVmName)[1]', 'nvarchar(255)') as repl_vm_name,
			s.aux_data.value('(/COibAuxData/SnapReplicaAuxData/ReplVmRef)[1]', 'nvarchar(255)') as repl_vm_ref,
			s.aux_data.value('(/COibAuxData/SnapReplicaAuxData/ReplSummary/Summary/ReplLocation)[1]', 'nvarchar(255)') as repl_location,
			dbo.MaxValue4(lov.usn, oibs.usn, p.usn, b.usn) as usn
		FROM [dbo].[WmiServer.LatestOibsView] lov
		JOIN [dbo].[Backup.Model.OIBs] oibs ON oibs.id = lov.id
		JOIN dbo.[Backup.Model.OIBsSensitiveInfo] s ON s.oib_id = oibs.id
		JOIN [dbo].[Backup.Model.Points] p ON oibs.point_id = p.id
		JOIN [dbo].[Backup.Model.Backups] b ON p.backup_id = b.id
		WHERE oibs.is_corrupted = 0 AND b.[job_target_type] = 1 AND b.[platform] = 0

GO

PRINT N'Creating [dbo].[WmiServer.VmInHyperVReplicaView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInHyperVReplicaView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInHyperVReplicaView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInHyperVReplicaView]
	AS
			SELECT 
				oibs.id,
				oibs.object_id as object_id,
				oibs.storage_id as point_id,
				so.aux_data,
				b.id as backup_id,
				b.target_type,
				b.job_target_host_id as target_host_id,
				dbo.MaxValue3(oibs.usn, s.usn, b.usn) as usn
			FROM [dbo].[WmiServer.LatestOibsView] lov
			JOIN [dbo].[Backup.Model.OIBs] oibs ON oibs.id = lov.id
			JOIN dbo.[Backup.Model.OIBsSensitiveInfo] so ON so.oib_id = oibs.id
			JOIN [dbo].[Backup.Model.Storages] s ON oibs.storage_id = s.id
			JOIN [dbo].[Backup.Model.Backups] b ON s.backup_id = b.id
			WHERE b.[job_target_type] = 1 AND b.[platform] = 1 AND (
			b.[target_type] = 2 --legacy replica
			OR
			b.[target_type] = 5 --snap replica
			)
GO

PRINT N'Creating [dbo].[WmiServer.DatabaseInfo]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.DatabaseInfo]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.DatabaseInfo]
GO
	CREATE VIEW [dbo].[WmiServer.DatabaseInfo]
	AS
		SELECT SERVERPROPERTY('ProductVersion') as product_version, SERVERPROPERTY('Edition') as edition
GO

PRINT N'Creating [dbo].[WmiServer.FailoverPlanObjectInJobView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.FailoverPlanObjectInJobView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.FailoverPlanObjectInJobView]
GO
	CREATE VIEW [dbo].[WmiServer.FailoverPlanObjectInJobView]
	AS
		SELECT 
			oij.id,
			oij.ex_options,
			CASE 
				WHEN object_last_proc_info.approx_size > 0 THEN object_last_proc_info.approx_size
				ELSE oij.approx_size 
			END as size,
			[dbo].[MaxValue2](oij.usn, object_last_proc_info.usn) as usn
		FROM [ObjectsInJobs] oij
		JOIN [dbo].[BJobs] bj ON oij.job_id = bj.id
		LEFT JOIN
		(
			SELECT 
				oib.[object_id], 
				oib.[usn],
				oib.[approx_size]
			FROM [Backup.Model.OIBs] oib
			JOIN
			(
				SELECT loib.object_id, MAX(loib.usn) as max_usn
				FROM [WmiServer.LatestOibsView] loib
				GROUP BY loib.object_id
			) AS t ON oib.object_id = t.object_id AND oib.usn = t.max_usn
		) AS object_last_proc_info ON object_last_proc_info.[object_id] = oij.[object_id]
		WHERE bj.type = 202
GO

PRINT N'Creating [dbo].[WmiServer.TapeInVaultView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeInVaultView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeInVaultView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeInVaultView]
	AS
		SELECT 
			miv.id,
			mv.name as vault_name,
			mp.options,
			exp_date.expiration_date,
			[dbo].MaxValue4(miv.usn, mv.usn, exp_date.tape_usn,exp_date.backup_set_usn) as usn
		FROM [dbo].[Tape.media_vaults] mv
		JOIN [dbo].[Tape.media_in_vaults] miv ON mv.id = miv.vault_id
		JOIN
		(
			SELECT 
				tm.id,
				tm.usn as tape_usn,
				tm.media_pool_id as media_pool_id,
				MAX(tbs.expiration_date) as expiration_date,
				MAX(tbs.usn) as backup_set_usn
			FROM [dbo].[Tape.tape_mediums] tm
			LEFT JOIN [dbo].[Tape.tape_medium_backup_sets] tmbs ON tmbs.tape_medium_id = tm.id
			LEFT JOIN [dbo].[Tape.backup_sets] tbs ON tmbs.backup_set_id = tbs.id
			GROUP BY tm.id, tm.media_pool_id, tm.usn
		) as exp_date ON exp_date.id = miv.media_id
		LEFT JOIN [dbo].[Tape.media_pools] mp ON exp_date.media_pool_id = mp.id
GO

PRINT N'Creating [dbo].[WmiServer.GuestDatabaseView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.GuestDatabaseView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.GuestDatabaseView]
GO
	CREATE VIEW [dbo].[WmiServer.GuestDatabaseView]
	AS
		SELECT
			gdb.id,
			s.server_name,
			s.db_instance,
			s.[db_name],
			gdb.usn
		FROM [dbo].[Backup.Model.GuestDatabase] gdb
		JOIN dbo.[Backup.Model.GuestDatabaseSensitiveData] s ON s.sql_guest_db_id = gdb.id
GO

PRINT N'Creating [dbo].[WmiServer.TapeLibraryView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeLibraryView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeLibraryView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeLibraryView]
	AS
		SELECT 
			tl.id,
			ln.name as name,
			el.[location_id],
			tl.tape_server_id,
			[dbo].[MaxValue2](tl.usn, el.usn) as usn
		FROM [dbo].[Tape.libraries] tl
		LEFT JOIN [dbo].[Tape.library_names] ln ON tl.id = ln.id
		LEFT JOIN [dbo].[EntityLocations] el ON el.[entity_id] = tl.id AND el.[entity_type] = 6
GO

PRINT N'Creating [dbo].[WmiServer.TenantRepositoryView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TenantRepositoryView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TenantRepositoryView]
GO
	CREATE VIEW [dbo].[WmiServer.TenantRepositoryView]
	AS
		SELECT 
			trq.id,
			trq.[tenantId] as tenant_id,
			trq.[name] as repository_name,
			trq.[repositoryId] as repository_id,
			trq.[quotaBytes] / 1024 / 1024 as quota_mb,
			trq.[usedBytes] / 1024 / 1024 as used_quota_mb,
			--ReportCloudTenantsView -> backupCount
            vmscount = (SELECT COUNT(DISTINCT lic_instances.id) 
						FROM [dbo].[Licensing.CC.BackupsOnQuotas] backup_quotas
						JOIN [dbo].[TenantQuotaView] tenant_quota ON backup_quotas.resource_quota_id = tenant_quota.id
						JOIN [dbo].[Licensing.LicensedInstances] lic_instances on lic_instances.id = backup_quotas.licensed_id
						LEFT JOIN [dbo].[Licensing.CC.CommonExtensions] ext ON ext.id = lic_instances.id 
						WHERE tenant_quota.[id] = trq.[id] AND
							  lic_instances.platform = 10000 AND --backup_platform
							  ext.ep_license_mode IS NULL),	
								
            serverCount = (SELECT COUNT(lic_instances.id)
						   FROM [dbo].[Licensing.CC.BackupsOnQuotas] agent_quotas
						   INNER JOIN [dbo].[TenantQuotaView] trq1 ON agent_quotas.resource_quota_id = trq.id
						   INNER JOIN [dbo].[Licensing.LicensedInstances] lic_instances on lic_instances.id  = agent_quotas.licensed_id
						   LEFT JOIN [dbo].[Licensing.CC.CommonExtensions] ext ON ext.id = lic_instances.id 
						   WHERE trq1.[id] = trq.[id] AND ext.ep_license_mode = 1),

			workstationCount = (SELECT COUNT(lic_instances.id)
						   FROM [dbo].[Licensing.CC.BackupsOnQuotas] agent_quotas
						   INNER JOIN [dbo].[TenantQuotaView] trq1 ON agent_quotas.resource_quota_id = trq.id
						   INNER JOIN [dbo].[Licensing.LicensedInstances] lic_instances on lic_instances.id  = agent_quotas.licensed_id
						   LEFT JOIN [dbo].[Licensing.CC.CommonExtensions] ext ON ext.id = lic_instances.id 
						   WHERE trq1.[id] = trq.[id] AND ext.ep_license_mode = 2),
			activity.[last_date] as lastactive,
			[dbo].MaxValue2(trq.usn, activity.usn) as usn
		FROM [dbo].[TenantQuotaView] trq
		LEFT JOIN (			
			SELECT 
				trq.[tenantId],
				trq.[repositoryId],
				MAX(js.[end_time]) as last_date, 
				MAX(js.[usn]) as usn
			FROM [dbo].[TenantQuotaView] trq
			JOIN [dbo].[Backup.Model.CloudSessionsOnQuotas] cs2q ON cs2q.[quota_id] = trq.[id]
			JOIN [dbo].[Backup.Model.CloudSessions] cs ON cs.id = cs2q.[session_id]
			JOIN [dbo].[Backup.Model.JobSessions] js ON cs.id = js.id
			WHERE cs.session_type <> 3 -- ECloudSessionType
			GROUP BY trq.[tenantId], trq.[repositoryId]
		) as activity ON activity.[tenantId] = trq.[tenantId] AND trq.[repositoryId] = activity.[repositoryId]
GO


PRINT N'Creating [dbo].[WmiServer.CloudGatewayView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudGatewayView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudGatewayView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudGatewayView]
	AS
		SELECT
			cg.[id]
			,cg.[host_id]
			,cg.[name]
			,cg.[options]
			,cg.[disabled]
			,dbo.MaxValue2(cg.[usn], h.[usn]) as usn
            ,[dbo].[fn.IsHostUpgradeRequired](cg.[host_id]) AS [component_is_out_of_date]
			,gate_component.[id] as gate_service_id
			,installer_component.[id] as installer_service_id
			,gateway_pool_id
		FROM [dbo].[Backup.Model.CloudGates] cg 
		LEFT JOIN [dbo].[Hosts] h ON cg.[host_id] = h.id
		LEFT JOIN [dbo].[HostComponents] gate_component ON h.[physical_host_id] = gate_component.[physical_host_id] AND gate_component.[type] = 7
		LEFT JOIN [dbo].[HostComponents] installer_component ON h.[physical_host_id] = installer_component.[physical_host_id] AND installer_component.[type] = 3
GO

PRINT N'Creating [dbo].[WmiServer.CloudTenantView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudTenantView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudTenantView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudTenantView]
	AS
		SELECT 
			id, 
			name, 
			expire_time,
			[type],
			usn 
		FROM [Tenants]
GO

PRINT N'Creating [dbo].[WmiServer.CloudTenantVersionInfoView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudTenantVersionInfoView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudTenantVersionInfoView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudTenantVersionInfoView]
	AS
		SELECT 
			cs.tenant_id as id,
			cs.tenant_id, 
			cs.protocolVersion,
			cs.productId,
			cs.productVersion,
			[dbo].[MaxValue2](cs.[usn], last_tenant_session.usn) as usn
		FROM [Backup.Model.CloudSessions] cs
		JOIN (
			SELECT tenant_id, max(usn) as usn
			FROM [Backup.Model.CloudSessions]
			GROUP BY tenant_id
		) last_tenant_session ON cs.tenant_id = last_tenant_session.tenant_id AND cs.usn = last_tenant_session.usn
GO

PRINT N'Creating [dbo].[WmiServer.TapeVaultView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.TapeVaultView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.TapeVaultView]
GO
	CREATE VIEW [dbo].[WmiServer.TapeVaultView]
	AS
		SELECT 
			mv.id,
			mv.name as vault_name,
			el.[location_id],
			[dbo].[MaxValue2](mv.usn, el.usn) as usn
		FROM [dbo].[Tape.media_vaults] mv
		LEFT JOIN [dbo].[EntityLocations] el ON el.[entity_id] = mv.[id] AND el.[entity_type] = 7
GO

PRINT N'Creating [dbo].[WmiServer.DedupStorageWmiView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.DedupStorageWmiView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.DedupStorageWmiView]
GO
	CREATE VIEW [dbo].[WmiServer.DedupStorageWmiView]
	AS
		SELECT 
			repo.[id],
			repo.[id] as repo_id,
			repo.[type],
			repo.[path]
		FROM
			[dbo].[BackupRepositories] repo
		WHERE
			repo.[type] IN (3, 6, 9, 18) -- CBackupRepositoryInfo.Type
GO

PRINT N'Creating [dbo].[WmiServer.ProxyAttachedDisksView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ProxyAttachedDisksView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ProxyAttachedDisksView]
GO
	CREATE VIEW [dbo].[WmiServer.ProxyAttachedDisksView]
	AS
		SELECT 
			d.id, 
			d.diskId,
			d.usn
		FROM [Disks] d
			JOIN [PhysHost_Disk] phd ON phd.disk_id = d.id
			JOIN [Hosts] h ON h.[physical_host_id] = phd.[physhost_id]
			JOIN [BackupProxies] p ON p.[host_id] = h.id 
		WHERE p.[type] = 0
GO

PRINT N'Creating [dbo].[WmiServer.CloudGatewayStatisticView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudGatewayStatisticView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudGatewayStatisticView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudGatewayStatisticView]
	AS
		SELECT 
			[id],
			[time],
			[tenant_id],
			[installation_id],
			[gate_id],
			[data_sent_to_client],
			[data_sent_by_client],
			[usn]
		FROM [dbo].[Stats.CloudGateways]
GO

PRINT N'Creating [dbo].[WmiServer.WanAcceleratorStatisticView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.WanAcceleratorStatisticView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.WanAcceleratorStatisticView]
GO
	CREATE VIEW [dbo].[WmiServer.WanAcceleratorStatisticView]
	AS
		SELECT 
			wa.[id],
			wa.[time],
			wa.[tenant_id],
			wa.[installation_id],
			wa.[source_accelerator_id],
			wa.[source_accelerator_db_id],
			wa.[target_accelerator_id],
			wa.[transferred_data],
			wa.[written_data],
			wa.[usn]
		FROM [dbo].[Stats.WanAccelerators] wa
GO

PRINT N'Creating [dbo].[WmiServer.CloudProvidersView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudProvidersView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudProvidersView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudProvidersView]
	AS
		SELECT 
			cs.[id],
			cs.[name],
			cs.[is_robocoped],
			el.[location_id],
			c.[user_name] as tenant_name,
			tc.[raw_data],
			tc.[flags],
			(
				SELECT ISNULL(t.data, '<CloudGates />')
				FROM
				(
					SELECT 
						cg.[ip_addr] as Ip,
						cg.[port] as Port,
						cg.[priority] as [Priority]
					FROM [dbo].[Backup.Model.CloudProviderGates] cg
					WHERE cg.[cloud_provider_id] = cs.[id]
					FOR XML RAW ('CloudGate'), ROOT ('CloudGates')
				) AS t(data)
			) as gate_list,
			[dbo].[MaxValue3](cs.[usn], c.usn, el.[usn]) as usn
		FROM [dbo].[Backup.Model.CloudProviders] cs
		JOIN [dbo].[Credentials] c ON cs.creds_id = c.id
		LEFT JOIN [dbo].[Backup.Model.TrustedCertificates] tc ON tc.[id] = cs.[cert_id]
		LEFT JOIN [dbo].[EntityLocations] el ON el.[entity_id] = cs.id
GO
 
PRINT N'Creating [dbo].[WmiServer.ExtendableRepositoryExtentView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExtendableRepositoryExtentView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExtendableRepositoryExtentView]
GO
	CREATE VIEW [dbo].[WmiServer.ExtendableRepositoryExtentView]
	AS
		SELECT
			er.[id],
			er.[meta_repo_id],
			er.[dependant_repo_id],
			er.[options],
			br.[status],
			[dbo].[MaxValue2](br.[usn], er.[usn]) as usn	
		FROM [dbo].[Backup.ExtRepo.ExtRepos] er
		JOIN [dbo].[BackupRepositories] br ON er.[dependant_repo_id] = br.[id]
		WHERE br.[type] IN (0, 1, 2, 3, 4, 6, 9, 10)
GO
 
PRINT N'Creating [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]
GO
	CREATE VIEW [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]
	AS
		SELECT
			er.[id],
			er.[meta_repo_id],
			er.[dependant_repo_id],
			er.[options],
			er.[usn]
		FROM [dbo].[Backup.ExtRepo.ExtRepos] er
		JOIN [dbo].[BackupRepositories] br ON er.[dependant_repo_id] = br.[id]
		WHERE br.[type] IN (11, 12, 13, 14, 15)
GO

PRINT N'Creating [dbo].[WmiServer.ReplicationJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ReplicationJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ReplicationJobsView]	
GO
	CREATE VIEW [dbo].[WmiServer.ReplicationJobsView]
	AS
		SELECT
			jobs.[id],
			jobs.[usn],
			jobs.[options],
			jobs.[target_type],
			jobs.[target_host_id],
			source_wan.[accelerator_id] as source_wan_id,
			target_wan.[accelerator_id] as target_wan_id
		FROM
			[dbo].[BJobs] jobs
		LEFT JOIN [dbo].[Backup.Model.JobWanAccelerators] source_wan ON jobs.id = source_wan.job_id AND source_wan.type = 0 AND source_wan.[accelerator_id] <> '00000000-0000-0000-0000-000000000000'
		LEFT JOIN [dbo].[Backup.Model.JobWanAccelerators] target_wan ON jobs.id = target_wan.job_id AND target_wan.type = 1 AND target_wan.[accelerator_id] <> '00000000-0000-0000-0000-000000000000'
		WHERE
			jobs.[type] = 1
GO

PRINT N'Creating [dbo].[WmiServer.CloudHardwarePlansView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudHardwarePlansView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudHardwarePlansView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudHardwarePlansView]
	AS
		SELECT
			vhp.[id],
			vhp.[friendlyName],
			0 as platform, --EPlatform.EVmware
			vhp.[hypervisorHostId] as host_id,
			vhp.[parentReference] as reference,
			vhp.[processorUsageLimitMhz] as cpu_usage_mhz,
			vhp.[memoryUsageLimitMb] as ram_usage_mb,
			vhpn.[countWithInternent],
			vhpn.[countWithoutInternent],
			dbo.MaxValue2(vhp.usn, vhpn.usn) as usn
		FROM [dbo].[Backup.Model.ViHardwarePlans] vhp
		JOIN [dbo].[Backup.Model.ViHardwarePlanNetworks] vhpn ON vhpn.[hardwarePlanId] = vhp.[id]
		UNION ALL
		SELECT
			hhp.[id],
			hhp.[friendlyName],
			1 as platform, --EPlatform.EHyperV
			hhp.[hypervisorHostId] as host_id,
			null as reference,
			hhp.[processorUsageLimitCores] as cpu_usage_mhz,
			hhp.[memoryUsageLimitMb] as ram_usage_mb,
			hhpn.[countWithInternent],
			hhpn.[countWithoutInternent],
			dbo.MaxValue2(hhp.usn, hhpn.usn) as usn
		FROM [dbo].[Backup.Model.HvHardwarePlans] hhp
		JOIN [dbo].[Backup.Model.HvHardwarePlanNetworks] hhpn ON hhpn.[hardwarePlanId] = hhp.[id]
GO

PRINT N'Creating [dbo].[WmiServer.CloudHardwarePlanStoragesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudHardwarePlanStoragesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudHardwarePlanStoragesView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudHardwarePlanStoragesView]
	AS
		SELECT
			id,
			hardwarePlanId,
			quotaGb,
			friendlyName as storage_name,
			usn
		FROM [dbo].[Backup.Model.HvHardwarePlanVolumes]
		UNION ALL
		SELECT
			id,
			hardwarePlanId,
			quotaGb,
			friendlyName as storage_name,
			usn
		FROM [dbo].[Backup.Model.ViHardwarePlanDatastores]
GO

PRINT N'Creating [dbo].[WmiServer.CloudHardwarePlanViStoragesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudHardwarePlanViStoragesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudHardwarePlanViStoragesView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudHardwarePlanViStoragesView]
	AS
		SELECT
			id,
			reference,
			usn
		FROM [dbo].[Backup.Model.ViHardwarePlanDatastores]
GO

PRINT N'Creating [dbo].[WmiServer.CloudHardwarePlanHvVolumesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudHardwarePlanHvVolumesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudHardwarePlanHvVolumesView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudHardwarePlanHvVolumesView]
	AS
		SELECT
			id,
			volumePath,
			usn
		FROM [dbo].[Backup.Model.HvHardwarePlanVolumes]
GO

PRINT N'Creating [dbo].[WmiServer.HardwarePlan2TenantView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.HardwarePlan2TenantView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.HardwarePlan2TenantView]
GO
	CREATE VIEW [dbo].[WmiServer.HardwarePlan2TenantView]
	AS
		SELECT hardwarePlanId, tenantId FROM [dbo].[Backup.Model.HvHardwareQuotas]
		UNION ALL
		SELECT hardwarePlanId, tenantId FROM [dbo].[Backup.Model.ViHardwareQuotas]
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantWareReplicaView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantWareReplicaView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantWareReplicaView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantWareReplicaView]
	AS
		SELECT 
			repl.[id],
			repl.[target_vm_name] as repl_vm_name,
			repl.[target_vm_ref] as repl_vm_ref,
			repl.[target_location] as repl_location,
			repl.[object_id],
			repl.[usn],
			vihq.tenantId as tenant_id,
			vihq.hardwarePlanId as hardware_plan_id,
			config.[cpuCount] as cpu_count,
			config.[memoryMb] as memory_mb
		FROM dbo.Replicas repl
		LEFT JOIN [dbo].[Backup.Model.ViCloudTenantBackups] vicb ON vicb.backup_id = repl.backup_id
		LEFT JOIN [dbo].[Backup.Model.ViHardwareQuotas] vihq ON vicb.quota_id = vihq.id
		JOIN [dbo].[ReplicaConfigurations] config ON repl.[id] = config.[id]
		WHERE vicb.backup_id IS NOT NULL
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantVcdReplicaView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantVcdReplicaView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantVcdReplicaView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantVcdReplicaView]
	AS
		SELECT 
			repl.[id],
			repl.[target_vm_name] as repl_vm_name,
			repl.[target_vm_ref] as repl_vm_ref,
			repl.[target_location] as repl_location,
			repl.[object_id],
			repl.[usn],
			vcdhq.tenantId as tenant_id,
			config.[cpuCount] as cpu_count,
			config.[memoryMb] as memory_mb
		FROM dbo.Replicas repl
		JOIN [dbo].[Backup.Model.VcdCloudTenantBackups] vcdcb ON vcdcb.backup_id = repl.backup_id
		JOIN [dbo].[CC.ViDirector.DataCenters] vcdhq ON vcdcb.quota_id = vcdhq.id
		JOIN [dbo].[ReplicaConfigurations] config ON repl.[id] = config.[id]
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantVcdReplicaResourcesUsageView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantVcdReplicaResourcesUsageView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantVcdReplicaResourcesUsageView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantVcdReplicaResourcesUsageView]
	AS
		WITH storage_policies_usage_info as 
		(
			SELECT sp.datacenterId,
				   SUM(sp.quotaGb) AS total_quota_gb,
				   SUM(sp.usedBytes) AS total_used_bytes
			FROM [dbo].[CC.ViDirector.StoragePolicies] sp
			GROUP BY sp.datacenterId
		)    
		SELECT  
			dc.[id],
			dc.[tenantId],
			dc.[vcHostId],
			dc.datacenterName,
			dc.[datacenterReference],
			sp.total_quota_gb AS storage,
			sp.total_used_bytes AS storage_usages_bytes,
			dc.[usn]
		FROM [dbo].[CC.ViDirector.DataCenters] dc
		LEFT JOIN storage_policies_usage_info sp ON sp.datacenterId = dc.id
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantWareReplicaStorageUsageView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantWareReplicaStorageUsageView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantWareReplicaStorageUsageView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantWareReplicaStorageUsageView]
	AS
		SELECT 
			usage.id,
			usage.replicaId as replica_id, 
			usage.usageBytes,
			q.[hardwarePlanDatastoreId] as datastore_id,
			usage.usn
		FROM [dbo].[Backup.Model.ViHardwareQuotaDatastoreUsages] usage
		JOIN [dbo].[Backup.Model.ViHardwareQuotaDatastores] q ON usage.[hardwareDatastoreQuotaId] = q.id
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantHyperVReplicaStorageUsageView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantHyperVReplicaStorageUsageView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantHyperVReplicaStorageUsageView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantHyperVReplicaStorageUsageView]
	AS
		SELECT 
			usage.id,
			usage.replicaId as replica_id, 
			usage.usageBytes,
			q.[hardwarePlanVolumeId] as datastore_id,
			usage.usn
		FROM [dbo].[Backup.Model.HvHardwareQuotaVolumeUsages] usage
		JOIN [dbo].[Backup.Model.HvHardwareQuotaVolumes] q ON usage.[hardwareVolumeQuotaId] = q.id
GO

PRINT N'Creating [dbo].[WmiServer.VmInTenantHyperVReplicaView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.VmInTenantHyperVReplicaView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.VmInTenantHyperVReplicaView]
GO
	CREATE VIEW [dbo].[WmiServer.VmInTenantHyperVReplicaView]
	AS
		SELECT 
			repl.[id],
			repl.[target_vm_name] as repl_vm_name,
			repl.[target_vm_ref] as repl_vm_ref,
			repl.[target_location] as repl_location,
			repl.[object_id],
			repl.[usn],
			vihq.tenantId as tenant_id,
			vihq.hardwarePlanId as hardware_plan_id,
			config.[cpuCount] as cpu_count,
			config.[memoryMb] as memory_mb
		FROM dbo.Replicas repl
		LEFT JOIN [dbo].[Backup.Model.HvCloudTenantBackups] vicb ON vicb.backup_id = repl.backup_id
		LEFT JOIN [dbo].[Backup.Model.HvHardwareQuotas] vihq ON vicb.quota_id = vihq.id
		JOIN [dbo].[ReplicaConfigurations] config ON repl.[id] = config.[id]
		WHERE vicb.backup_id IS NOT NULL
GO

PRINT N'Creating [dbo].[WmiServer.ExtendableBackupRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExtendableBackupRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExtendableBackupRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.ExtendableBackupRepositoriesView]
	AS	
		SELECT
			r.[id],
			r.[options],
			settings.[encrypt_archived_data],
			settings.[advanced_options],
			[dbo].[MaxValue2](r.[usn], settings.[usn]) as usn
		FROM [dbo].[BackupRepositories] r 
		LEFT JOIN [dbo].[BackupRepositories.ArchiveSettings] settings ON settings.repository_id = r.id
		WHERE r.[type] = 10 --ExtendableRepository
GO

PRINT N'Creating [dbo].[WmiServer.WanAcceleratorMetricsStatistic]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.WanAcceleratorMetricsStatistic]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.WanAcceleratorMetricsStatistic]
GO
	CREATE VIEW [dbo].[WmiServer.WanAcceleratorMetricsStatistic]
	AS	
		SELECT
			[id],
			[time],
			[accelerator_id],
			[cache_size],
			[usn]
		FROM [dbo].[Stats.WanAcceleratorMetrics]
GO

PRINT N'Creating [dbo].[WmiServer.RoleAccountsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RoleAccountsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RoleAccountsView]
GO
	CREATE VIEW [dbo].[WmiServer.RoleAccountsView]
	AS	
		SELECT 
			ra.[id],
			acc.[nt4_name],
			acc.[sid],
			acc.[type],
			CASE 
				WHEN r.[name] = 'Veeam Backup Administrator' THEN 0
				WHEN r.[name] = 'Veeam Backup Viewer' THEN 1
				WHEN r.[name] = 'Veeam Restore Operator' THEN 2
				WHEN r.[name] = 'Veeam Backup Operator' THEN 3
				WHEN r.[name] = 'Veeam Tape Operator' THEN 4
			END
			as [role]
		FROM [dbo].[Backup.Security.Accounts] acc
		JOIN [dbo].[Backup.Security.RoleAccounts] ra ON acc.[id] = ra.[account_id]
		JOIN [dbo].[Backup.Security.Roles] r ON ra.[role_id] = r.[id]
		WHERE acc.[type] IN (1, 2)
GO

PRINT N'Creating [dbo].[WmiServer.RuntimeSobrInfo]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RuntimeSobrInfo]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RuntimeSobrInfo]
GO
	CREATE VIEW [dbo].[WmiServer.RuntimeSobrInfo]
	AS	
		SELECT
			[meta_repo_id] as sobr_id, 
			h.*
		FROM [dbo].[Backup.ExtRepo.ExtRepos] ext
		JOIN [dbo].[BackupRepositories] br ON ext.[dependant_repo_id] = br.[id]
		JOIN [dbo].[Hosts] h ON (
			br.[host_id] = h.[id] AND br.[type] <> 2 OR
			h.[id] = '6745A759-2205-4CD2-B172-8EC8F7E60EF8' AND br.[type] = 2 --CIFS
			)
GO

-- [WmiServer.SbVirtualLabView]
PRINT N'Creating [dbo].[WmiServer.SbVirtualLabView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SbVirtualLabView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SbVirtualLabView]
GO
	CREATE VIEW [dbo].[WmiServer.SbVirtualLabView]
	AS
		SELECT 
			[id],
			[name],
			[description],
			[vm_ref],
			[usn],
			[platform],
			[host_id]
		FROM [dbo].[VirtualLabs]
GO

-- [WmiServer.CloudSubtenantView]
PRINT N'Creating [dbo].[WmiServer.CloudSubtenantView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudSubtenantView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudSubtenantView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudSubtenantView]
	AS
		SELECT 
			subt.id, 
			subt.name, 
			subt.tenantId as tenant_id,
			ten.name as tenant_name,
			quot.quotaBytes as quota_bytes,
			quot.usedBytes as used_bytes,			
			subt.isDisabled as is_disabled,	
			quot_sub.isUnlimited as is_quota_unlimited,					
			subt.usn
		FROM [dbo].[Subtenants] subt
		JOIN [dbo].[Tenants] ten ON subt.tenantId = ten.id
		JOIN [dbo].[Quotas.Subtenant] quot_sub ON subt.id = quot_sub.[subtenantId]
		JOIN [dbo].[Quotas] quot ON quot.id = quot_sub.id
		WHERE quot.type = 5
GO

-- [WmiServer.Associations.SubtenantToRepositoryView]
PRINT N'Creating [dbo].[WmiServer.Associations.SubtenantToRepositoryView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.Associations.SubtenantToRepositoryView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.Associations.SubtenantToRepositoryView]
GO
	CREATE VIEW [dbo].[WmiServer.Associations.SubtenantToRepositoryView]
	AS
		SELECT 
		subt.id as left_id,
		repos.id as right_id
		FROM [dbo].[Subtenants] subt
		JOIN [dbo].[WmiServer.TenantRepositoryView] repos ON subt.tenantId = repos.tenant_id
GO

-- [WmiServer.CloudHostsView]
PRINT N'Creating [dbo].[WmiServer.CloudHostsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudHostsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudHostsView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudHostsView]
	AS
		SELECT 
			id,
			friendlyName,
			usn
		FROM [dbo].[Backup.Model.CloudConnectHosts]
GO

-- [WmiServer.CloudRepositoryView]
PRINT N'Creating [dbo].[WmiServer.CloudHostsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudRepositoryView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudRepositoryView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudRepositoryView]
	AS
		SELECT 
			br.[id],
			cr.[provider_id],
			br.[usn]
		FROM [dbo].[Backup.Model.CloudRepositories] cr
		JOIN [dbo].[BackupRepositories] br ON cr.[repository_id] = br.[id]
GO

--------------------------------------------------------------------------------
-- [WmiServer.AgentsView]
PRINT N'Creating [dbo].[WmiServer.AgentsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.AgentsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.AgentsView]
GO
	CREATE VIEW [dbo].[WmiServer.AgentsView]
	AS
		SELECT			
			ep.id,
			ep.[machine_name],
			ep.[platform] as os_platform,
			ep.[os_architecture],
			ep.[agent_installation_status],
			ep.[aux_data],
			ep.[display_name],
			ep.[is_cluster],
			ep.[parent_cluster] as parent_cluster_id,
			eiv.[license_mode] as license_mode,
			[dbo].[MaxValue2](ep.[usn], eiv.[usn]) as usn
		FROM [Backup.Model.EpAgentInfo] ep
		LEFT JOIN [dbo].[Licensing.EndpointInstancesView] eiv On ep.bobject_id = eiv.bObject_id		
GO

--------------------------------------------------------------------------------
-- [WmiServer.AgentBackupsView]
PRINT N'Creating [dbo].[WmiServer.AgentBackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.AgentBackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.AgentBackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.AgentBackupsView]
	AS
		SELECT DISTINCT
			b.id as backup_id, 
			ep.id as agent_id
		FROM [Backup.Model.Backups] b
		JOIN [Backup.Model.Points] p ON b.id = p.backup_id
		JOIN [Backup.Model.OIBs] oib ON oib.point_id = p.id
		JOIN [Backup.Model.EpAgentInfo] ep ON oib.[object_id] = ep.[bObject_id]
		WHERE ep.[platform] = 6 --EPlatform.EEndPoint
		UNION
		SELECT
			b.id as backup_id, 
			ep.id as agent_id
		FROM [Backup.Model.EpAgentInfo] ep
		JOIN [BObjects] bo ON ep.[bobject_id] = bo.[id]
		JOIN [BObjects] bo_child ON bo_child.[parent_id] = bo.[id]
		JOIN [Backup.Model.OIBs] oib ON oib.[object_id] = bo_child.[id]
		JOIN [Backup.Model.Points] p ON oib.point_id = p.id
		JOIN [Backup.Model.Backups] b ON b.id = p.backup_id
		WHERE ep.[platform] = 7 --EPlatform.ELinuxPhysical
GO

PRINT N'Creating [dbo].[WmiServer.EpJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.EpJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.EpJobsView]	
GO
	CREATE VIEW [dbo].[WmiServer.EpJobsView]
	AS
		SELECT
			jobs.[id],
			jobs.[options],
			jobs.[target_dir],
			jobs.[usn]
		FROM [dbo].[BJobs] jobs
		WHERE jobs.[type] IN 
		(
			12002,--EpAgentPolicy
			12003--EpAgentBackup
		)
GO

PRINT N'Creating [dbo].[WmiServer.EpWorkerJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.EpWorkerJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.EpWorkerJobsView]	
GO
	CREATE VIEW [dbo].[WmiServer.EpWorkerJobsView]
	AS
		SELECT
			jobs.[id],
			jobs.[parent_job_id],
			jobs.[usn]
		FROM [dbo].[BJobs] jobs
		WHERE jobs.[parent_job_id] IS NOT NULL 
			AND jobs.[type] IN
			(
				4000, --for managed by agent
				12000-- EpAgentManagement, for managed by VBR
			)
GO

PRINT N'Creating [dbo].[WmiServer.LocationView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.LocationView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.LocationView]	
GO
	CREATE VIEW [dbo].[WmiServer.LocationView]
	AS
		SELECT
			[id],
			[name],
			[usn]
		FROM [dbo].[Locations] 
GO

PRINT N'Creating [dbo].[WmiServer.ProtectedComputersView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ProtectedComputersView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ProtectedComputersView]	
GO
	CREATE VIEW [dbo].[WmiServer.ProtectedComputersView]
	AS
		SELECT
			c.[id],
			[name],
			el.[location_id],
			[dbo].[MaxValue2](c.[usn], el.[usn]) as usn
		FROM [dbo].[EpContainers] c
		LEFT JOIN [dbo].[EntityLocations] el ON el.[entity_id] = c.[id]
		WHERE c.[type] = 1 --EEpContainerType.VeeamContainer
GO

-- [WmiServer.ProtectedComputersGroupInJobsView]
PRINT N'Creating [dbo].[WmiServer.ProtectedComputersGroupInJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ProtectedComputersGroupInJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ProtectedComputersGroupInJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.ProtectedComputersGroupInJobsView]
	AS
		SELECT
			oij.[id] as id,
			oij.[job_id],
			c.[id] as group_id,
			oij.[usn]
		FROM [dbo].[ObjectsInJobs] oij
		JOIN [dbo].[BJobs] bj ON oij.[job_id] = bj.[id]
		JOIN [dbo].[EpContainers] c ON c.bobject_id = oij.[object_id]
		WHERE bj.[platform] IN (6, 7)
GO

-- [WmiServer.DomainProtectedGroupsView]
PRINT N'Creating [dbo].[WmiServer.DomainProtectedGroupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.DomainProtectedGroupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.DomainProtectedGroupsView]
GO
	CREATE VIEW [dbo].[WmiServer.DomainProtectedGroupsView]
	AS
		SELECT 
		adObjects.id,
		adDomains.dc_address,
		adDomains.dc_port,
		c.[parent_id],
		adObjects.[usn]
	FROM [dbo].[Backup.Model.AdObjects] adObjects
	LEFT JOIN [dbo].[Backup.Model.AdDomains] adDomains ON adDomains.[id] = adObjects.[domain_id]
	JOIN [dbo].[EpContainers] c ON adObjects.id = c.[extension_id]
GO

-- [WmiServer.CsvFileProtectedGroupsView]
PRINT N'Creating [dbo].[WmiServer.CsvFileProtectedGroupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CsvFileProtectedGroupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CsvFileProtectedGroupsView]
GO
	CREATE VIEW [dbo].[WmiServer.CsvFileProtectedGroupsView]
	AS
		SELECT
			csv.id,
			csv.file_path,
			ep.parent_id,
			csv.usn
		FROM [dbo].[CsvFiles] csv
		JOIN [dbo].[EpContainers] ep ON csv.id = ep.extension_id
GO

-- [WmiServer.ProtectedIndividualComputersView]
PRINT N'Creating [dbo].[WmiServer.ProtectedIndividualComputersView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ProtectedIndividualComputersView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ProtectedIndividualComputersView]
GO
	CREATE VIEW [dbo].[WmiServer.ProtectedIndividualComputersView]
	AS
		SELECT 
			c.id,
			c.name,
			c.parent_id,
			c.usn
		FROM [dbo].[EpContainers] c
		WHERE c.[type] = 2
GO

-- [WmiServer.HierarchyObjectLocationsView]
PRINT N'Creating [dbo].[WmiServer.HierarchyObjectLocationsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.HierarchyObjectLocationsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.HierarchyObjectLocationsView]
GO
	CREATE VIEW [dbo].[WmiServer.HierarchyObjectLocationsView]
	AS
		SELECT 
			el.[id],
			CASE 
				WHEN el.[entity_type] = 0 THEN el.[entity_id]
				WHEN el.[entity_type] IN (1, 2) THEN bo.[host_id]
			END as host_id,
			bo.[object_id] as reference,
			el.[location_id],
			dbo.MaxValue2(bo.usn, el.usn) as usn
		FROM [dbo].[EntityLocations] el
		LEFT JOIN [dbo].[BObjects] bo ON el.[entity_id] = bo.id
		WHERE el.[entity_type] IN (0, 1, 2)
GO

-- [WmiServer.OptionsView]
PRINT N'Creating [dbo].[WmiServer.OptionsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.OptionsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.OptionsView]
GO
	CREATE VIEW [dbo].[WmiServer.OptionsView]
	AS
		SELECT 
			MAX(usn) as usn
		FROM [dbo].[Options] bo
		WHERE id IN ('BE61EA36-42C1-4BDE-BE47-0F47A56D63F6', 'E452B26D-0A27-4910-8B6F-BD3C86FFDB74')
GO


--------------------------------------------------------------------------------
-- [WmiServer.EpBackupsContainersView]
PRINT N'Creating [dbo].[WmiServer.EpBackupsContainersView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.EpBackupsContainersView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.EpBackupsContainersView]
GO
	CREATE VIEW [dbo].[WmiServer.EpBackupsContainersView]
	AS
		SELECT
			backups.id,
			backups.job_name,
			backups.usn,
			backups.job_id,
			backups.repository_id
		FROM [dbo].[Backup.Model.Backups] backups WITH (NOLOCK)
		WHERE [job_target_type] IN (12002, 12003)
GO

--------------------------------------------------------------------------------
-- [WmiServer.EpBackupsView]
PRINT N'Creating [dbo].[WmiServer.EpBackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.EpBackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.EpBackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.EpBackupsView]
	AS
		SELECT
			backups.id,
			backups.[parent_backup_id],
			backups.[backup_policy_name],
			backups.usn
		FROM [dbo].[Backup.Model.Backups] backups WITH (NOLOCK)
		WHERE [job_target_type] IN (
			4000,--EndpointBackup
			12000--EpAgentManagement
			)
GO

--------------------------------------------------------------------------------
-- [WmiServer.MbaJobSessionView]
PRINT N'Creating [dbo].[WmiServer.MbaJobSessionView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.MbaJobSessionView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.MbaJobSessionView]
GO
	CREATE VIEW [dbo].[WmiServer.MbaJobSessionView]
	AS
		SELECT 
		   js.id,
		   bjs.backup_policy_tag,
		   taskSessions.[object_id],
		   bjs.usn
		FROM [Backup.Model.JobSessions] js
		JOIN [Backup.Model.BackupJobSessions] bjs ON bjs.id = js.id
		CROSS APPLY
		( 
			--VAL has parent and child bObjects and taskSessions
			SELECT TOP 1
				bts.[object_id]
			FROM [Backup.Model.BackupTaskSessions] bts 
			WHERE bts.session_id = js.id 
		) taskSessions
		WHERE js.[job_type] = 4000		
GO

--------------------------------------------------------------------------------
-- [WmiServer.AgentRestorePointsView]
PRINT N'Creating [dbo].[WmiServer.AgentRestorePointsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.AgentRestorePointsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.AgentRestorePointsView]
GO
	CREATE VIEW [dbo].[WmiServer.AgentRestorePointsView]
	AS			
		SELECT
			oib.id,
			oib.storage_id,
			oib.[product_version_flags],
			ep.id as agent_id,
			oib.[usn]
		FROM [Backup.Model.OIBs] oib
		LEFT JOIN [Backup.Model.EpAgentInfo] ep ON oib.[object_id] = ep.[bObject_id]
		WHERE ep.[platform] = 6 --EPlatform.EEndPoint
		UNION
		SELECT
			oib.id,
			oib.storage_id,
			oib.[product_version_flags],
			ep.id as agent_id,
			oib.[usn]
		FROM [Backup.Model.OIBs] oib
		JOIN [BObjects] bo_child ON oib.[object_id] = bo_child.[id]
		JOIN [BObjects] bo ON bo_child.[parent_id] = bo.[id]
		LEFT JOIN [Backup.Model.EpAgentInfo] ep ON ep.[bobject_id] = bo.[id]
		WHERE ep.[platform] = 7 --EPlatform.ELinuxPhysical
GO

--------------------------------------------------------------------------------
-- [WmiServer.AgentLicensesView]
PRINT N'Creating [dbo].[WmiServer.AgentLicensesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.AgentLicensesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.AgentLicensesView]
GO
	CREATE VIEW [dbo].[WmiServer.AgentLicensesView]
	AS
	SELECT
		[platform],
		[text],
		[usn]
	FROM [dbo].[Backup.Model.AgentsLicenses]
GO

---------------------------------
PRINT N'Creating [dbo].[WmiServer.JobSessionFailsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.JobSessionFailsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.JobSessionFailsView]
GO
	CREATE VIEW [dbo].[WmiServer.JobSessionFailsView]
    AS
          SELECT 
			js.id,
			(SELECT T.msg.value('.', 'nvarchar(max)') FROM js.log_xml.nodes('/Root/Log[@Status="EWarning"]/Title') as T(msg) FOR XML PATH('msg'), ROOT('root')) as warnings,
			(SELECT T.msg.value('.', 'nvarchar(max)') FROM js.log_xml.nodes('/Root/Log[@Status="EFailed"]/Title') as T(msg) FOR XML PATH('msg'), ROOT('root')) as failures,
			js.usn
          FROM [dbo].[Backup.Model.JobSessions] js
		  WHERE js.[result] in (1, 2) --CBaseSessionInfo.EResult.Warning OR CBaseSessionInfo.EResult.Failed
		  AND js.job_type IN (
			  0, 
			  1, 
			  2, 
			  3,
			  8, 
			  24,
			  28,
			  50,
			  51,
			  52,
			  54,
			  202,--FailoverPlan
			  203,--UndoFailoverPlan
			  4000,
			  12000,
			  12002,
			  12003
			  )
GO

--------------------------------------------------------------------------------
-- [WmiServer.MbaBackupStatisticView]
PRINT N'Creating [dbo].[WmiServer.MbaBackupStatisticView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.MbaBackupStatisticView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.MbaBackupStatisticView]
GO
	CREATE VIEW [dbo].[WmiServer.MbaBackupStatisticView]
	AS
	SELECT
	   [id],
	   [agent_id],
	   [policy_job_id] as policy_id,
	   [points_count],
	   [backup_size],
	   [sync_date_utc],
	   [usn]
	FROM [dbo].[Backup.Model.EpAgentBackupStats]
GO

---------------------------------
PRINT N'Creating [dbo].[WmiServer.SessionTaskFailsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.SessionTaskFailsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.SessionTaskFailsView]
GO
	CREATE VIEW [dbo].[WmiServer.SessionTaskFailsView]
    AS
          SELECT 
			bts.id,
			(SELECT T.msg.value('.', 'nvarchar(max)') FROM bts.log_xml.nodes('/Root/Log[@Status="EWarning"]/Title') as T(msg) FOR XML PATH('msg'), ROOT('root')) as warnings,
			(SELECT T.msg.value('.', 'nvarchar(max)') FROM bts.log_xml.nodes('/Root/Log[@Status="EFailed"]/Title') as T(msg) FOR XML PATH('msg'), ROOT('root')) as failures,
			bts.usn
          FROM [dbo].[Backup.Model.BackupTaskSessions] bts
		  WHERE bts.[status] in (2, 3) --ESessionStatus.Failed OR ESessionStatus.Warning
GO

-- [WmiServer.CloudBackupsView]
PRINT N'Creating [dbo].[WmiServer.CloudBackupsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudBackupsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudBackupsView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudBackupsView]
	AS
		SELECT
			backups.id,
			q2b.[installationId] as installation_id,
			q2t.[tenantId] as tenant_id,
			q2st.[subtenantId] as subtenant_id,
			[dbo].[MaxValue2](backups.usn, q.usn) as usn			
		FROM [dbo].[Backup.Model.Backups] backups WITH (NOLOCK)
		JOIN [dbo].[Quotas.Backup] q2b WITH (NOLOCK) ON q2b.[backupId] = backups.[id]
		JOIN [dbo].[Quotas] q WITH (NOLOCK) ON q.[id] = q2b.[id]
		LEFT JOIN [dbo].[Quotas.Tenant] q2t ON q.[id] = q2t.id
		LEFT JOIN [dbo].[Quotas.Subtenant] q2st ON q.[id] = q2st.[id]
		WHERE q.[type] IN (4, 5) --EQuotaType.Tenant OR EQuotaType.Subtenant
GO

PRINT N'Creating [dbo].[WmiServer.DataDomainRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.DataDomainRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.DataDomainRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.DataDomainRepositoriesView]
	AS
		SELECT * 
		FROM [WmiServer.BackupRepositoriesView] 
		WHERE repo_type = 3
GO

PRINT N'Creating [dbo].[WmiServer.CloudGatewayPoolsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.CloudGatewayPoolsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.CloudGatewayPoolsView]
GO
	CREATE VIEW [dbo].[WmiServer.CloudGatewayPoolsView]
	AS
		SELECT 
			id,
			name,
			[description],
			usn
		FROM [dbo].[CloudGatewayPools]
GO

PRINT N'Creating [dbo].[WmiServer.ArchiveRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ArchiveRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ArchiveRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.ArchiveRepositoriesView]
	AS
		SELECT 
			id,
			[type],
			[options],
			[total_space],
			ISNULL(repLimits.[used_space], -1) as used_space,
			[usn]
		FROM [dbo].[BackupRepositories] r
		LEFT JOIN [dbo].[BackupRepositories.LimitSettings] repLimits ON repLimits.[repository_id] = r.[id]
		WHERE r.[type] IN (11, 12, 14)
GO

PRINT N'Creating [dbo].[WmiServer.ExternalRepositoriesView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExternalRepositoriesView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExternalRepositoriesView]
GO
	CREATE VIEW [dbo].[WmiServer.ExternalRepositoriesView]
	AS
		SELECT 
			id,
			[type],
			[options],
			[end_point_key_id],
			[total_space],
			[usn]
		FROM [dbo].[BackupRepositories] r
		WHERE r.[type] IN (16, 17)
GO
 
PRINT N'Creating [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]
GO
	CREATE VIEW [dbo].[WmiServer.ExtendableRepositoryArchiveExtentView]
	AS
		SELECT
			er.[id],
			er.[meta_repo_id],
			er.[dependant_repo_id],
			er.[usn]
		FROM [dbo].[Backup.ExtRepo.ExtRepos] er
GO


PRINT N'Creating [dbo].[WmiServer.RepositoryBaseView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.RepositoryBaseView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.RepositoryBaseView]
GO
	CREATE VIEW [dbo].[WmiServer.RepositoryBaseView]
	AS
		SELECT 
			r.id,
			r.name,
			r.[description],
			r.[type],			
			location.[location_id],
			[dbo].[MaxValue2](r.usn, location.usn) as usn
		FROM [dbo].[BackupRepositories] r
		LEFT JOIN [dbo].[EntityLocations] location ON r.id = location.[entity_id] AND location.[entity_type] = 4
		WHERE r.[type] IN (0, 1, 2, 3, 4, 6, 9, 10, 11, 12, 13, 14, 16, 17, 18)
GO

PRINT N'Creating [dbo].[WmiServer.ExtendableRepositoryExtentBaseView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.ExtendableRepositoryExtentBaseView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.ExtendableRepositoryExtentBaseView]
GO
	CREATE VIEW [dbo].[WmiServer.ExtendableRepositoryExtentBaseView]
	AS
		SELECT
			er.[id],
			er.[meta_repo_id],
			er.[dependant_repo_id],
			er.[options],
			br.[status],
			[dbo].[MaxValue2](br.[usn], er.[usn]) as usn	
		FROM [dbo].[Backup.ExtRepo.ExtRepos] er
		LEFT JOIN [dbo].[BackupRepositories] br ON er.[dependant_repo_id] = br.[id]
		WHERE br.[type] IN (0, 1, 2, 3, 4, 6, 9, 10, 11, 12, 13, 14, 16, 17)
GO

PRINT N'Creating [dbo].[WmiServer.BackupRestorePointChunksView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupRestorePointChunksView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupRestorePointChunksView]
GO
	CREATE VIEW [dbo].[WmiServer.BackupRestorePointChunksView]
	AS
		SELECT es.id, es.storage_id, es.dependant_repo_id as extent_id, usn
		FROM [dbo].[Backup.ExtRepo.Storages] es 
		UNION
		SELECT sc.id, sc.storage_id, sc.extent_id, usn
		FROM [Backup.Model.StorageCopies] sc
GO

PRINT N'Creating [dbo].[WmiServer.BackupObjectsInJobsView]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WmiServer.BackupObjectsInJobsView]') AND type in (N'V'))
	DROP VIEW [dbo].[WmiServer.BackupObjectsInJobsView]
GO
	CREATE VIEW [dbo].[WmiServer.BackupObjectsInJobsView]
	AS
		SELECT 
			oij.id,
			oij.job_id,
			oij.order_no,
			oij.ex_options,
			--only for assotiation			
			oij.ex_options.value('(/ExOptions/SourceExOptions/SourceBackupId)[1]', 'uniqueidentifier') as source_backup_id,
			oij.usn
		FROM [dbo].[ObjectsInJobs] oij
		JOIN [dbo].[BJobs] bj ON bj.[id] = oij.[job_id]
		WHERE bj.[type] = 51
GO