IF NOT EXISTS(
	SELECT *  
	FROM information_schema.table_constraints  
	WHERE constraint_type = 'PRIMARY KEY'   
	AND table_name = N'Version_Sitecollections')
BEGIN
	-- Creating primary key on [Id] in table 'Version_Sitecollections'
	ALTER TABLE [dbo].[Version_Sitecollections]
	ADD CONSTRAINT [PK_Version_Sitecollections]
		PRIMARY KEY CLUSTERED ([Id] ASC);
END

IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Object_ID = Object_ID(N'ScriptloaderTimestamps'))
BEGIN
	-- Creating table 'ScriptloaderTimestamps'
	CREATE TABLE [dbo].[ScriptloaderTimestamps] (
		[Key] nvarchar(400)  NOT NULL,
		[Value] datetime  NOT NULL
	);

	-- Creating primary key on [Key] in table 'ScriptloaderTimestamps'
	ALTER TABLE [dbo].[ScriptloaderTimestamps]
	ADD CONSTRAINT [PK_ScriptloaderTimestamps]
	PRIMARY KEY CLUSTERED ([Key] ASC);
END

IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Name      = N'UpgradePriority'
      AND Object_ID = Object_ID(N'Version_Sitecollections'))
BEGIN
	ALTER TABLE Version_Sitecollections ADD [UpgradePriority] int NULL
	ALTER TABLE Version_Sitecollections ADD [LastVisited] datetime NULL
	ALTER TABLE Version_Sitecollections ADD [Visits] bigint NULL
	ALTER TABLE Version_Sitecollections ADD [Created] datetime NULL
	ALTER TABLE Version_Sitecollections ADD [UpgradePriorityOverride] bit NULL
	ALTER TABLE Version_Sitecollections ADD [ScriptloaderVariables] nvarchar(max) NULL
END


IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Object_ID = Object_ID(N'SitecollectionTaskQueue'))
BEGIN
	-- Creating table 'SitecollectionTaskQueue'
	CREATE TABLE [dbo].[SitecollectionTaskQueue] (
		[TaskId] int IDENTITY(1,1) NOT NULL,
		[SitecollectionID] int  NOT NULL,
		[Retries] int  NOT NULL,
		[TaskType] int  NOT NULL,
		[Started] datetime  NULL,
		[Ended] datetime  NULL,
		[CurrentTask] int  NULL,
		[TotalTasks] int  NULL,
		[Message] nvarchar(max)  NULL,
		[UpgradeFolder] nvarchar(max)  NULL,
		[Status] int  NOT NULL,
		[Created] datetime  NOT NULL
	);

	-- Creating primary key on [TaskId] in table 'SitecollectionTaskQueue'
	ALTER TABLE [dbo].[SitecollectionTaskQueue]
	ADD CONSTRAINT [PK_SitecollectionTaskQueue]
		PRIMARY KEY CLUSTERED ([TaskId] ASC);

	-- Creating foreign key on [SitecollectionID] in table 'SitecollectionTaskQueue'
	ALTER TABLE [dbo].[SitecollectionTaskQueue]
	ADD CONSTRAINT [FK_SitecollectionTaskQueueVersion_Sitecollections]
		FOREIGN KEY ([SitecollectionID])
		REFERENCES [dbo].[Version_Sitecollections]
			([Id])
		ON DELETE NO ACTION ON UPDATE NO ACTION;

	-- Creating non-clustered index for FOREIGN KEY 'FK_SitecollectionTaskQueueVersion_Sitecollections'
	CREATE INDEX [IX_FK_SitecollectionTaskQueueVersion_Sitecollections]
	ON [dbo].[SitecollectionTaskQueue]
		([SitecollectionID]);
END