﻿-------------------------------------------------------------------------------
-- DeleteQuota
PRINT N'Creating [dbo].[DeleteQuota]';
IF EXISTS ( SELECT 1 FROM sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[DeleteQuota]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[DeleteQuota];
GO

CREATE PROCEDURE [dbo].[DeleteQuota]
	@id UNIQUEIDENTIFIER,
    @usn BIGINT = NULL
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;    

    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END

    BEGIN TRANSACTION;

	DELETE [dbo].[Quotas.Subtenant] WHERE id = @id
	DELETE [dbo].[Quotas.Tenant] WHERE id = @id

	-- Delete childs
	DECLARE @childId UNIQUEIDENTIFIER;
	WHILE(1 = 1)
	BEGIN
		SET @childId = (SELECT TOP 1 [id] FROM [dbo].[Quotas.Parent] where parentId = @id);
		IF @childId IS NULL BREAK;
		EXEC [dbo].[DeleteQuota] @id = @childId, @usn = @usn
	END

	-- Reassign owner
	DECLARE @parentId UNIQUEIDENTIFIER;
	SET @parentId = (SELECT parentId FROM [dbo].[Quotas.Parent] WHERE id = @id);
	IF @parentId is not null
	BEGIN
		EXEC [dbo].[ChangeQuotaBackup] @id = @id, @newQuotaId = @parentId
		DELETE [dbo].[Quotas.Parent] WHERE id = @id
	END;

	DELETE [dbo].[Quotas.Repository] WHERE id = @id
	DELETE [dbo].[Quotas.VcdOrganization] WHERE id = @id
	DELETE [dbo].[Quotas] WHERE id = @id

	EXEC [dbo].[InsertTombStone] 'Quotas', @id, @usn

	COMMIT TRANSACTION;
    END;
GO

--------------------------------------------------------------------------------
-- QuotaView
PRINT N'Creating [dbo].[QuotaView]';
IF OBJECT_ID(N'[dbo].[QuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[QuotaView];
GO

	CREATE VIEW [dbo].[QuotaView]
AS
	SELECT
		q.id,
		q.type,
		q.name,
		q.description,
		q.quotaBytes,
		q.usedBytes,
		q.usn,
		qr.repositoryId,
		qp.parentId,
		qt.tenantId,
		qt.wanId,
		qs.subtenantId,
		qs.isUnlimited,		
		org.[organization_id],
		w.[workspace_id]
    FROM    [dbo].[Quotas] q
			LEFT JOIN [dbo].[Quotas.Repository] qr ON q.id = qr.id
			LEFT JOIN [dbo].[Quotas.Parent] qp ON q.id = qp.id
			LEFT JOIN [dbo].[Quotas.Tenant] qt ON q.id = qt.id
			LEFT JOIN [dbo].[Quotas.Subtenant] qs ON q.id = qs.id
			LEFT JOIN [dbo].[Quotas.VcdOrganization] org ON q.[id] = org.[id]
			LEFT JOIN [dbo].[Quotas.VSphereWorkspace] w ON q.[id] = w.[id]
GO

--------------------------------------------------------------------------------
-- RecursiveQuotaView
PRINT N'Creating [dbo].[RecursiveQuotaView]';
IF OBJECT_ID(N'[dbo].[RecursiveQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RecursiveQuotaView];
GO

	CREATE VIEW [dbo].[RecursiveQuotaView]
AS
    SELECT
		q.id,
		qc.parentId,
		CASE 
            WHEN qs.isUnlimited = 'TRUE'
               THEN CAST(9223372036854775807 as BIGINT)
               ELSE (q.quotaBytes - q.usedBytes) 
		END as availableBytes
    FROM    [dbo].[Quotas] q
			LEFT JOIN [dbo].[Quotas.Parent] qc ON q.id = qc.id
			LEFT JOIN [dbo].[Quotas.Subtenant] qs ON q.id = qs.id;
GO

-------------------------------------------------------------------------------
-- CalcAvailableBytesByQuotaId
PRINT N'Creating [dbo].[CalcAvailableBytesByQuotaId]';
IF EXISTS ( SELECT 1 FROM sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[CalcAvailableBytesByQuotaId]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[CalcAvailableBytesByQuotaId];
GO

CREATE PROCEDURE [dbo].[CalcAvailableBytesByQuotaId]
	@id UNIQUEIDENTIFIER
AS
BEGIN
	
	SET NOCOUNT ON;
   
	WITH x AS
	(
	  SELECT id, parentId, availableBytes
		FROM [dbo].[RecursiveQuotaView]
		WHERE id = @id
	  UNION ALL
	  SELECT y.id, y.parentId, y.availableBytes
		FROM x 
		INNER JOIN [dbo].[RecursiveQuotaView] as y ON y.id = x.parentId
	)

	SELECT CONVERT(BIGINT, MIN(availableBytes)) as availableBytes
	FROM x
	OPTION (MAXRECURSION 10);
END
GO

-------------------------------------------------------------------------------
--AddQuota
PRINT N'Creating [dbo].[AddQuota]';
IF EXISTS ( SELECT  1  FROM    sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[AddQuota]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[AddQuota];
GO
CREATE PROCEDURE [dbo].[AddQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
    @usn BIGINT = NULL
AS
BEGIN
	SET NOCOUNT ON;	
	
    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END

	INSERT INTO [dbo].[Quotas]
           ([id]
		   ,[type]
		   ,[name]
		   ,[description]
           ,[quotaBytes]
           ,[usedBytes]
           ,[usn])
     VALUES
           (@id, @type, @name, @description, @quotaBytes, @usedBytes, @usn)        

END
GO

-------------------------------------------------------------------------------
--UpdateQuota
PRINT N'Creating [dbo].[UpdateQuota]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[UpdateQuota]
GO
CREATE PROCEDURE [dbo].[UpdateQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@updatedCount int = 0 output,
    @usn BIGINT = NULL
AS
BEGIN
    
    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END

	-- [dbo].[Quotas] 
	UPDATE [dbo].[Quotas]
	SET  [name] = @name
		,[description] = @description
        ,[quotaBytes] = @quotaBytes
        --,[usedBytes] = @usedBytes -- LW: Destructive update
        ,[usn] = @usn
    WHERE  [id] = @id and type = @type;

	SET @updatedCount = @@ROWCOUNT
END
GO

-------------------------------------------------------------------------------
--AddRepositoryQuota
PRINT N'Creating [dbo].[AddRepositoryQuota]';
IF EXISTS ( SELECT  1  FROM    sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[AddRepositoryQuota]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[AddRepositoryQuota];
GO
CREATE PROCEDURE [dbo].[AddRepositoryQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@repositoryId uniqueidentifier,
    @usn BIGINT = NULL
AS
BEGIN
	SET NOCOUNT ON;	
    SET XACT_ABORT ON;
	
    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END

    BEGIN TRANSACTION;

	exec [dbo].[AddQuota] @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, @usn = @usn

	INSERT INTO [dbo].[Quotas.Repository]
           ([id]
           ,[repositoryId])
    VALUES
           (@id, @repositoryId)

	COMMIT TRANSACTION;
END
GO

-------------------------------------------------------------------------------
--UpdateRepositoryQuota
PRINT N'Creating [dbo].[UpdateRepositoryQuota]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateRepositoryQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[UpdateRepositoryQuota]
GO
CREATE PROCEDURE [dbo].[UpdateRepositoryQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@repositoryId uniqueidentifier,
	@updatedCount int = 0 output,
    @usn BIGINT = NULL
AS
BEGIN
    SET XACT_ABORT ON;

    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END
    
    BEGIN TRANSACTION;

	exec [dbo].[UpdateQuota] @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes,
						     @updatedCount = @updatedCount output, @usn = @usn

	IF @updatedCount <> 0
	BEGIN
        -- [dbo].[Quotas.Repository]
        UPDATE [dbo].[Quotas.Repository]
        SET [repositoryId] = @repositoryId
        WHERE [id] = @id;

        SET @updatedCount = @@ROWCOUNT
        IF @updatedCount = 0
        BEGIN
	        ROLLBACK TRANSACTION;
	        RAISERROR ('Not consistent data.', 11, 1); 
	        RETURN;
        END
	END

	COMMIT TRANSACTION;
END
GO

--------------------------------------------------------------------------------
-- RepositoryQuotaView
PRINT N'Creating [dbo].[RepositoryQuotaView]';
IF OBJECT_ID(N'[dbo].[RepositoryQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[RepositoryQuotaView];
GO

	CREATE VIEW [dbo].[RepositoryQuotaView]
AS
    SELECT
		q.id,
		q.type,
		q.name,
		q.description,
		q.quotaBytes,
		q.usedBytes,
		q.usn,
		qr.repositoryId
    FROM    [dbo].[Quotas.Repository] qr
            INNER JOIN [dbo].[Quotas] q ON q.id = qr.id;
GO

--------------------------------------------------------------------------------
--AddChildQuota
PRINT N'Creating [dbo].[AddChildQuota]';
IF EXISTS ( SELECT  1  FROM    sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[AddChildQuota]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[AddChildQuota];
GO
CREATE PROCEDURE [dbo].[AddChildQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@parentId uniqueidentifier,
    @usn BIGINT = NULL
AS
BEGIN
	SET NOCOUNT ON;	
    SET XACT_ABORT ON;

    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END
	
    BEGIN TRANSACTION;

	exec [dbo].[AddQuota] @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, @usn = @usn

	INSERT INTO [dbo].[Quotas.Parent]
           ([id]
           ,[parentId])
    VALUES
           (@id, @parentId)

	COMMIT TRANSACTION;
END
GO

-------------------------------------------------------------------------------
--UpdateChildQuota
PRINT N'Creating [dbo].[UpdateChildQuota]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateChildQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[UpdateChildQuota]
GO
CREATE PROCEDURE [dbo].[UpdateChildQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@parentId uniqueidentifier,
	@updatedCount int = 0 output,
    @usn BIGINT = NULL
AS
BEGIN
    SET XACT_ABORT ON;

    IF (@usn IS NULL)
    BEGIN
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
    END

    BEGIN TRANSACTION;

	exec [dbo].[UpdateQuota] @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes,
							 @updatedCount = @updatedCount output, @usn = @usn
	
	IF @updatedCount <> 0
	BEGIN
	    -- [dbo].[Quotas.Parent]
	    UPDATE [dbo].[Quotas.Parent]
	    SET [parentId] = @parentId
        WHERE [id] = @id;

	    SET @updatedCount = @@ROWCOUNT
	    IF @updatedCount = 0
	    BEGIN
		    ROLLBACK TRANSACTION;
		    RAISERROR ('Not consistent data.', 11, 1); 
		    RETURN;
	    END
	END

	COMMIT TRANSACTION;
END
GO

--------------------------------------------------------------------------------
-- ChildQuotaView
PRINT N'Creating [dbo].[ChildQuotaView]';
IF OBJECT_ID(N'[dbo].[ChildQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[ChildQuotaView];
GO

	CREATE VIEW [dbo].[ChildQuotaView]
AS
    SELECT
		q.id,
		q.type,
		q.name,
		q.description,
		q.quotaBytes,
		q.usedBytes,
		q.usn,
		qc.parentId
    FROM    [dbo].[Quotas.Parent] qc
            INNER JOIN [dbo].[Quotas] q ON q.id = qc.id;
GO

-------------------------------------------------------------------------------
--AddTenantQuota
PRINT N'Creating [dbo].[AddTenantQuota]';
IF EXISTS ( SELECT  1  FROM    sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[AddTenantQuota]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[AddTenantQuota];
GO
CREATE PROCEDURE [dbo].[AddTenantQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@repositoryId uniqueidentifier,
	@tenantId uniqueidentifier,
	@wanId uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON;	
    SET XACT_ABORT ON;
	
    DECLARE @usn BIGINT;
    EXEC [dbo].[IncrementUsn] @usn OUTPUT;

    BEGIN TRANSACTION;

	exec [dbo].[AddRepositoryQuota]  @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, -- Quota
									 @repositoryId = @repositoryId, -- Repository quota
                                     @usn = @usn

	INSERT INTO [dbo].[Quotas.Tenant]
           ([id]
           ,[tenantId]
           ,[wanId])
    VALUES
           (@id, @tenantId, @wanId)


	COMMIT TRANSACTION;
END
GO

-------------------------------------------------------------------------------
--UpdateTenantQuota
PRINT N'Creating [dbo].[UpdateTenantQuota]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateTenantQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[UpdateTenantQuota]
GO
CREATE PROCEDURE [dbo].[UpdateTenantQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@repositoryId uniqueidentifier,
	@tenantId uniqueidentifier,
	@wanId uniqueidentifier,
	@updatedCount int = 0 output
AS
BEGIN
    SET XACT_ABORT ON;

    DECLARE @usn BIGINT;
    EXEC [dbo].[IncrementUsn] @usn OUTPUT;

    BEGIN TRANSACTION;

	exec [dbo].[UpdateRepositoryQuota]  @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, -- Quota
										@repositoryId = @repositoryId, -- Repository quota
										@updatedCount = @updatedCount output,
                                        @usn = @usn
	IF @updatedCount <> 0
	BEGIN
	    -- [dbo].[Quotas.Tenant]
	    UPDATE [dbo].[Quotas.Tenant]
	    SET [tenantId] = @tenantId,
            [wanId] = @wanId
        WHERE [id] = @id;

	    SET @updatedCount = @@ROWCOUNT
	    IF @updatedCount = 0
	    BEGIN
		    ROLLBACK TRANSACTION;
		    RAISERROR ('Not consistent data.', 11, 1); 
		    RETURN;
	    END
	END

	COMMIT TRANSACTION;
END
GO

--------------------------------------------------------------------------------
-- TenantQuotaView
PRINT N'Creating [dbo].[TenantQuotaView]';
IF OBJECT_ID(N'[dbo].[TenantQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[TenantQuotaView];
GO

	CREATE VIEW [dbo].[TenantQuotaView]
AS
    SELECT rqv.*,
		qt.tenantId,
		qt.wanId
    FROM    [dbo].[Quotas.Tenant] qt
            INNER JOIN [dbo].[RepositoryQuotaView] rqv ON rqv.id = qt.id;
GO

-------------------------------------------------------------------------------
-- AddSubtenantQuota
PRINT N'Creating [dbo].[AddSubtenantQuota]';
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AddSubtenantQuota]') AND type IN ( N'P', N'PC' ))
    DROP PROCEDURE [dbo].[AddSubtenantQuota];
GO
CREATE PROCEDURE [dbo].[AddSubtenantQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@parentId uniqueidentifier,
	@subtenantId uniqueidentifier,
	@isUnlimited bit
AS
BEGIN
	SET NOCOUNT ON;	
    SET XACT_ABORT ON;
	
    DECLARE @usn BIGINT;
    EXEC [dbo].[IncrementUsn] @usn OUTPUT;

    BEGIN TRANSACTION;

	exec [dbo].[AddChildQuota]  @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, -- Quota
								@parentId = @parentId, -- Child quota
                                @usn = @usn

	INSERT INTO [dbo].[Quotas.Subtenant]
           ([id]
           ,[subtenantId]
           ,[isUnlimited])
    VALUES
           (@id, @subtenantId, @isUnlimited)

	COMMIT TRANSACTION;
END
GO

-------------------------------------------------------------------------------
--UpdateSubtenantQuota
PRINT N'Creating [dbo].[UpdateSubtenantQuota]';
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateSubtenantQuota]') AND type IN ( N'P', N'PC' ))
    DROP PROCEDURE [dbo].[UpdateSubtenantQuota];
GO
CREATE PROCEDURE [dbo].[UpdateSubtenantQuota]
	@id uniqueidentifier,
	@type int,
	@name nvarchar(MAX),
	@description nvarchar(MAX),
	@quotaBytes bigint,
	@usedBytes bigint,
	@parentId uniqueidentifier,
	@subtenantId uniqueidentifier,
	@isUnlimited bit,
	@updatedCount int = 0 output
AS
BEGIN
    SET XACT_ABORT ON;

    DECLARE @usn BIGINT;
    EXEC [dbo].[IncrementUsn] @usn OUTPUT;

    BEGIN TRANSACTION;

	exec [dbo].[UpdateChildQuota] @id = @id, @type = @type, @name = @name, @description = @description, @quotaBytes = @quotaBytes, @usedBytes = @usedBytes, -- Quota
								  @parentId = @parentId, -- Child quota
								  @updatedCount = @updatedCount output,
                                  @usn = @usn
	IF @updatedCount <> 0
	BEGIN
	    -- [dbo].[Quotas.Subtenant]
	    UPDATE [dbo].[Quotas.Subtenant]
	    SET [subtenantId] = @subtenantId,
            [isUnlimited] = @isUnlimited
        WHERE [id] = @id;

	    SET @updatedCount = @@ROWCOUNT
	    IF @updatedCount = 0
	    BEGIN
		    ROLLBACK TRANSACTION;
		    RAISERROR ('Not consistent data.', 11, 1); 
		    RETURN;
	    END
	END

	COMMIT TRANSACTION;
END
GO

--------------------------------------------------------------------------------
-- SubtenantQuotaView
PRINT N'Creating [dbo].[SubtenantQuotaView]';
IF OBJECT_ID(N'[dbo].[SubtenantQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[SubtenantQuotaView];
GO

	CREATE VIEW [dbo].[SubtenantQuotaView]
AS
    SELECT
		cqv.*,
		qs.subtenantId,
		qs.isUnlimited
    FROM    [dbo].[Quotas.Subtenant] qs
            INNER JOIN [dbo].[ChildQuotaView] cqv ON cqv.id = qs.id;
GO

-------------------------------------------------------------------------------
-- SetQuotaBackup
PRINT N'Creating [dbo].[SetQuotaBackup]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SetQuotaBackup]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[SetQuotaBackup]
GO
CREATE PROCEDURE [dbo].[SetQuotaBackup]
	@id uniqueidentifier,
	@backupId uniqueidentifier,
	@installationId uniqueidentifier
AS
	BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;
		BEGIN TRANSACTION;
		DELETE FROM [dbo].[Quotas.Backup] where [backupId] = @backupId
		INSERT INTO [dbo].[Quotas.Backup]
	           ([id]
	           ,[backupId]
			   ,[installationId])
	     VALUES
	           (@id
	           ,@backupId
			   ,@installationId)
		COMMIT TRANSACTION;
	END;
GO

-------------------------------------------------------------------------------
-- ChangeQuotaBackup
PRINT N'Creating [dbo].[ChangeQuotaBackup]';
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ChangeQuotaBackup]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[ChangeQuotaBackup];
GO
CREATE PROCEDURE [dbo].[ChangeQuotaBackup]
	@id uniqueidentifier,
	@newQuotaId uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON;
	
	UPDAtE [dbo].[Quotas.Backup]
	SET [id] = @newQuotaId
	WHERE [id] = @id
    
END;
GO

-------------------------------------------------------------------------------
-- RemoveQuotaBackupByBackupId
PRINT N'Creating [dbo].[RemoveQuotaBackupByBackupId]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveQuotaBackupByBackupId]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[RemoveQuotaBackupByBackupId]
GO
CREATE PROCEDURE [dbo].[RemoveQuotaBackupByBackupId]
	@backupId uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON;
	
	DELETE FROM [dbo].[Quotas.Backup] where [backupId] = @backupId
END
GO

-------------------------------------------------------------------------------
-- RemoveQuotaBackupByQuotaId
PRINT N'Creating [dbo].[RemoveQuotaBackupByQuotaId]'
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RemoveQuotaBackupByQuotaId]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[RemoveQuotaBackupByQuotaId]
GO
CREATE PROCEDURE [dbo].[RemoveQuotaBackupByQuotaId]
	@id uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON;
	
	DELETE FROM [dbo].[Quotas.Backup] where [id] = @id
END
GO

--------------------------------------------------------------------------------
-- CloudUserQuotaView
PRINT N'Creating [dbo].[CloudUserQuotaView]';
IF OBJECT_ID(N'[dbo].[CloudUserQuotaView]', N'V') IS NOT NULL
    DROP VIEW [dbo].[CloudUserQuotaView];
GO

	CREATE VIEW [dbo].[CloudUserQuotaView]
AS
    SELECT rqv.id as quotaId,
		qt.tenantId as userId
    FROM    [dbo].[Quotas.Tenant] qt
            INNER JOIN [dbo].[RepositoryQuotaView] rqv ON rqv.id = qt.id
	
	UNION ALL

	SELECT cqv.id as quotaId,
		qs.subtenantId as userId
    FROM    [dbo].[Quotas.Subtenant] qs
            INNER JOIN [dbo].[ChildQuotaView] cqv ON cqv.id = qs.id;
GO

-------------------------------------------------------------------------------
-- Vcd.MakeSureOrganizationDescriptorAndQuotaExists
PRINT N'Creating [dbo].[Vcd.MakeSureOrganizationDescriptorAndQuotaExists]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Vcd.MakeSureOrganizationDescriptorAndQuotaExists]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Vcd.MakeSureOrganizationDescriptorAndQuotaExists]
GO
CREATE PROCEDURE [Vcd.MakeSureOrganizationDescriptorAndQuotaExists]
	@vcd_host_id UNIQUEIDENTIFIER,
	@vcd_cells XML,
	@org_ref nvarchar(max),
	@org_name nvarchar(255)
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        DECLARE @usn BIGINT;
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;

		DECLARE @orgId UNIQUEIDENTIFIER
		EXEC [dbo].[Vcd.GetOrAddOrgDescriptor] @vcd_host_id, @vcd_cells, @org_ref, @org_name, @orgId OUTPUT, @usn
		
		EXEC [dbo].[MakeSureOrganizationQuotaExists] @orgId, @usn
    END;
GO

-------------------------------------------------------------------------------
-- MakeSureOrganizationQuotaExists
PRINT N'Creating [dbo].[MakeSureOrganizationQuotaExists]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MakeSureOrganizationQuotaExists]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[MakeSureOrganizationQuotaExists]
GO
CREATE PROCEDURE [MakeSureOrganizationQuotaExists]
	@org_id UNIQUEIDENTIFIER,
    @usn BIGINT = NULL
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        IF (@usn IS NULL)
        BEGIN
            EXEC [dbo].[IncrementUsn] @usn OUTPUT;
        END

		BEGIN TRANSACTION;
		IF NOT EXISTS (SELECT id FROM [dbo].[Quotas.VcdOrganization] WHERE [organization_id] = @org_id)
		BEGIN

			DECLARE @config_id UNIQUEIDENTIFIER
			SET @config_id = dbo.FindEnabledVcdConfigurationByOrgId(@org_id);
			IF (@config_id is NULL)
				RAISERROR ('Unable to find enabled configuration.', 11, 1); 
			
			DECLARE @repo_id UNIQUEIDENTIFIER
			DECLARE @quota_in_bytes BIGINT
			DECLARE @new_quota_id UNIQUEIDENTIFIER
			SELECT 
				@repo_id = repo.[id], 
				@quota_in_bytes = config.[quota_gb] * 1024 * 1024 * 1024,
				@new_quota_id = NEWID()
			FROM [dbo].[Vcd.OrgConfigurations] config
			JOIN [dbo].[BackupRepositories] repo ON config.[repository_unique_id] = repo.[unique_id]
			WHERE config.[id] = @config_id

			EXEC [dbo].[AddRepositoryQuota] @id = @new_quota_id, 
											@type = 1, 
											@name = 'VCD multi tenancy quota',
											@description = 'VCD multi tenancy quota',
											@quotaBytes = @quota_in_bytes,
											@usedBytes = 0,
											@repositoryId = @repo_id,
                                            @usn = @usn
				
			INSERT INTO [dbo].[Quotas.VcdOrganization]([id], [organization_id])
			VALUES (@new_quota_id, @org_id)
			END

		COMMIT TRANSACTION;

    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.UpdateOtherOrganizationQuotaValue
PRINT N'Creating [dbo].[Quota.Vcd.UpdateOtherOrganizationQuotaValue]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.UpdateOtherOrganizationQuotaValue]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.UpdateOtherOrganizationQuotaValue]
GO
CREATE PROCEDURE [Quota.Vcd.UpdateOtherOrganizationQuotaValue]
	@quota_gb bigint
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;
		
		DECLARE @quota_in_bytes bigint
		SET @quota_in_bytes = @quota_gb * 1024 * 1024 * 1024
			
		UPDATE q
			SET [quotaBytes] = @quota_in_bytes
		FROM [dbo].[Quotas] q
		JOIN [dbo].[Quotas.VcdOrganization] org ON org.[id] = q.[id]
		WHERE org.[organization_id] NOT IN
		(
			SELECT [vcd_organization_id]
			FROM [dbo].[Vcd.OrgConfigurations]
		)

    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.UpdateIndividualQuotaValue
PRINT N'Creating [dbo].[Quota.Vcd.UpdateIndividualQuotaValue]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.UpdateIndividualQuotaValue]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.UpdateIndividualQuotaValue]
GO
CREATE PROCEDURE [Quota.Vcd.UpdateIndividualQuotaValue]
	@org_id UNIQUEIDENTIFIER,
	@quota_gb bigint
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;
		
		DECLARE @quota_in_bytes bigint
		SET @quota_in_bytes = @quota_gb * 1024 * 1024 * 1024
		
		UPDATE q
			SET [quotaBytes] = @quota_in_bytes
		FROM [dbo].[Quotas] q
		JOIN [dbo].[Quotas.VcdOrganization] q2org ON q2org.[id] = q.[id]
		WHERE q2org.[organization_id] = @org_id

    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.DeleteIndividualOrganizationQuota
PRINT N'Creating [dbo].[Quota.Vcd.DeleteIndividualOrganizationQuota]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.DeleteIndividualOrganizationQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.DeleteIndividualOrganizationQuota]
GO
CREATE PROCEDURE [Quota.Vcd.DeleteIndividualOrganizationQuota]
	@organization_id UNIQUEIDENTIFIER
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;
		
		DECLARE @old_quota_id uniqueidentifier
		SELECT @old_quota_id = q2org.[id]
		FROM [dbo].[Quotas.VcdOrganization] q2org
		WHERE q2org.[organization_id] = @organization_id

		--the quota may not exist for an imported organization
		IF (@old_quota_id IS NOT NULL)
		BEGIN
            DECLARE @usn BIGINT;
            EXEC [dbo].[IncrementUsn] @usn OUTPUT;

			EXEC [dbo].[DeleteQuota] @old_quota_id, @usn
		END
    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.RecreateIndividualOrganizationQuota
PRINT N'Creating [dbo].[Quota.Vcd.RecreateIndividualOrganizationQuota]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.RecreateIndividualOrganizationQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.RecreateIndividualOrganizationQuota]
GO
CREATE PROCEDURE [Quota.Vcd.RecreateIndividualOrganizationQuota]
	@organization_id UNIQUEIDENTIFIER,
    @usn BIGINT = NULL
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        IF (@usn IS NULL)
        BEGIN
            EXEC [dbo].[IncrementUsn] @usn OUTPUT;
        END
				
		DECLARE @config_id UNIQUEIDENTIFIER
		SET @config_id = dbo.FindEnabledVcdConfigurationByOrgId(@organization_id);
		IF (@config_id is NULL)
			RAISERROR ('Unable to find enabled configuration.', 11, 1);

		DECLARE @current_repo_unique_id UNIQUEIDENTIFIER
		DECLARE @quota_gb bigint
		SELECT 
			@current_repo_unique_id = repository_unique_id, 
			@quota_gb = [quota_gb]
		FROM [dbo].[Vcd.OrgConfigurations]
		WHERE id = @config_id

		DECLARE @current_repo_id UNIQUEIDENTIFIER
		SELECT @current_repo_id = id FROM [dbo].[BackupRepositories] WHERE unique_id = @current_repo_unique_id

		DECLARE @quota_in_bytes bigint
		SET @quota_in_bytes = @quota_gb * 1024 * 1024 * 1024

		DECLARE @quota_id uniqueidentifier
		SELECT 
			@quota_id = q2org.[id]
		FROM [dbo].[Quotas.VcdOrganization] q2org
		WHERE q2org.[organization_id] = @organization_id
		
		BEGIN TRANSACTION

		IF (@quota_id IS NULL)
		BEGIN
			SET @quota_id = NEWID()
			EXEC [dbo].[AddRepositoryQuota] @id = @quota_id, 
											@type = 1, 
											@name = 'VCD multi tenancy quota',
											@description = 'VCD multi tenancy quota',
											@quotaBytes = @quota_in_bytes,
											@usedBytes = 0,
											@repositoryId = @current_repo_id,
                                            @usn = @usn
		END
		ELSE
		BEGIN
			EXEC [dbo].[UpdateRepositoryQuota] @id = @quota_id, 
											@type = 1, 
											@name = 'VCD multi tenancy quota',
											@description = 'VCD multi tenancy quota',
											@quotaBytes = @quota_in_bytes,
											@usedBytes = 0,				--isn't used in the procedure
											@repositoryId = @current_repo_id,
                                            @usn = @usn
		END
		

		DELETE [dbo].[Quotas.Backup] WHERE id = @quota_id
			
		INSERT INTO [Quotas.Backup]([id], [backupId]) 
		SELECT 
			@quota_id as id, 
			backups.[id] as backupId
		FROM [dbo].[Backup.Model.Backups] backups
		JOIN [dbo].[Backup.Model.Backups.VcdInfo] backups_vcdext ON backups.[id] = backups_vcdext.[id]
		WHERE backups.[repository_id] = @current_repo_id AND backups_vcdext.[vcd_org_id] = @organization_id

		DELETE [Quotas.VcdOrganization] WHERE id = @quota_id
		INSERT INTO [Quotas.VcdOrganization](id, organization_id)
		VALUES (@quota_id, @organization_id)

		COMMIT TRANSACTION

    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.RecreateOtherOrganizationQuotas
PRINT N'Creating [dbo].[Quota.Vcd.RecreateOtherOrganizationQuotas]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.RecreateOtherOrganizationQuotas]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.RecreateOtherOrganizationQuotas]
GO
CREATE PROCEDURE [Quota.Vcd.RecreateOtherOrganizationQuotas]
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        DECLARE @usn BIGINT;
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
		
        DECLARE org_cursor CURSOR
        FOR	
			SELECT [id]
			FROM [dbo].[Vcd.Organizations] org
			WHERE NOT EXISTS(SELECT id FROM [dbo].[Vcd.OrgConfigurations] config WHERE config.[vcd_organization_id] = org.[id])

        OPEN org_cursor;
		
        DECLARE @org_id UNIQUEIDENTIFIER;
		FETCH NEXT FROM org_cursor INTO @org_id;
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC [dbo].[Quota.Vcd.RecreateIndividualOrganizationQuota] @org_id, @usn
			FETCH NEXT FROM org_cursor INTO @org_id;
		END;
		
        CLOSE org_cursor;
        DEALLOCATE org_cursor;
    END;
GO

-------------------------------------------------------------------------------
-- Quota.Vcd.DeleteOtherOrganizationQuotas
PRINT N'Creating [dbo].[Quota.Vcd.DeleteOtherOrganizationQuotas]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.Vcd.DeleteOtherOrganizationQuotas]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.Vcd.DeleteOtherOrganizationQuotas]
GO
CREATE PROCEDURE [Quota.Vcd.DeleteOtherOrganizationQuotas]
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        DECLARE @usn BIGINT;
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;
		
        DECLARE quotas_cursor CURSOR
        FOR	
			SELECT q2org.[id]
			FROM [dbo].[Quotas.VcdOrganization] q2org
			WHERE NOT EXISTS(SELECT id FROM [dbo].[Vcd.OrgConfigurations] config WHERE config.[vcd_organization_id] = q2org.[organization_id])

        OPEN quotas_cursor;
		
        DECLARE @quota_id UNIQUEIDENTIFIER;
		FETCH NEXT FROM quotas_cursor INTO @quota_id;
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC [dbo].[DeleteQuota] @quota_id, @usn
			FETCH NEXT FROM quotas_cursor INTO @quota_id;
		END;
		
        CLOSE quotas_cursor;
        DEALLOCATE quotas_cursor;
    END;
GO

-------------------------------------------------------------------------------
-- CreateWorkspaceQuotaByConfiguration
PRINT N'Creating [dbo].[CreateWorkspaceQuotaByConfiguration]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreateWorkspaceQuotaByConfiguration]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[CreateWorkspaceQuotaByConfiguration]
GO
CREATE PROCEDURE [CreateWorkspaceQuotaByConfiguration]
	@config_id UNIQUEIDENTIFIER,
	@workspace_id UNIQUEIDENTIFIER,
	@new_quota_id UNIQUEIDENTIFIER,
    @usn BIGINT = NULL
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        IF (@usn IS NULL)
        BEGIN
            EXEC [dbo].[IncrementUsn] @usn OUTPUT;
        END
					
		DECLARE @repo_unique_id UNIQUEIDENTIFIER
		DECLARE @quota_gb bigint
		SELECT @repo_unique_id = repository_unique_id, @quota_gb = [quota_gb] FROM [dbo].[VSphere.WorkspaceConfigurations]
		WHERE id = @config_id

		DECLARE @quota_in_bytes bigint
		SET @quota_in_bytes = @quota_gb * 1024 * 1024 * 1024

		DECLARE @repo_id UNIQUEIDENTIFIER
		SELECT @repo_id = id FROM [dbo].[BackupRepositories] WHERE unique_id = @repo_unique_id

		EXEC [dbo].[AddRepositoryQuota] @id = @new_quota_id, 
										@type = 1, 
										@name = 'VSphere multi tenancy quota',
										@description = 'VSphere multi tenancy quota',
										@quotaBytes = @quota_in_bytes,
										@usedBytes = 0,
										@repositoryId = @repo_id,
                                        @usn = @usn
				
		INSERT INTO [dbo].[Quotas.VSphereWorkspace]([id], [workspace_id])
		VALUES (@new_quota_id, @workspace_id)
    END;
GO
	
-------------------------------------------------------------------------------
-- MakeSureWorkspaceQuotaExists
PRINT N'Creating [dbo].[MakeSureWorkspaceQuotaExists]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MakeSureWorkspaceQuotaExists]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[MakeSureWorkspaceQuotaExists]
GO
CREATE PROCEDURE [MakeSureWorkspaceQuotaExists]
	@workspace_sid_binary varbinary(max),
	@parent_quota_sid_binary varbinary(max),
	@quota_id UNIQUEIDENTIFIER OUT,
    @usn BIGINT = NULL
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        IF (@usn IS NULL)
        BEGIN
            EXEC [dbo].[IncrementUsn] @usn OUTPUT;
        END

		DECLARE @quota_workspace_id UNIQUEIDENTIFIER
		SET @quota_workspace_id = [dbo].[FindWorkspaceIdBySids](@workspace_sid_binary, @parent_quota_sid_binary)
		
		DECLARE @configuration_id UNIQUEIDENTIFIER
		SET @configuration_id = [dbo].[FindWorkspaceConfigurationIdBySids](@workspace_sid_binary, @parent_quota_sid_binary)

		BEGIN TRANSACTION;
		IF NOT EXISTS (SELECT id FROM [dbo].[Quotas.VSphereWorkspace] WHERE [workspace_id] = @quota_workspace_id)
		BEGIN		
			SET @quota_id = NEWID()
			EXEC [dbo].[CreateWorkspaceQuotaByConfiguration] @configuration_id, @quota_workspace_id, @quota_id, @usn
		END
		ELSE
			SELECT @quota_id = id FROM [dbo].[Quotas.VSphereWorkspace] WHERE [workspace_id] = @quota_workspace_id

		COMMIT TRANSACTION;

    END;
GO

-------------------------------------------------------------------------------
-- Quota.VSphere.UpdateQuotaValue
PRINT N'Creating [dbo].[Quota.VSphere.UpdateQuotaValue]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.VSphere.UpdateQuotaValue]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.VSphere.UpdateQuotaValue]
GO
CREATE PROCEDURE [Quota.VSphere.UpdateQuotaValue]
	@workspace_id UNIQUEIDENTIFIER,
	@quota_in_bytes bigint
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;
		
		UPDATE q
			SET [quotaBytes] = @quota_in_bytes
		FROM [dbo].[Quotas] q
		JOIN [dbo].[Quotas.VSphereWorkspace] q2w ON q2w.[id] = q.[id]
		WHERE q2w.[workspace_id] = @workspace_id

		UPDATE q
			SET [quotaBytes] = @quota_in_bytes
		FROM [dbo].[Quotas] q
		JOIN [dbo].[Quotas.VSphereWorkspace] q2w ON q2w.[id] = q.[id]
		JOIN [dbo].[VSphere.Workspaces] w ON q2w.[workspace_id] = w.[id]
		JOIN [dbo].[VSphere.Workspaces] parent_w ON w.[quota_parent_workspace_sid] = parent_w.[sid_binary]
		WHERE parent_w.[id] = @workspace_id
			
    END;
GO

-------------------------------------------------------------------------------
-- Quota.VSphere.RecreateWorkspaceQuota
PRINT N'Creating [dbo].[Quota.VSphere.RecreateWorkspaceQuota]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Quota.VSphere.RecreateWorkspaceQuota]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[Quota.VSphere.RecreateWorkspaceQuota]
GO
CREATE PROCEDURE [Quota.VSphere.RecreateWorkspaceQuota]
	@workspace_id UNIQUEIDENTIFIER,
	@repository_unique_id UNIQUEIDENTIFIER,
	@quota_in_bytes bigint
AS
    BEGIN
		SET NOCOUNT ON;
		SET XACT_ABORT ON;

        DECLARE @usn BIGINT;
        EXEC [dbo].[IncrementUsn] @usn OUTPUT;

		DECLARE @repository_id UNIQUEIDENTIFIER
		SELECT @repository_id = [id]
		FROM [dbo].[BackupRepositories] WHERE [unique_id] = @repository_unique_id

		DECLARE quota_cursor CURSOR
        FOR	
			SELECT q.[id]
			FROM [Quotas] q
			JOIN [Quotas.VSphereWorkspace] q2w ON q2w.id = q.[id]
			WHERE q2w.[workspace_id] = @workspace_id
			UNION
			SELECT q.[id]
			FROM [Quotas] q
			JOIN [Quotas.VSphereWorkspace] q2w ON q2w.id = q.[id]
			JOIN [VSphere.Workspaces] w ON q2w.[workspace_id] = w.[id]
			JOIN [VSphere.Workspaces] parent_w ON w.[quota_parent_workspace_sid] = parent_w.[sid_binary]
			WHERE parent_w.[id] = @workspace_id

        OPEN quota_cursor;
				
		DECLARE @quota_workspace_id UNIQUEIDENTIFIER;
        DECLARE @quota_id UNIQUEIDENTIFIER;
		FETCH NEXT FROM quota_cursor INTO @quota_id;
		WHILE @@FETCH_STATUS = 0
		BEGIN
			EXEC [dbo].[UpdateRepositoryQuota] @id = @quota_id, 
												@type = 1, 
												@name = 'VSphere multi tenancy quota',
												@description = 'VSphere multi tenancy quota',
												@quotaBytes = @quota_in_bytes,
												@usedBytes = 0,
												@repositoryId = @repository_id,
                                                @usn = @usn
			
			SELECT @quota_workspace_id = [workspace_id] FROM [Quotas.VSphereWorkspace] WHERE [id] = @quota_id

			DELETE [dbo].[Quotas.Backup] WHERE id = @quota_id
			INSERT INTO [Quotas.Backup]([id], [backupId]) 
			SELECT 
				@quota_id as id, 
				backups.[id] as backupId
			FROM [dbo].[Backup.Model.Backups] backups
			JOIN [dbo].[Backup.Model.Backups.VSphereInfo] backups_vsphere ON backups.[id] = backups_vsphere.[id]
			WHERE backups.[repository_id] = @repository_id AND 
				  backups_vsphere.[workspace_id] = @quota_workspace_id

			FETCH NEXT FROM quota_cursor INTO @quota_id;
		END;
		
        CLOSE quota_cursor;
        DEALLOCATE quota_cursor;
    END;
GO

-------------------------------------------------------------------------------
-- UpdateRepoIdForQuotaBackups
PRINT N'Creating [dbo].[UpdateRepoIdForQuotaBackups]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateRepoIdForQuotaBackups]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[UpdateRepoIdForQuotaBackups]
GO
CREATE PROCEDURE [UpdateRepoIdForQuotaBackups]
	@id UNIQUEIDENTIFIER,
	@repository_id UNIQUEIDENTIFIER
AS
    BEGIN
		SET NOCOUNT ON;	
        SET XACT_ABORT ON;

		DECLARE @usn BIGINT;
		EXEC [dbo].[IncrementUsn] @usn OUTPUT;
		
        UPDATE b
		SET b.repository_id = @repository_id,
			b.usn = @usn
		FROM [dbo].[Backup.Model.Backups] b
			INNER JOIN [dbo].[Quotas.Backup] qb on qb.backupId = b.id
		WHERE qb.id = @id 
			AND b.repository_id <> @repository_id
    END;
GO

-------------------------------------------------------------------------------
-- SetInstallationIdToQuotaBackup
PRINT N'Creating [dbo].[SetInstallationIdToQuotaBackup]'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SetInstallationIdToQuotaBackup]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[SetInstallationIdToQuotaBackup]
GO
CREATE PROCEDURE [dbo].[SetInstallationIdToQuotaBackup]
	@backupId uniqueidentifier,
	@installationId uniqueidentifier
AS
	BEGIN
		SET NOCOUNT ON;
		UPDATE [dbo].[Quotas.Backup]
		SET [installationId] = @installationId
		WHERE [backupId] = @backupId;
	END
GO

-------------------------------------------------------------------------------
-- GetArchiveDiffBytesByQuotaId
PRINT N'Creating [dbo].[GetArchiveDiffBytesByQuotaId]';
IF EXISTS ( SELECT 1 FROM sys.objects WHERE   object_id = OBJECT_ID(N'[dbo].[GetArchiveDiffBytesByQuotaId]') AND type IN ( N'P', N'PC' ) )
    DROP PROCEDURE [dbo].[GetArchiveDiffBytesByQuotaId];
GO

CREATE PROCEDURE [dbo].[GetArchiveDiffBytesByQuotaId]
	@id UNIQUEIDENTIFIER
AS
BEGIN
	
	SET NOCOUNT ON;
   
	WITH x AS
	(
	  SELECT id, parentId
		FROM [dbo].[RecursiveQuotaView]
		WHERE id = @id
	  UNION ALL
	  SELECT y.id, y.parentId
		FROM x 
		INNER JOIN [dbo].[RecursiveQuotaView] as y ON y.parentId = x.id
	)

	SELECT SUM(storages.[backup_size] - storageCopies.[dehydrated_size]) FROM x
	JOIN [dbo].[Quotas.Backup] as quotaBackups on quotaBackups.[id] = x.[id]
	JOIN [dbo].[Backup.Model.Storages] as storages ON storages.[backup_id] = quotaBackups.[backupId]
	JOIN [dbo].[Backup.Model.StorageCopies] as storageCopies ON storageCopies.[storage_id] = storages.[id]
	WHERE storages.[external_content_mode] = 1
END
GO