IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Backups_Backups]') AND parent_object_id = OBJECT_ID(N'[dbo].[Backups]'))
ALTER TABLE [dbo].[Backups] DROP CONSTRAINT [FK_Backups_Backups]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Backups_BJobs]') AND parent_object_id = OBJECT_ID(N'[dbo].[Backups]'))
ALTER TABLE [dbo].[Backups] DROP CONSTRAINT [FK_Backups_BJobs]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Backups_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[Backups]'))
ALTER TABLE [dbo].[Backups] DROP CONSTRAINT [FK_Backups_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BJobs_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[BJobs]'))
ALTER TABLE [dbo].[BJobs] DROP CONSTRAINT [FK_BJobs_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BObjects_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[BObjects]'))
ALTER TABLE [dbo].[BObjects] DROP CONSTRAINT [FK_BObjects_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BSessionInfo_Backups]') AND parent_object_id = OBJECT_ID(N'[dbo].[BSessionInfo]'))
ALTER TABLE [dbo].[BSessionInfo] DROP CONSTRAINT [FK_BSessionInfo_Backups]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BSessionInfo_BObjects]') AND parent_object_id = OBJECT_ID(N'[dbo].[BSessionInfo]'))
ALTER TABLE [dbo].[BSessionInfo] DROP CONSTRAINT [FK_BSessionInfo_BObjects]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BSessionInfo_BSessions]') AND parent_object_id = OBJECT_ID(N'[dbo].[BSessionInfo]'))
ALTER TABLE [dbo].[BSessionInfo] DROP CONSTRAINT [FK_BSessionInfo_BSessions]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_BSessions_BJobs]') AND parent_object_id = OBJECT_ID(N'[dbo].[BSessions]'))
ALTER TABLE [dbo].[BSessions] DROP CONSTRAINT [FK_BSessions_BJobs]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Folder_Host_Folders]') AND parent_object_id = OBJECT_ID(N'[dbo].[Folder_Host]'))
ALTER TABLE [dbo].[Folder_Host] DROP CONSTRAINT [FK_Folder_Host_Folders]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Folder_Host_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[Folder_Host]'))
ALTER TABLE [dbo].[Folder_Host] DROP CONSTRAINT [FK_Folder_Host_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Folders_Folders]') AND parent_object_id = OBJECT_ID(N'[dbo].[Folders]'))
ALTER TABLE [dbo].[Folders] DROP CONSTRAINT [FK_Folders_Folders]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Hosts_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[Hosts]'))
ALTER TABLE [dbo].[Hosts] DROP CONSTRAINT [FK_Hosts_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInBackups_Backups]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInBackups]'))
ALTER TABLE [dbo].[ObjectsInBackups] DROP CONSTRAINT [FK_ObjectsInBackups_Backups]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInBackups_BObjects]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInBackups]'))
ALTER TABLE [dbo].[ObjectsInBackups] DROP CONSTRAINT [FK_ObjectsInBackups_BObjects]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInBackups_ObjectsInBackups]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInBackups]'))
ALTER TABLE [dbo].[ObjectsInBackups] DROP CONSTRAINT [FK_ObjectsInBackups_ObjectsInBackups]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInJobs_BJobs]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInJobs]'))
ALTER TABLE [dbo].[ObjectsInJobs] DROP CONSTRAINT [FK_ObjectsInJobs_BJobs]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInJobs_BObjects]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInJobs]'))
ALTER TABLE [dbo].[ObjectsInJobs] DROP CONSTRAINT [FK_ObjectsInJobs_BObjects]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ObjectsInJobs_Folders]') AND parent_object_id = OBJECT_ID(N'[dbo].[ObjectsInJobs]'))
ALTER TABLE [dbo].[ObjectsInJobs] DROP CONSTRAINT [FK_ObjectsInJobs_Folders]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Soap_creds_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[Soap_creds]'))
ALTER TABLE [dbo].[Soap_creds] DROP CONSTRAINT [FK_Soap_creds_Hosts]
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Ssh_creds_Hosts]') AND parent_object_id = OBJECT_ID(N'[dbo].[Ssh_creds]'))
ALTER TABLE [dbo].[Ssh_creds] DROP CONSTRAINT [FK_Ssh_creds_Hosts]
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'file_name')
begin
    alter table dbo.Backups add file_name nvarchar(255) null
    print 'New column {file_name} has been successfully added to dbo.Backups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'post_command_run_count')
begin
    alter table dbo.BJobs add post_command_run_count int DEFAULT 0 NOT null
    print 'New column {post_command_run_count} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'end_time')
begin
    alter table dbo.BSessionInfo add end_time datetime DEFAULT '01.01.1900' NOT null
    print 'New column {end_time} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'end_time')
begin
    alter table dbo.BSessions add end_time datetime DEFAULT '01.01.1900' NOT null
    print 'New column {end_time} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'inside_dir')
begin
    alter table dbo.ObjectsInBackups add inside_dir nvarchar(400) default 'empty' not null
    print 'New column {inside_dir} has been successfully added to dbo.ObjectsInBackups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [name] = 'adjust_firewall')
begin
    alter table dbo.Ssh_creds add adjust_firewall bit default 0 not null
    print 'New column {adjust_firewall} has been successfully added to dbo.Ssh_creds table'
    
    DECLARE @id uniqueidentifier, @host_id uniqueidentifier, @object_id_1 uniqueidentifier, @object_id nvarchar(400)
	DECLARE objectsinbackups_cursor CURSOR FOR
	SELECT [id],[object_id] FROM [dbo].[ObjectsInBackups]
	WHERE [inside_dir] = 'empty'

	OPEN objectsinbackups_cursor

	-- Perform the first fetch.
	FETCH NEXT FROM objectsinbackups_cursor into @id, @object_id_1

	-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
	WHILE @@FETCH_STATUS = 0
	BEGIN
	   set @host_id = (select [host_id] from [dbo].[BObjects] where [id] = @object_id_1)
	   set @object_id = (select [object_id] from [dbo].[BObjects] where [id] = @object_id_1)
	   update [dbo].[ObjectsInBackups] set [inside_dir] = (select convert(nvarchar(36), @host_id) + ' (' + @object_id + ')') where [id] = @id

	   -- This is executed as long as the previous fetch succeeds.
	   FETCH NEXT FROM objectsinbackups_cursor into @id, @object_id_1
	END

	CLOSE objectsinbackups_cursor
	DEALLOCATE objectsinbackups_cursor
end
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Options]') AND type in (N'U'))
BEGIN
	CREATE TABLE Options (
	[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
	[name] nvarchar(50) not null default '',
	[value] xml not null default '')
END
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'operation')
begin
    alter table dbo.BSessions add operation nvarchar(400) DEFAULT '' NOT null
    print 'New column {operation} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'total_objects')
begin
    alter table dbo.BSessions add total_objects int DEFAULT 0 NOT null
    print 'New column {total_objects} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'processed_objects')
begin
    alter table dbo.BSessions add processed_objects int DEFAULT 0 NOT null
    print 'New column {processed_objects} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'total_size')
begin
    alter table dbo.BSessions add total_size bigint DEFAULT 0 NOT null
    print 'New column {total_size} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'processed_size')
begin
    alter table dbo.BSessions add processed_size bigint DEFAULT 0 NOT null
    print 'New column {processed_size} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'operation')
begin
    alter table dbo.BSessionInfo add operation nvarchar(400) DEFAULT '' NOT null
    print 'New column {operation} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'total_objects')
begin
    alter table dbo.BSessionInfo add total_objects int DEFAULT 0 NOT null
    print 'New column {total_objects} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'processed_objects')
begin
    alter table dbo.BSessionInfo add processed_objects int DEFAULT 0 NOT null
    print 'New column {processed_objects} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'total_size')
begin
    alter table dbo.BSessionInfo add total_size bigint DEFAULT 0 NOT null
    print 'New column {total_size} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'processed_size')
begin
    alter table dbo.BSessionInfo add processed_size bigint DEFAULT 0 NOT null
    print 'New column {processed_size} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'control')
begin
    alter table dbo.BJobs add control int DEFAULT 0 NOT null
    print 'New column {control} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'vss_options')
begin
    alter table dbo.BJobs add vss_options xml DEFAULT '<CVssOptions/>' NOT null
    print 'New column {vss_options} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'vss_options')
begin
    alter table dbo.ObjectsInJobs add vss_options xml default '<CVssOptions/>' not null
    print 'New column {vss_options} has been successfully added to dbo.ObjectsInJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'stats')
begin
    alter table dbo.Backups add stats xml null
    print 'New column {stats} has been successfully added to dbo.Backups table'
end
GO
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'is_retry')
begin
    alter table dbo.Backups add is_retry bit default 0 not null
    print 'New column {is_retry} has been successfully added to dbo.Backups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'is_retry')
begin
    alter table dbo.BSessions add is_retry bit default 0 not null
    print 'New column {is_retry} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [name] = 'auto_sudo')
begin
    alter table dbo.Ssh_creds add auto_sudo bit default 1 not null
    print 'New column {auto_sudo} has been successfully added to dbo.Ssh_creds table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'version')
begin
    alter table dbo.Backups add version int DEFAULT 0 NOT null
    print 'New column {version} has been successfully added to dbo.Backups table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'is_running')
begin
	declare @constr sysname
	set @constr = (select object_name(cdefault) as 'DefaultName' from syscolumns where [id] = object_id('ObjectsInBackups') and [name] = 'is_running')
	exec('alter table ObjectsInBackups drop constraint ' + @constr)
	exec sp_rename '[dbo].[ObjectsInBackups].[is_running]', 'state', 'COLUMN'
	alter table ObjectsInBackups alter column state int not null
	alter table ObjectsInBackups ADD CONSTRAINT DF__ObjectsIn__state__267ABA7A DEFAULT 0 FOR state
	print 'Column {is_running} has been successfully rename to {state} to dbo.ObjectsInBackups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'vcb_host_id')
begin
    alter table dbo.BJobs add vcb_host_id uniqueidentifier DEFAULT '6745a759-2205-4cd2-b172-8ec8f7e60ef8' NOT null
    print 'New column {vcb_host_id} has been successfully added to dbo.BJobs table'
end
GO
update [dbo].[Folders] set [name] = 'Sessions' where [id] = 'aacdcffb-a706-4327-8884-8506e46275fc'
GO
if not exists (select * from [dbo].[Options] where [id]='91bb166b-e197-48f7-a430-7904e013b30b')
begin
	exec sp_executesql @statement = N'
    insert into [dbo].[Options] values(''91bb166b-e197-48f7-a430-7904e013b30b'', ''email_notification'', ''<CMailOptions/>'')
    print ''Insert item into [dbo].[Options] table'''
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'info')
begin
    alter table dbo.Hosts add info nvarchar(255) default '' not null
    print 'New column {info} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'description')
begin
    alter table dbo.Hosts add description nvarchar(1024) default '' not null
    print 'New column {description} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [name] = 'enabled')
begin
    alter table dbo.Ssh_creds add enabled bit default 1 not null
    print 'New column {enabled} has been successfully added to dbo.Ssh_creds table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Soap_creds]') and [name] = 'enabled')
begin
    alter table dbo.Soap_creds add enabled bit default 1 not null
    print 'New column {enabled} has been successfully added to dbo.Soap_creds table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'target_type')
begin
    alter table dbo.BJobs add target_type int DEFAULT 0 NOT null
    print 'New column {target_type} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'description')
begin
    alter table dbo.BJobs add description nvarchar(1024) default '' not null
    print 'New column {description} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'protocol')
begin
    alter table dbo.Hosts add protocol int DEFAULT 0 NOT null
    print 'New column {protocol} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from [dbo].[Options] where [id]='91bb166b-e197-48f7-a430-7904e013b30c')
begin
	exec sp_executesql @statement = N'
    insert into [dbo].[Options] values(''91bb166b-e197-48f7-a430-7904e013b30c'', ''lock_info'', ''<CLockInfo/>'')
    print ''Insert item into [dbo].[Options] table'''
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'is_full')
begin
    alter table dbo.ObjectsInBackups add is_full bit default 1 not null
    print 'New column {is_full} has been successfully added to dbo.ObjectsInBackups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'reference')
begin
    alter table dbo.Hosts add reference nvarchar(1024) DEFAULT '' NOT null
    print 'New column {reference} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'api_version')
begin
    alter table dbo.Hosts add api_version int DEFAULT 0 NOT null
    print 'New column {api_version} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'approx_size')
begin
    alter table dbo.ObjectsInJobs add approx_size bigint DEFAULT 0 NOT null
    print 'New column {approx_size} has been successfully added to dbo.ObjectsInJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'location')
begin
    alter table dbo.ObjectsInJobs add location nvarchar(1024) default '' not null
    print 'New column {location} has been successfully added to dbo.ObjectsInJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BObjects]') and [name] = 'guest_os')
begin
    alter table dbo.BObjects add guest_os xml DEFAULT '' not null
    print 'New column {guest_os} has been successfully added to dbo.BObjects table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[LicensedHosts]') and [name] = 'type')
begin
    alter table dbo.LicensedHosts add type int DEFAULT 0 NOT null
    print 'New column {type} has been successfully added to dbo.LicensedHosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'mode')
begin
    alter table dbo.BSessionInfo add mode int DEFAULT 0 NOT null
    print 'New column {mode} has been successfully added to dbo.BSessionInfo table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'target_file')
begin
    alter table dbo.BJobs ALTER COLUMN target_file nvarchar(2000) null
    print 'Column {target_file} has been successfully modified at dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'creation_time')
begin
    alter table dbo.ObjectsInBackups add creation_time DATETIME DEFAULT '01.01.1900' NOT null
    print 'New column {creation_time} has been successfully added to dbo.ObjectsInBackups table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'object_name')
begin
    alter table dbo.BSessionInfo ALTER COLUMN object_name nvarchar(2000)
    print 'Column {object_name} has been successfully modified at dbo.BSessionInfo table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'target_dir')
begin
    alter table dbo.BJobs ALTER COLUMN target_dir nvarchar(2000)
    print 'Column {target_dir} has been successfully modified at dbo.BJobs table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BObjects]') and [name] = 'object_name')
begin
    alter table dbo.BObjects ALTER COLUMN object_name nvarchar(2000) null
    print 'Column {object_name} has been successfully modified at dbo.BObjects table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BObjects]') and [name] = 'object_id')
begin
    alter table dbo.BObjects ALTER COLUMN object_id nvarchar(2000)
    print 'Column {object_id} has been successfully modified at dbo.BObjects table'
end
GO
if not exists (select * from dbo.Version where current_version >= 60)
	update BJobs set options.modify('replace value of (/BackupJobOptions/RunManually/text())[1] with "true"')
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'usn')
begin
    alter table dbo.Backups add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Backups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'usn')
begin
    alter table dbo.BJobs add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.BJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BObjects]') and [name] = 'usn')
begin
    alter table dbo.BObjects add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.BObjects table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'usn')
begin
    alter table dbo.BSessionInfo add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'usn')
begin
    alter table dbo.BSessions add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Folder_Host]') and [name] = 'usn')
begin
    alter table dbo.Folder_Host add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Folder_Host table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Folders]') and [name] = 'usn')
begin
    alter table dbo.Folders add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Folders table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'usn')
begin
    alter table dbo.Hosts add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[LicensedHosts]') and [name] = 'usn')
begin
    alter table dbo.LicensedHosts add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.LicensedHosts table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'usn')
begin
    alter table dbo.ObjectsInBackups add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.ObjectsInBackups table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'usn')
begin
    alter table dbo.ObjectsInJobs add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.ObjectsInJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Soap_creds]') and [name] = 'usn')
begin
    alter table dbo.Soap_creds add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Soap_creds table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [name] = 'usn')
begin
    alter table dbo.Ssh_creds add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Ssh_creds table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Options]') and [name] = 'usn')
begin
    alter table dbo.Options add usn bigint not null default 0
    print 'New column {usn} has been successfully added to dbo.Options table'
end
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReplicationInfo]') AND type in (N'U'))
BEGIN
	CREATE TABLE ReplicationInfo (
	[base_id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
	[usn] bigint not null default 1)
END
GO
if (select count(*) from [dbo].[ReplicationInfo]) = 0
begin
	insert into [dbo].[ReplicationInfo](usn)values(1)
end
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TombStones]') AND type in (N'U'))
BEGIN
	CREATE TABLE TombStones (
	[uid] [uniqueidentifier] NOT NULL,
	[table_name] nvarchar(255) not null,
	[date] [datetime] NOT NULL,
	[usn] bigint primary key not null)
END
GO
if exists (select * from sys.sysobjects where id = OBJECT_ID(N'[dbo].[InsertTombStone]'))
DROP PROCEDURE [dbo].[InsertTombStone]
GO
CREATE PROCEDURE [dbo].[InsertTombStone] 
    @table_name nvarchar(50),
    @row_id uniqueidentifier,
    @usn bigint
AS
BEGIN
    SET NOCOUNT ON;
    
    declare @date_time datetime
	set @date_time = GETDATE()	
	
	insert into TombStones ([uid], [table_name], [date], [usn])values(@row_id, @table_name, @date_time, @usn)
END
GO
if exists (select * from sys.sysobjects where id = OBJECT_ID(N'[dbo].[TrackChange]'))
DROP PROCEDURE [dbo].[TrackChange]
GO
begin
    exec sp_executesql @statement = N'
    CREATE PROCEDURE [dbo].[TrackChange] 
	    @table_name nvarchar(50),
	    @row_id uniqueidentifier,
	    @change_type int
    AS
    BEGIN
	    SET NOCOUNT ON;
    	
		update ReplicationInfo set usn = usn + 1
    	
		declare @usn bigint, @sql_query nvarchar (1000)
		set @sql_query = ''set @usn = (select usn-1 from ReplicationInfo)''
		exec sp_executesql @sql_query,N''@usn bigint output'', @usn output	
		
		if @change_type = 2
		begin
			exec [dbo].[InsertTombStone] @table_name, @row_id, @usn    
		end 
		
		if @change_type = 0 OR @change_type = 1
		begin
			set @sql_query = ''update ['' + @table_name + ''] set usn = @usn where id = @row_id''
			exec sp_executesql @sql_query,N''@usn bigint, @row_id uniqueidentifier'', @usn, @row_id
		end

    END
    '
end
GO
if not exists (select * from syscolumns where [id] = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'type')
begin
    alter table [dbo].[ObjectsInJobs] add [type] int DEFAULT 0 NOT null
    print 'New column {type} has been successfully added to dbo.ObjectsInJobs table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'job_source_type')
begin
	exec sp_executesql @statement = N'
    alter table [dbo].[BJobs] add [job_source_type] int DEFAULT 0 NOT null

    alter table [dbo].[BSessions] add [job_source_type] int DEFAULT 0 NOT null

    alter table [dbo].[Backups] add [job_source_type] int DEFAULT 0 NOT null
	'
	exec sp_executesql @statement = N'
	update [dbo].[BJobs] set [job_source_type] = 0, [type] = 0 where [type] = 0
	update [dbo].[BJobs] set [job_source_type] = 3, [type] = 2 where [type] = 1
	update [dbo].[BJobs] set [job_source_type] = 0, [type] = 1 where [type] = 2 and [job_source_type] <> 3
	update [dbo].[BJobs] set [job_source_type] = 1, [type] = 0 where [type] = 3
	update [dbo].[BJobs] set [job_source_type] = 1, [type] = 1 where [type] = 4
	update [dbo].[BJobs] set [job_source_type] = 2, [type] = 0 where [type] = 5
	update [dbo].[BJobs] set [job_source_type] = 2, [type] = 1 where [type] = 6

	update [dbo].[BSessions] set [job_source_type] = 0, [job_type] = 0 where [job_type] = 0
	update [dbo].[BSessions] set [job_source_type] = 3, [job_type] = 2 where [job_type] = 1
	update [dbo].[BSessions] set [job_source_type] = 0, [job_type] = 1 where [job_type] = 2 and [job_source_type] <> 3
	update [dbo].[BSessions] set [job_source_type] = 1, [job_type] = 0 where [job_type] = 3
	update [dbo].[BSessions] set [job_source_type] = 1, [job_type] = 1 where [job_type] = 4
	update [dbo].[BSessions] set [job_source_type] = 2, [job_type] = 0 where [job_type] = 5
	update [dbo].[BSessions] set [job_source_type] = 2, [job_type] = 1 where [job_type] = 6

	update [dbo].[Backups] set [job_source_type] = 0, [job_type] = 0 where [job_type] = 0
	update [dbo].[Backups] set [job_source_type] = 3, [job_type] = 2 where [job_type] = 1
	update [dbo].[Backups] set [job_source_type] = 0, [job_type] = 1 where [job_type] = 2 and [job_source_type] <> 3
	update [dbo].[Backups] set [job_source_type] = 1, [job_type] = 0 where [job_type] = 3
	update [dbo].[Backups] set [job_source_type] = 1, [job_type] = 1 where [job_type] = 4
	update [dbo].[Backups] set [job_source_type] = 2, [job_type] = 0 where [job_type] = 5
	update [dbo].[Backups] set [job_source_type] = 2, [job_type] = 1 where [job_type] = 6
	'
end
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Security.Roles]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Security.Roles]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Security_Roles_id]  DEFAULT (newid()),
			[name] [nvarchar](50) NOT NULL
			
		    CONSTRAINT [PK_Backup_Security_Roles] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END
GO
	
	
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Security.RoleAccounts]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Security.RoleAccounts]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Security_RoleAccounts_id]  DEFAULT (newid()),
			[role_id] [uniqueidentifier] NOT NULL,
			[account_id] [uniqueidentifier] NOT NULL
			
		    CONSTRAINT [PK_Backup_Security_RoleAccounts] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END
GO	
	
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Security.Accounts]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Security.Accounts]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Security_Accounts_id]  DEFAULT (newid()),
			[name] [nvarchar](50) NOT NULL,
			[sid] [nvarchar](184) NOT NULL,
			[nt4_name] [nvarchar](100) NOT NULL,
			[type] [int] NOT NULL
			
		    CONSTRAINT [PK_Backup_Security_Accounts] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END	
GO	
	
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Security.RolePermissions]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Security.RolePermissions]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Security_RolePermissions_id]  DEFAULT (newid()),
			[role_id] [uniqueidentifier] NOT NULL,
			[permission] [int] NOT NULL
			
		    CONSTRAINT [PK_Backup_Security_RolePermissions] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END
GO

/********************************************************/
/*               SECURITY									*/
BEGIN					
	DECLARE @localAdminsAccountId uniqueidentifier
	SELECT @localAdminsAccountId = '38E4B8DF-65B5-4d3c-9A26-86F9142AE26F'

	IF NOT EXISTS (SELECT * FROM [dbo].[Backup.Security.Accounts] WHERE [dbo].[Backup.Security.Accounts].[id] = @localAdminsAccountId )
		BEGIN
			INSERT INTO [dbo].[Backup.Security.Accounts]( [id], [name], [sid], [nt4_name], [type])
			VALUES ( @localAdminsAccountId, N'Local administrators', N'S-1-5-32-544', 'Administrators', 1 )						
		END
		


	--  Permission types
	DECLARE @permRepDataExport int
	SELECT @permRepDataExport = 1
	
	DECLARE @permJobsMgmt int
	SELECT @permJobsMgmt = 2

	--  Backup Administrator 
	DECLARE @BackupAdminRoleId uniqueidentifier
	SELECT @BackupAdminRoleId = '5FF0E0EB-45CF-48cc-9677-7613FC79BC11'
	IF NOT EXISTS (SELECT * FROM [dbo].[Backup.Security.Roles] WHERE [dbo].[Backup.Security.Roles].[id]=@BackupAdminRoleId)
		BEGIN			
			INSERT INTO [dbo].[Backup.Security.Roles]( [id], [name] )
			VALUES( @BackupAdminRoleId, 'Veeam Backup Administrator' )
			
			-- Add permissions
			INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
			VALUES( NEWID(), @BackupAdminRoleId, @permRepDataExport )
			
			INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
			VALUES( NEWID(), @BackupAdminRoleId, @permJobsMgmt )
			
			-- Add administrators to this role
			INSERT INTO [dbo].[Backup.Security.RoleAccounts]( [id], [role_id], [account_id] )
			VALUES( NEWID(), @BackupAdminRoleId, @localAdminsAccountId )
			
		END
		
	--  Backup Operator 
	DECLARE @BackupOperatorRoleId uniqueidentifier
	SELECT @BackupOperatorRoleId = '8EFD7AE8-03D5-44d1-A7F7-19E728EEB96D'
	IF NOT EXISTS (SELECT * FROM [dbo].[Backup.Security.Roles] WHERE [dbo].[Backup.Security.Roles].[id]=@BackupOperatorRoleId)
		BEGIN			
			INSERT INTO [dbo].[Backup.Security.Roles]( [id], [name] )
			VALUES( @BackupOperatorRoleId, 'Veeam Backup Operator' )
			
			-- Add permissions
			INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
			VALUES( NEWID(), @BackupOperatorRoleId, @permJobsMgmt )
			
		END
	
	--	Backup Viewer
	DECLARE @RepCollectorRoleId uniqueidentifier
	SELECT @RepCollectorRoleId = '3C5720EC-BADB-4a66-B1EC-EB4037DAD657'
	IF NOT EXISTS (SELECT * FROM [dbo].[Backup.Security.Roles] WHERE [dbo].[Backup.Security.Roles].[id]=@RepCollectorRoleId )
		BEGIN
			INSERT INTO [dbo].[Backup.Security.Roles]( [id], [name] )
			VALUES( @RepCollectorRoleId, 'Veeam Backup Viewer' )
			
			-- Add permissions
			INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
			VALUES( NEWID(), @RepCollectorRoleId, @permRepDataExport )														
			
			-- Add administrators to this role
			--INSERT INTO [dbo].[Backup.Security.RoleAccounts]( [id], [role_id], [account_id] )
			--VALUES( NEWID(), @RepCollectorRoleId, @localAdminsAccountId )
		END
END
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'included_size')
begin
    alter table dbo.BJobs add included_size bigint not null default 0
    print 'New column {included_size} has been successfully added to dbo.BJobs table'
end
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'excluded_size')
begin
    alter table dbo.BJobs add excluded_size bigint not null default 0
    print 'New column {excluded_size} has been successfully added to dbo.BJobs table'
end
GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetDbReplicationInfo]') AND type in (N'P'))
	BEGIN
		DROP PROCEDURE [dbo].[GetDbReplicationInfo]
	END
GO
	CREATE PROCEDURE [dbo].[GetDbReplicationInfo]
		@dbInstanceId uniqueidentifier OUTPUT,
		@highestUsn bigint OUTPUT
		
	AS
	BEGIN	
		SET NOCOUNT ON;
		SELECT @dbInstanceId = base_id, @highestUsn = usn FROM dbo.ReplicationInfo

		IF @dbInstanceId is NULL
		BEGIN
			RAISERROR('The database replication identity not configured yet.', 9, 1)		
		END
	END
GO	
	
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'avg_speed')
begin
    alter table dbo.BSessions add avg_speed bigint not null default 0
    print 'New column {avg_speed} has been successfully added to dbo.BSessions table'
end
GO
--if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'avg_speed')
--begin
--	exec sp_executesql @statement = N'
--    UPDATE [dbo].[BSessions]
--	SET [dbo].[BSessions].[avg_speed] = 
--		CASE 
--			WHEN [dbo].[BSessions].[end_time] > [dbo].[BSessions].[creation_time] AND DATEDIFF(second, [dbo].[BSessions].[creation_time], [dbo].[BSessions].[end_time]) > 0 AND [dbo].[BSessions].[avg_speed] = 0
--				THEN [dbo].[BSessions].[processed_size] / DATEDIFF(second, [dbo].[BSessions].[creation_time], [dbo].[BSessions].[end_time])
--			ELSE 0
--		END'
--end
--GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'avg_speed')
begin
    alter table dbo.BSessionInfo add avg_speed bigint not null default 0
    print 'New column {avg_speed} has been successfully added to dbo.BSessionInfo table'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'avg_speed')
begin
	exec sp_executesql @statement = N'
    UPDATE [dbo].[BSessionInfo]
	SET [dbo].[BSessionInfo].[avg_speed] = 
		CASE 
			WHEN [dbo].[BSessionInfo].[end_time] > [dbo].[BSessionInfo].[creation_time] AND DATEDIFF(second, [dbo].[BSessionInfo].[creation_time], [dbo].[BSessionInfo].[end_time]) > 0 AND [dbo].[BSessionInfo].[avg_speed] = 0
				THEN [dbo].[BSessionInfo].[processed_size] / DATEDIFF(second, [dbo].[BSessionInfo].[creation_time], [dbo].[BSessionInfo].[end_time])
			ELSE 0
		END'
end
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BObjects]') and [name] = 'path')
begin
    alter table dbo.BObjects add path nvarchar(400) not null default ''
    print 'New column {path} has been successfully added to dbo.BObjects table'
end
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'approx_size')
begin
    alter table dbo.ObjectsInBackups add approx_size bigint DEFAULT 0 NOT null
    print 'New column {approx_size} has been successfully added to dbo.ObjectsInBackups table'
end
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInBackups]') and [name] = 'proccess_id')
begin
    alter table dbo.ObjectsInBackups add proccess_id int DEFAULT -1 NOT null
    print 'New column {proccess_id} has been successfully added to dbo.ObjectsInBackups table'
end

GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'schedule_enabled')
begin
    alter table dbo.BJobs add schedule_enabled bit default 1 not null
    print 'New column {schedule_enabled} has been successfully added to dbo.BJobs table'
end
GO

IF exists ( select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='ObjectsInBackups' and COLUMN_NAME='next_id' )
BEGIN
	ALTER TABLE [dbo].[ObjectsInBackups] DROP COLUMN next_id
END
GO
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[onBackupDelete]'))
	drop trigger [dbo].[onBackupDelete]
GO
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[onSessionDelete]'))
	drop trigger [dbo].[onSessionDelete]
GO

if exists(select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [length]<1024 and [name]='password')
begin
	ALTER TABLE [dbo].[Ssh_creds] ALTER COLUMN [password] NVARCHAR(512)
	print 'Column type {password} has been successfully changed to NVARCHAR(512)'
end
GO

if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Ssh_creds]') and [length]<1024 and [name]='rootpassword')
begin
	ALTER TABLE [dbo].[Ssh_creds] ALTER COLUMN [rootpassword] NVARCHAR(512)
	print 'Column type {rootpassword} has been successfully changed to NVARCHAR(512)'
end
GO

if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Soap_creds]') and [length]<1024 and [name]='password')
begin
	ALTER TABLE [dbo].[Soap_creds] ALTER COLUMN [password] NVARCHAR(512)
	print 'Column type {password} has been successfully changed to NVARCHAR(512)'
end
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'win_creds')
begin
    alter table dbo.Hosts add win_creds xml DEFAULT '' NOT null
    print 'New column {win_creds} has been successfully added to dbo.Hosts table'
end
GO
if not exists (select * from [dbo].[Options] where [id]='91bb166b-e197-48f7-a430-7904e013b30d')
begin
	exec sp_executesql @statement = N'
    insert into [dbo].[Options] ([id], [name], [value]) values(''91bb166b-e197-48f7-a430-7904e013b30d'', ''threshold'', ''<CThresholdInfo/>'')
    print ''Insert item into [dbo].[Options] table'''
end
GO
update ObjectsInBackups set inside_dir = '' from [Backups] where [ObjectsInBackups].backup_id = [Backups].id AND [Backups].job_type = 1 AND [ObjectsInBackups].inside_dir <> ''
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessionInfo]') and [name] = 'change_tracking')
begin
    alter table dbo.BSessionInfo add change_tracking bit DEFAULT 0 NOT null
    print 'New column {change_tracking} has been successfully added to dbo.BSessionInfo table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'is_startfull')
begin
    alter table dbo.BSessions add is_startfull bit DEFAULT 0 NOT null
    print 'New column {is_startfull} has been successfully added to dbo.BSessions table'
end
GO
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backups]') and [name] = 'is_last')
begin
    alter table dbo.Backups add is_last bit DEFAULT 0 NOT null
    print 'New column {is_last} has been successfully added to dbo.Backups table'
end
GO
--set 'is_last' value only one time
if not exists (select * from [dbo].[Version] where [current_version] >= 88)
begin
	update Backups set is_last = 1 where id in
	(select id from Backups where is_rollback = 0)
end
GO
--
exec sp_executesql @statement = N'DISABLE TRIGGER u_ObjectsInBackups ON ObjectsInBackups'
exec sp_executesql @statement = N'
update oib
set oib.creation_time = b.creation_time
from ObjectsInBackups oib, Backups b
where oib.creation_time = ''1900-01-01 00:00:00.000''
and oib.backup_id = b.id
'
exec sp_executesql @statement = N'ENABLE TRIGGER u_ObjectsInBackups ON ObjectsInBackups'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.Leases]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.Leases] (
	[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
	[init_time] datetime NOT NULL,
	[ttl_min] int NOT NULL,
	[never_expires] [bit] NOT NULL )
END
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.VmMount]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.VmMount] (
	[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
	[lease_id] [uniqueidentifier] NOT NULL,
	[action_state] int NOT NULL,
	[restore_point_id] [uniqueidentifier] NOT NULL,
	[nfs_share_name] nvarchar(max) NOT NULL,
	[nfs_relative_path] nvarchar(max) NOT NULL,
	[backup_mount_id] [uniqueidentifier]
	)
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.VmRegistration]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.VmRegistration] 
	(
		[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
		[lease_id] [uniqueidentifier] NOT NULL,
		[action_state] int NOT NULL,
		[target_host_name] nvarchar(max) NOT NULL,
		[target_host_id] uniqueidentifier NOT NULL,
		[vm_name] nvarchar(max) NOT NULL,
		[vm_moref] nvarchar(128) NOT NULL DEFAULT(N''),
		[relative_target_folder_path] nvarchar(max) NOT NULL,
		[vmx_file_path] nvarchar(max) NOT NULL,
		[target_storage_ref] nvarchar(max) NOT NULL,
		[target_respool_ref] nvarchar(max)
	)
END
GO

IF NOT EXISTS (SELECT * FROM  [dbo].[Folders] WHERE [id] = '32E53DC4-62EA-47b4-8E02-88509707D587')
BEGIN
	INSERT INTO [dbo].[Folders] ([id], [parent_id], [name]) VALUES ('32E53DC4-62EA-47b4-8E02-88509707D587',NULL,'DRGroups')
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VirtualLabs]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[VirtualLabs] (
	[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
	[id_onhost] [uniqueidentifier] UNIQUE NOT NULL,
	[name] nvarchar(255) NOT NULL,
	[description] nvarchar(1024) NOT NULL,
	[host_id] [uniqueidentifier] NOT NULL,
	[vm_ref] nvarchar(1024) NOT NULL,
	[usn] bigint not null default 0
	)
END
GO

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Folders]') and [name] = 'description')
begin
    alter table dbo.Folders add description nvarchar(1024) default '' not null
    print 'New column {description} has been successfully added to dbo.Folders table'
end
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.Locks]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.Locks] (
		[id] [uniqueidentifier] primary key NOT NULL,
		[lease_id] [uniqueidentifier] NOT NULL,
		[session_id] [uniqueidentifier] NOT NULL,
		[lock_type] [int] NOT NULL,
		[usn] bigint not null default 0)
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.LockItems]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.LockItems] (
		[lock_id] [uniqueidentifier] NOT NULL,
		[lock_item_id] [uniqueidentifier] NOT NULL)
END
GO

if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BSessions]') and [name] = 'overall_status')
begin
    ALTER TABLE [BSessions] ADD [state] int not null default -1
    exec sp_rename '[dbo].[BSessions].[overall_status]', 'result', 'COLUMN'
end
GO
if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'control')
begin
    declare @constraint nvarchar(100)
	declare @sqlcommand nvarchar(1000) 
	set @constraint = (select [name] from sys.default_constraints where [object_id] = (select cdefault from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'control'))
	set @sqlcommand = N'Alter table BJobs drop constraint ' + @constraint
	exec sp_sqlexec @sqlcommand
	alter table [BJobs] drop column [control]
end
GO
if not exists (select * from [dbo].[Version] where [current_version] >= 100)
    update [Version] set [current_version] = 100
GO
---------------------------------------------------





/********************************************************/
/*       COMMON STORED PROCEDURES					    */


---------------------------------------------------
--
PRINT N'Creating [dbo].[f_insert_as_first]'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[f_insert_as_first]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[f_insert_as_first]
GO
CREATE FUNCTION [dbo].[f_insert_as_first] (@x1 XML, @x2 XML)
RETURNS XML
AS
BEGIN
 
      -- insert into null value is impossible
      IF (@x1 is null)
            RETURN null
 
    -- if the value to insert is null or if @x1 contains no element we do nothing
      IF ((@x1.value('count(/*)','int') = 0) OR (@x2 is null))
            RETURN @x1
 
      -- if there is no element to insert we do nothing
      IF (@x2.value('count(/*)','int') = 0)
            RETURN @x1
 
      -- if any one of the two instances is not a valid document (more than one root element)
      -- we do nothing
      IF ((@x1.value('count(/*)','int') > 1) OR (@x2.value('count(/*)','int') > 1))
            RETURN @x1 
 
 
      DECLARE @x XML
      SET @x = CONVERT(XML, (CONVERT(nvarchar(MAX), @x1) + CONVERT(nvarchar(MAX), @x2)))
      SET @x.modify('insert /*[2] as first into /*[1]')
      SET @x.modify('delete /*[2]')
 
      RETURN @x
 
END
go
--
---------------------------------------------------



---------------------------------------------------
--
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IncrementUsn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[IncrementUsn]
GO
CREATE PROCEDURE [dbo].[IncrementUsn]
	@usn bigint OUTPUT
as 
BEGIN 
	update [dbo].[ReplicationInfo] set usn = usn + 1, @usn = usn
END
GO
--
---------------------------------------------------



/*      END OF COMMON STORED PROCEDURES	  	            */
/********************************************************/


---------------------------------------------------
--200
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 200)
BEGIN
	---------------------------------------------------	
	IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.Points]') AND type in (N'U'))
	BEGIN
		exec sp_executesql @stat = N'
			CREATE TABLE [dbo].[Backup.Model.Points](
				[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Points_id]  DEFAULT (newid()),
				[link_id] [uniqueidentifier] NULL,
				[num] [int] NOT NULL default 0,
				[creation_time] [datetime] NOT NULL,
				[type] [int] NOT NULL,
				[alg]  [int] NOT NULL,
				[group_id] uniqueidentifier NOT NULL,
				[backup_id] [uniqueidentifier] NULL,
				[usn] [bigint] NOT NULL default 0,
			 CONSTRAINT [PK_Points] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
			) ON [PRIMARY]
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 200; END	
END
GO
--200
---------------------------------------------------
--201
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 201)
BEGIN
	---------------------------------------------------	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.OIBs]') AND type in (N'U'))
	BEGIN
		exec sp_executesql @stat = N'
			CREATE TABLE [dbo].[Backup.Model.OIBs](
				[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_OIBs_id]  DEFAULT (newid()),
				[object_id] [uniqueidentifier] NOT NULL,
				[point_id] [uniqueidentifier] NULL,
				[storage_id] [uniqueidentifier] NULL,
				[link_id] [uniqueidentifier] NULL,
				[is_corrupted] [bit] NOT NULL,
				[is_consistent] [bit] NOT NULL,				
				[state] [int] NOT NULL,
				[type] [int] NOT NULL,
				[alg] [int] NOT NULL,
				[inside_dir] [nvarchar](400) NOT NULL,
				[creation_time] [datetime] NOT NULL,
				[vmname] [nvarchar](1000) NOT NULL,
				[guest_os_info] [xml],
				[memory] [bigint] NOT NULL,
				[approx_size] [bigint] NOT NULL,
				[process_id] [int] NOT NULL,
				[has_index] [bit] NOT NULL,
				[aux_data] [xml] NOT NULL default '''',
				[usn] [bigint] NOT NULL default 0,
			 CONSTRAINT [PK_OIBs] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
			) ON [PRIMARY]
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 201; END	
END
GO
--201
---------------------------------------------------
--202
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 202)
BEGIN
	---------------------------------------------------	
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.OIBs]') AND type in (N'U'))
	BEGIN
		exec sp_executesql @stat = N'
			ALTER TABLE [dbo].[Backup.Model.OIBs] ADD  DEFAULT ((-1)) FOR [process_id]
			ALTER TABLE [dbo].[Backup.Model.OIBs] ADD  DEFAULT (''empty'') FOR [inside_dir]
			ALTER TABLE [dbo].[Backup.Model.OIBs] ADD  DEFAULT (''01.01.1900'') FOR [creation_time]
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 202; END	
END
GO
--202
---------------------------------------------------
--203
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 203)
BEGIN
	---------------------------------------------------
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'Backup.Model.Backups') AND type in (N'U'))
	BEGIN
		exec sp_executesql @stat = N'
			CREATE TABLE [dbo].[Backup.Model.Backups](
				[id] [uniqueidentifier] NOT NULL,
				[job_id] [uniqueidentifier] NULL,
				[job_name] [nvarchar](255) NULL,
				[job_source_type] [int] NULL,
				[job_target_type] [int] NULL,
				[job_target_host_id] [uniqueidentifier] NULL,
				[job_target_host_protocol] [int] NULL,
				[usn] [bigint] NOT NULL default 0,
			 CONSTRAINT [PK_Backup] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
			) ON [PRIMARY]
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 203; END	
END
GO
--203
---------------------------------------------------
--204
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 204)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_Points_Backups]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.Points]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Points]  WITH CHECK ADD  CONSTRAINT [FK_Points_Backups] FOREIGN KEY([backup_id])
		REFERENCES [dbo].[Backup.Model.Backups] ([id])
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 204; END	
END
GO
--204
-----------------------------------------------------
--205
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 205)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_OIBs_Points]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.OIBs]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.OIBs]  WITH CHECK ADD  CONSTRAINT [FK_OIBs_Points] FOREIGN KEY([point_id])
		REFERENCES [dbo].[Backup.Model.Points] ([id])
	END
	' 
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 205; END	
END
GO
--205
-----------------------------------------------------
--206
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 206)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.Storages]'') AND type in (N''U''))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.Storages](
			[id] [uniqueidentifier] NOT NULL,
			[file_path] [nvarchar](1000) NULL,
			[backup_id] [uniqueidentifier] NULL,
			[host_id] [uniqueidentifier] NULL,
			[creation_time] [datetime] NOT NULL,
			[modification_time] [datetime] NOT NULL,			
			[stats] [xml] NULL,
			[version] [int] NOT NULL,
			[block_size] [int] NOT NULL default 1024,
			[usn] [bigint] NOT NULL default 0,			
		 CONSTRAINT [PK_Storages] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]
	END
	' 
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 206; END	
END
GO
--206
-----------------------------------------------------
--207
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 207)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_Storages_Backups]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.Storages]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Storages]  WITH CHECK ADD  CONSTRAINT [FK_Storages_Backups] FOREIGN KEY([backup_id])
		REFERENCES [dbo].[Backup.Model.Backups] ([id])
	END
	' 
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 207; END	
END
GO
--207
-----------------------------------------------------
--208
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 208)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_OIBs_Storages]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.OIBs]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.OIBs]  WITH CHECK ADD  CONSTRAINT [FK_OIBs_Storages] FOREIGN KEY([storage_id])
		REFERENCES [dbo].[Backup.Model.Storages] ([id])
	END
	' 
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 208; END	
END
GO
--208
-----------------------------------------------------
--209
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 209)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_OIBs_OIBs]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.OIBs]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.OIBs]  WITH CHECK ADD  CONSTRAINT [FK_OIBs_OIBs] FOREIGN KEY([link_id])
		REFERENCES [dbo].[Backup.Model.OIBs] ([id])
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 209; END	
END
GO
--209
-----------------------------------------------------
--210
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 210)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[Backup.TrackedActions.Leases]'') AND [name] = ''keepalive_time'')
	BEGIN
		ALTER TABLE [dbo].[Backup.TrackedActions.Leases] ADD keepalive_time DATETIME NOT NULL
	END	
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 210; END	
END
GO
--210
-----------------------------------------------------
--211
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 211)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_Points_Points]'') AND parent_object_id = OBJECT_ID(N''[dbo].[Backup.Model.Points]''))
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Points]  WITH CHECK ADD  CONSTRAINT [FK_Points_Points] FOREIGN KEY([link_id])
		REFERENCES [dbo].[Backup.Model.Points] ([id])
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 211; END	
END
GO
--211
-----------------------------------------------------
--212
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 212)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	CREATE PROCEDURE [dbo].[AddTrackChangeTriggers]
		@tablename nvarchar(1000),
		@include_insert bit = 1,
		@include_update bit = 1,
		@include_delete bit = 1
	AS
	BEGIN
		SET NOCOUNT ON;	
		declare @tables table (prefix nvarchar(255), owner nvarchar(255), tname nvarchar(255), ttype nvarchar(255), rem nvarchar(255))
		insert into @tables exec sp_tables null, ''dbo''

		declare @cur_tables cursor
		set @cur_tables = cursor local for select tname from @tables where tname = @tablename
		open @cur_tables

		declare @tname nvarchar(255)
		fetch next from @cur_tables into @tname

		declare @triggername nvarchar(255)
		select @triggername = replace (@tname, ''.'', ''_'')
	
		
				
		while @@fetch_status = 0
		begin
			if not (@tname = ''Version'' OR 
						@tname = ''sysdiagrams'' OR 
						@tname = ''log'')
			begin
			
	
				declare @text nvarchar(1024)
				declare @script nvarchar (1024)
				select @text = N''
				create trigger !!?? on [dbo].[##] for ^^ 
				as
				begin
					declare @id uniqueidentifier
					select @id = id from $$
					if not @id is null
						exec dbo.TrackChange ''''##'''', @id, %%
				end
				''
				
				if @include_insert = 1				
				IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[i_'' + @triggername + '']''))
				begin
					select @script = replace (@text, ''??'', @triggername)
					select @script = replace (@script, ''##'', @tname)
					select @script = replace (@script, ''!!'', ''i_'')
					select @script = replace (@script, ''^^'', ''insert'')
					select @script = replace (@script, ''$$'', ''inserted'')
					select @script = replace (@script, ''%%'', ''0'')
					print @script

					EXEC dbo.sp_executesql @statement = @script
					print ''Trigger after insert added '' + @tname
				end
		               
		        if @include_update = 1
				IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[u_'' + @triggername + '']''))
				begin
					select @script = replace (@text, ''??'', @triggername)
					select @script = replace (@script, ''##'', @tname)
					select @script = replace (@script, ''!!'', ''u_'')
					select @script = replace (@script, ''^^'', ''update'')
					select @script = replace (@script, ''$$'', ''inserted'')
					select @script = replace (@script, ''%%'', ''1'')
					print @script

					EXEC dbo.sp_executesql @statement = @script
					print ''Trigger after update added '' + @tname
				end
		        
		        if @include_delete = 1
				IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[d_'' + @triggername + '']''))
				begin
					select @script = replace (@text, ''??'', @triggername)
					select @script = replace (@script, ''##'', @tname)
					select @script = replace (@script, ''!!'', ''d_'')
					select @script = replace (@script, ''^^'', ''delete'')
					select @script = replace (@script, ''$$'', ''deleted'')
					select @script = replace (@script, ''%%'', ''2'')
					print @script

					EXEC dbo.sp_executesql @statement = @script
					print ''Trigger after delete added '' + @tname
				end
			end
			fetch next from @cur_tables into @tname
		end
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 212; END	
END
GO
--212
-----------------------------------------------------
--213
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 213)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.Backups]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.Backups'', 0, 1, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 213; END	
END
GO
--213
-----------------------------------------------------
--214
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 214)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.OIBs]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.OIBs'', 0, 1, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 214; END	
END
GO
--214
-----------------------------------------------------
--215
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 215)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.Points]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.Points'', 0, 1, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 215; END
END
GO
--215
-------------------------------------------------------
--216
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 216)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.Storages]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.Storages'', 0, 1, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 216; END	
END
GO
--216
-----------------------------------------------------



-----------------------------------------------------
--227
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 227)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[HostsByJobs]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[HostsByJobs](
				[id] [uniqueidentifier] NOT NULL,
				[host_id] [uniqueidentifier] NULL,
				[job_id] [uniqueidentifier] NULL,
				[uuid] [nvarchar](255) NOT NULL,
				[usn] [bigint] NOT NULL DEFAULT 0
			 CONSTRAINT [PK_HostsByJobs] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
			) ON [PRIMARY]
		END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 227; END	
END
GO
--227
-----------------------------------------------------



-----------------------------------------------------
--228
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 228)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_HostsByJobs_Hosts]'') AND parent_object_id = OBJECT_ID(N''[dbo].[HostsByJobs]''))
		BEGIN
			ALTER TABLE [dbo].[HostsByJobs]  WITH CHECK ADD  CONSTRAINT [FK_HostsByJobs_Hosts] FOREIGN KEY([host_id])
			REFERENCES [dbo].[Hosts] ([id])
			ON DELETE CASCADE
		END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 228; END	
END
GO
--228
-----------------------------------------------------


-----------------------------------------------------
--229
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 229)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		IF NOT  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''[dbo].[FK_HostsByJobs_BJobs]'') AND parent_object_id = OBJECT_ID(N''[dbo].[HostsByJobs]''))
		BEGIN
			ALTER TABLE [dbo].[HostsByJobs]  WITH CHECK ADD  CONSTRAINT [FK_HostsByJobs_BJobs] FOREIGN KEY([job_id])
			REFERENCES [dbo].[BJobs] ([id])
			ON DELETE CASCADE
		END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 229; END	
END
GO
--229
-----------------------------------------------------



-----------------------------------------------------
--233
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 233)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[ObjectsInJobs]'') and [name] = ''disk_filter'')
		begin
			alter table dbo.ObjectsInJobs add disk_filter nvarchar(max) not null default ''''
			print ''New column {disk_filter} has been successfully added to dbo.ObjectsInJobs table''
		end
		if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[ObjectsInJobs]'') and [name] = ''update_vmx'')
		begin
			alter table dbo.ObjectsInJobs add update_vmx bit not null default ''false''
			print ''New column {update_vmx} has been successfully added to dbo.ObjectsInJobs table''
		end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 233; END	
END
GO
--233
-----------------------------------------------------



-----------------------------------------------------
--234
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 234)
BEGIN
	---------------------------------------------------
	IF NOT  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[i_HostsByJobs]'))
	BEGIN
		exec sp_executesql @stat = N'
			create trigger [dbo].[i_HostsByJobs] on [dbo].[HostsByJobs] for insert 
			as
			begin
				declare @id uniqueidentifier
				select @id = id from inserted
				if not @id is null
					exec dbo.TrackChange ''HostsByJobs'', @id, 0
			end
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 234; END	
END
GO
--234
-----------------------------------------------------


-----------------------------------------------------
--235
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 235)
BEGIN
	---------------------------------------------------
	IF NOT  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[u_HostsByJobs]'))
	BEGIN
		exec sp_executesql @stat = N'
			create trigger [dbo].[u_HostsByJobs] on [dbo].[HostsByJobs] for update 
			as
			begin
				declare @id uniqueidentifier
				select @id = id from inserted
				if not @id is null
					exec dbo.TrackChange ''HostsByJobs'', @id, 1
			end
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 235; END	
END
GO
--235
-----------------------------------------------------


-----------------------------------------------------
--236
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 236)
BEGIN
	---------------------------------------------------
	IF NOT  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[d_HostsByJobs]'))
	BEGIN
		exec sp_executesql @stat = N'
			create trigger [dbo].[d_HostsByJobs] on [dbo].[HostsByJobs] for delete 
			as
			begin
				declare @id uniqueidentifier
				select @id = id from deleted
				if not @id is null
					exec dbo.TrackChange ''HostsByJobs'', @id, 2
					
				if not exists (select * from [dbo].[HostsByJobs] where uuid in (select distinct uuid from deleted))
				begin
					delete [dbo].[LicensedHosts] where uuid in (select distinct uuid from deleted)
				end
			end
		'
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 236; END	
END
GO
--236
-----------------------------------------------------

-----------------------------------------------------
--237
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 237)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[Backup.TrackedActions.VmRegistration]'') AND [name] = ''need_find_new_vm'')
	BEGIN
		ALTER TABLE [dbo].[Backup.TrackedActions.VmRegistration] ADD need_find_new_vm bit NOT NULL
	END	
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 237; END	
END
GO
--237
-----------------------------------------------------


-----------------------------------------------------
--238
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 238)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[LicensedHosts]'') and [name] = ''lic_edition'')
	begin
		alter table dbo.LicensedHosts add lic_edition int DEFAULT 1 NOT null
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 238; END	
END
GO
--238
-----------------------------------------------------


-----------------------------------------------------
--240
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 240)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[LicensedHosts]'') and [name] = ''is_licensed'')
	begin
		alter table dbo.LicensedHosts add is_licensed bit DEFAULT 0 NOT null
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 240; END	
END
GO
--240
-----------------------------------------------------



-----------------------------------------------------
--241
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 241)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[DRRoles]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[DRRoles] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[name] nvarchar(max) NOT NULL,
			[effective_memory] [bigint] NOT NULL,
			[boot_delay] int NOT NULL,
			[test_script_file_full_name] nvarchar(max) NOT NULL
			)
		END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 241; END	
END
GO
--241
-----------------------------------------------------



-----------------------------------------------------
--242
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 242)
BEGIN
	---------------------------------------------------
	DECLARE @permJobsCtrl int
	SELECT @permJobsCtrl = 3

	DECLARE @permRestoreCtrl int
	SELECT @permRestoreCtrl = 4
	
	DECLARE @BackupAdminRoleId uniqueidentifier
	SELECT @BackupAdminRoleId = '5FF0E0EB-45CF-48cc-9677-7613FC79BC11'
	
	DECLARE @BackupOperatorRoleId uniqueidentifier
	SELECT @BackupOperatorRoleId = '8EFD7AE8-03D5-44d1-A7F7-19E728EEB96D'
	
	DECLARE @localAdminsAccountId uniqueidentifier
	SELECT @localAdminsAccountId = '38E4B8DF-65B5-4d3c-9A26-86F9142AE26F'
	
	DECLARE @ReplicaOperatorRoleId uniqueidentifier
	SELECT @ReplicaOperatorRoleId = 'B167C3AF-2262-4b6c-9861-0606FC0CB6B1'
	IF NOT EXISTS (SELECT * FROM [dbo].[Backup.Security.Roles] WHERE [dbo].[Backup.Security.Roles].[id]=@ReplicaOperatorRoleId)
		BEGIN			
			INSERT INTO [dbo].[Backup.Security.Roles]( [id], [name] )
			VALUES( @ReplicaOperatorRoleId, 'Veeam Restore Operator' )
			
			-- Add permissions
			INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
			VALUES( NEWID(), @ReplicaOperatorRoleId, @permRestoreCtrl )
			
		END

	-- Add permissions
	INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
	VALUES( NEWID(), @BackupAdminRoleId, @permRestoreCtrl )
	
	INSERT INTO [dbo].[Backup.Security.RolePermissions]( [id], [role_id], [permission] )
	VALUES( NEWID(), @BackupAdminRoleId, @permJobsCtrl )
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 242; END	
END
GO
--242
-----------------------------------------------------

-----------------------------------------------------
--244
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 244)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[LinkedJobs]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[LinkedJobs] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[job_id] [uniqueidentifier] NOT NULL,
			[linked_job_id] [uniqueidentifier] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT ((0))	
			)
		END
		
		IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[LinkedJobs]''))
		begin
			exec [dbo].[AddTrackChangeTriggers] N''LinkedJobs''
		end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 244; END	
END
GO
--244
-----------------------------------------------------

-----------------------------------------------------
--245
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 245)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobSessions]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[Backup.Model.JobSessions](
				[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
				[job_id] [uniqueidentifier] NULL,
				[job_name] [nvarchar](255) NOT NULL,
				[job_type] [int] NOT NULL DEFAULT ((0)),
				[creation_time] [datetime] NOT NULL,
				[end_time] [datetime] NOT NULL DEFAULT (''01.01.1900''),
				[state] [int] NOT NULL DEFAULT ((-1)),
				[result] [int] NOT NULL,				
				[control] [int] NOT NULL DEFAULT ((0)),
				[description] [text] NULL DEFAULT (''''),	
				[operation] [nvarchar](400) NOT NULL,	
				[progress] [int] NOT NULL DEFAULT ((0)),				
				[usn] [bigint] NOT NULL DEFAULT ((0)),
				[app_group_fail] [bit] NULL DEFAULT ((0)),
				[troubleshoot_mode] [bit] NULL DEFAULT ((0))
			)
		END
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[Backup.Model.RestoreJobSessions](
				[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
				[action] [int] NOT NULL DEFAULT 0,
				[usn] [bigint] NOT NULL DEFAULT 0
			 )
		END
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreTaskSessions]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[Backup.Model.RestoreTaskSessions](
				[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
				[session_id] [uniqueidentifier] NOT NULL,
				[object_name] [nvarchar](2000) NULL,
				[object_id] [uniqueidentifier] NULL,
				[status] [int] NOT NULL,
				[reason] [ntext] NULL,
				[creation_time] [datetime] NOT NULL,
				[end_time] [datetime] NOT NULL DEFAULT (''01.01.1900''), 
				[operation] [nvarchar](400) NOT NULL DEFAULT (''''),
				[usn] [bigint] NOT NULL DEFAULT 0
			 ) 
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 245; END	
END
GO
--245
-----------------------------------------------------

-----------------------------------------------------
--246
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 246)
BEGIN
	---------------------------------------------------
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VirtualLabs]') and [name] = N'usn')
		alter table dbo.VirtualLabs add usn  bigint NOT NULL default 0
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[DRRoles]') and [name] = N'usn')
		alter table dbo.DRRoles add usn  bigint NOT NULL default 0
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.VmMount]') and [name] = N'usn')
		alter table dbo.[Backup.TrackedActions.VmMount] add usn  bigint NOT NULL default 0
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.VmRegistration]') and [name] = N'usn')
		alter table dbo.[Backup.TrackedActions.VmRegistration] add usn  bigint NOT NULL default 0

	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 246; END	
END
GO
--246
-----------------------------------------------------


-----------------------------------------------------
--248
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 248)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.JobSessions'', 0, 0
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.RestoreJobSessions'', 0, 0
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreTaskSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.RestoreTaskSessions'', 0, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 248; END	
END
GO
--248
-----------------------------------------------------


-----------------------------------------------------
--249
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 249)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[VirtualLabs]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''VirtualLabs''
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[DRObjectsInFolders]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''DRObjectsInFolders''
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[DRRoles]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''DRRoles''
	end	
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 249; END	
END
GO
--249
-----------------------------------------------------
--252
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 252)
BEGIN
	CREATE TABLE [dbo].[Backup.Model.SbSessions](
		[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
		[preferred_date] [datetime] NOT NULL,	
		[usn] [bigint] NOT NULL DEFAULT ((0)),
		[power_off_vm_on_fail] BIT NULL DEFAULT(1)
	)


	CREATE TABLE [dbo].[Backup.Model.SbTaskSessions] (
		[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
		[drsession_id] [uniqueidentifier] NOT NULL,
		[type] int NOT NULL,
		[object_name] nvarchar(max) NOT NULL,
		[object_id] [uniqueidentifier] NOT NULL,
		[oib_id] [uniqueidentifier] NOT NULL,
		[overall_status] int NOT NULL,
		[description] nvarchar(max) NOT NULL,
		[start_time] DateTime NOT NULL,
		[finish_time] DateTime NOT NULL,
		[total_steps] int NOT NULL,
		[processed_steps] int NOT NULL,
		[powerOn_status] int NOT NULL,
		[heartbeat_status] int NOT NULL,
		[ping_status] int NOT NULL,
		[test_script_status] int NOT NULL,
		[powerOff_status] int NOT NULL,
		[test_script_error_code] int NOT NULL,
		
		[vm_ref] nvarchar(max) NOT NULL,
		
		[usn] bigint not null default 0,
		[percent] [int] NOT NULL DEFAULT ((0)),
		
		[appliance_ip] [nvarchar](80) NOT NULL DEFAULT (''),
		[subnet_ip] [nvarchar](80) NOT NULL DEFAULT (''),
		[subnet_mask] [nvarchar](80) NOT NULL DEFAULT (''),
		
		[vm_external_ip] [nvarchar](80) NOT NULL DEFAULT (''),
		[state] int not null,
		
		[order_num] [int] IDENTITY(0,1) NOT NULL,
		[control] [int] NOT NULL DEFAULT((0)),
		[leave_powered_on]    [bit] NOT NULL DEFAULT((0)),
		[oiag_id] [uniqueidentifier] NULL,
		[restore_counter] [int] NOT NULL DEFAULT(0)	
	)

	---------------------------------------------------
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 252; END	
END
GO
--252
-----------------------------------------------------

-----------------------------------------------------
--253
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 253)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.SbSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.SbSessions'', 0, 0
	end	
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.SbTaskSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.SbTaskSessions'', 0, 0
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 253; END	
END
GO
--253
-----------------------------------------------------


-----------------------------------------------------
--254
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 254)
BEGIN	
	---------------------------------------------------
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.JobRestoreVm]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.JobRestoreVm] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),

			[oibid] [uniqueidentifier] NOT NULL,
			[vmname] nvarchar(max) NOT NULL,
			[targethostid] [uniqueidentifier] NOT NULL,
			[targetstorageref] nvarchar(max) NOT NULL,
			[targetrespoolref] nvarchar(max) NOT NULL,
			[tspoweron] bit NOT NULL,
			[disktype] int NOT NULL,
	        
			[usn] bigint not null default 0
		)
	END
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.JobRestoreVmFiles]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.JobRestoreVmFiles] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),

			[oibid] [uniqueidentifier] NOT NULL,
			[filestorestore] nvarchar(max) NOT NULL,
			[targethostid] [uniqueidentifier] NOT NULL,
			[targetdir] nvarchar(max) NOT NULL,

			[usn] bigint not null default 0
		)
	END
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.JobRestoreFiles]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.JobRestoreFiles] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),

			[oibid] [uniqueidentifier] NOT NULL,

			[usn] bigint not null default 0
		)
	END
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.JobFailover]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.JobFailover] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),

			[oibid] [uniqueidentifier] NOT NULL,
			[failover] bit NOT NULL,
	        
			[usn] bigint not null default 0
		)
	END
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 254; END	
END
GO
--254
-----------------------------------------------------

-----------------------------------------------------
--255
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 255)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobRestoreVm]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.JobRestoreVm''
	end	
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobRestoreVmFiles]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.JobRestoreVmFiles''
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobRestoreFiles]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.JobRestoreFiles''
	end
	'
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.JobFailover]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.JobFailover''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 255; END	
END
GO
--255
-----------------------------------------------------


-----------------------------------------------------
--256
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 256)
BEGIN
	exec sp_executesql @stat = N'
	CREATE PROCEDURE [dbo].[GetJobScheduleOptions]
		@job_id uniqueidentifier
	AS
	BEGIN
		SET NOCOUNT ON;

		SELECT [dbo].[BJobs].[schedule]
		FROM [dbo].[BJobs]
		WHERE [dbo].[BJobs].[id] = @job_id

	END
	'

	exec sp_executesql @stat = N'
	CREATE PROCEDURE [dbo].[SetJobScheduleOptions]
		@job_id uniqueidentifier,
		@schedule_options XML
	AS
	BEGIN
		SET NOCOUNT ON;

		UPDATE [dbo].[BJobs] SET
			   [dbo].[BJobs].[schedule] = @schedule_options
		WHERE [dbo].[BJobs].[id] = @job_id

	END
	'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 256; END	
END	
GO
--256
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 257)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Hosts]'') and [name] = ''bios_uuid'')
	begin
		alter table dbo.Hosts add "bios_uuid" nvarchar(255) default null
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 257; END	
END		
GO
--257
---------------------------------------------------------------------------


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 259)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.BackupJobSessions]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.BackupJobSessions](
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[is_retry] [bit] NOT NULL DEFAULT 0,
			[total_objects] [int] NOT NULL  DEFAULT 0,
			[processed_objects] [int] NOT NULL DEFAULT 0,
			[total_size] [bigint] NOT NULL DEFAULT 0,
			[processed_size] [bigint] NOT NULL DEFAULT 0,
			[usn] [bigint] NOT NULL DEFAULT 0,
			[job_source_type] [int] NOT NULL DEFAULT 0,
			[avg_speed] [bigint] NOT NULL DEFAULT 0,
			[is_startfull] [bit] NOT NULL DEFAULT 0			)
	END

	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.BackupJobSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.BackupJobSessions'', 0, 0 
	end	
	'
	CREATE TABLE [dbo].[Backup.Model.BackupTaskSessions](
		[id] [uniqueidentifier] NOT NULL,
		[session_id] [uniqueidentifier] NOT NULL,
		[creation_time] [datetime] NOT NULL,
		[object_name] [nvarchar](2000) NULL,
		[status] [int] NOT NULL,
		[reason] [ntext] NULL,
		[object_id] [uniqueidentifier] NULL,
		[end_time] [datetime] NOT NULL DEFAULT ('01.01.1900'),
		[operation] [nvarchar](400) NOT NULL  DEFAULT (''),
		[total_objects] [int] NOT NULL DEFAULT 0,
		[processed_objects] [int] NOT NULL  DEFAULT 0,
		[total_size] [bigint] NOT NULL DEFAULT 0,
		[processed_size] [bigint] NOT NULL DEFAULT 0,
		[mode] [int] NOT NULL DEFAULT 0,
		[usn] [bigint] NOT NULL DEFAULT 0,
		[avg_speed] [bigint] NOT NULL DEFAULT 0,
		[change_tracking] [bit] NOT NULL DEFAULT 0
		)
		
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.BackupTaskSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.BackupTaskSessions'', 0, 0
	end	
	'
			
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 259; END	
END		
GO
--259
-----------------------------------------------------
--260

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 260)
BEGIN
    exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[VmssDatastores]'') AND type in (N''U''))
    BEGIN
	    CREATE TABLE [dbo].[VmssDatastores](
	    [id] [uniqueidentifier] primary key NOT NULL,
	    [esx_bios_uuid] [nvarchar](255) NOT NULL,
	    [datastore_name] [nvarchar](255) NOT NULL,
	   	[usn] [bigint] NOT NULL DEFAULT ((0))	    
	    ) ON [PRIMARY]
    END'
			
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 260; END	
END		
GO

--260
-----------------------------------------------------
--261

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 261)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[VmssDatastores]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''VmssDatastores''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 261; END	
END
GO
--261

-----------------------------------------------------
    
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 262)
BEGIN
    exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[VmssVms]'') AND type in (N''U''))
    BEGIN
		   CREATE TABLE [dbo].[VmssVms](
			[id] [uniqueidentifier] primary key NOT NULL,
			[vm_registration_name] [nvarchar]( 255 ) NOT NULL,
            [registration_host_id][uniqueidentifier] NOT NULL,           
            [oib]  [uniqueidentifier] NOT NULL,
			[xml_config] [nvarchar](2048) NOT NULL,				
			[vm_lease_id] [uniqueidentifier] NOT NULL,
			[session_id] [uniqueidentifier] NOT NULL,
			[mount_state] [int] NOT NULL,
			[ui_session_id][uniqueidentifier] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT ((0))
		) ON [PRIMARY] 	    
    END'
			
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 262; END	
END		
GO
--262
-----------------------------------------------------

--263
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 263)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[VmssVms]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''VmssVms''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 263; END	
END
GO
--263

-----------------------------------------------------
--264
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 264)
BEGIN
	exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[ObjectsInApplicationGroups]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[ObjectsInApplicationGroups] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[folder_id] [uniqueidentifier] NOT NULL,
			[object_id] [uniqueidentifier] NOT NULL,
			[order] [int] NOT NULL,
			[guest_os_info] [xml],
			[effective_memory] [bigint] NOT NULL,
			[options] [xml],
			[usn] [bigint] NOT NULL DEFAULT ((0))
			)
		END
	'	
	exec sp_executesql @stat= N'
		exec [dbo].[AddTrackChangeTriggers] N''ObjectsInApplicationGroups'', 0, 1, 0
	'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 264; END	
END
GO
-----------------------------------------------------
-----------------------------------------------------
--265
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 265)
BEGIN
	exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[SbVerificationRules]'') AND type in (N''U''))
		BEGIN
			CREATE TABLE [dbo].[SbVerificationRules] (
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[job_id] [uniqueidentifier] NOT NULL,
			[object_id] [uniqueidentifier] NOT NULL,
			[object_type] [int] NOT NULL,
			[options] [xml],
			[usn] [bigint] NOT NULL DEFAULT ((0))
			)
		END
	'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 265; END	
END
GO
-----------------------------------------------------
--266
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 266)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[SbTaskSessions]'') and [name] = ''test_scripts_results'')
	begin
		alter table [dbo].[Backup.Model.SbTaskSessions] add "test_scripts_results" xml		
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 266; END	
END		
GO

-----------------------------------------------------
--267
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 267)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''options'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [options] [xml] not null default ('''')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 267; END	
END		
GO

-----------------------------------------------------
--268
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 268)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''initiator_sid'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [initiator_sid] [nvarchar](255) not null default ('''')
	end'
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''initiator_name'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [initiator_name] [nvarchar](255) not null default ('''')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 268; END	
END		
GO

-----------------------------------------------------
--269
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 269)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreTaskSessions]'') and [name] = ''process'')
	begin
		alter table [dbo].[Backup.Model.RestoreTaskSessions] add [process] [xml] not null default ('''')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 269; END	
END		
GO

-----------------------------------------------------
--270
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 270)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''reason'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [reason] [nvarchar](max) not null default ('''')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 270; END	
END		
GO

-----------------------------------------------------
--271
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 271)
BEGIN
	if not exists (select * from [dbo].[Options] where [id]='326EE145-E5E9-40b6-9B2B-7CB8ACF93164')
	begin
		insert into [dbo].[Options] values('326EE145-E5E9-40b6-9B2B-7CB8ACF93164', 'sessionkeep', '<CSessionKeep xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Keep>12</Keep></CSessionKeep>', 0)
		print 'Insert item into [dbo].[Options] table'
	end
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 271; END	
END		
GO

-----------------------------------------------------
--272
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 272)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.JobSessions]'') and [name] = ''log_xml'')
	begin
		alter table [dbo].[Backup.Model.JobSessions] add [log_xml] [xml] not null default (''<Root TotalUsn="0" TotalId="0"></Root>'')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 272; END	
END		
GO


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 272)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.SbTaskSessions]'') and [name] = ''log_xml'')
	begin
		alter table [dbo].[Backup.Model.SbTaskSessions] add [log_xml] [xml] not null default (''<Root TotalUsn="0" TotalId="0"></Root>'')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 274; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
--275
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 275)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.TrackedActions.VmMount]'') and [name] = ''mount_folder'')
	begin
		alter table [dbo].[Backup.TrackedActions.VmMount] add [mount_folder] [nvarchar](max) not null default ('''')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 275; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 275)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[BSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''BSessions''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 276; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 276)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Options]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Options''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 277; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 277)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Track_changes]''))
	begin
		drop table [dbo].[Track_changes]
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 278; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 278)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.JobSessions]'') and [name] = ''lease_id'')
	begin
		alter table [dbo].[Backup.Model.JobSessions] add [lease_id] [uniqueidentifier] not null default (''00000000-0000-0000-0000-000000000000'')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 279; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 279)
BEGIN
	exec sp_executesql @stat = N'
	IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[Product]'') AND type in (N''U''))
	BEGIN
	CREATE TABLE [dbo].[Product](
		[product_name] [nvarchar](255) NOT NULL
	) ON [PRIMARY]
	INSERT INTO Product(product_name) VALUES (N''Veeam Backup and Replication'')
	END
	'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 280; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 283)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''files_log_xml'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [files_log_xml] [xml] not null default (''<Root TotalUsn="0" TotalId="0"></Root>'')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 283; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 284)
BEGIN
	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[BJobs]'') AND [name] = ''platform'')
	BEGIN
		ALTER TABLE [dbo].[BJobs] ADD platform int NOT NULL DEFAULT(0)
	END'	
		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 284; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 285)
BEGIN
	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[ObjectsInJobs]'') AND [name] = ''platform'')
	BEGIN
		ALTER TABLE [dbo].[ObjectsInJobs] ADD platform int NOT NULL DEFAULT(0)
	END'	
		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 285; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 286)
BEGIN
	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[BObjects]'') AND [name] = ''platform'')
	BEGIN
		ALTER TABLE [dbo].[BObjects] ADD platform int NOT NULL DEFAULT(0)
	END'	
		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 286; END	
END		
GO
--
-----------------------------------------------------















/********************************************************/
/*               DATA UPGRADE 40-50						*/



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 286)
BEGIN
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn.Backup50Upgrade.GetBackupsChainAsc]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
	DROP FUNCTION [dbo].[fn.Backup50Upgrade.GetBackupsChainAsc]
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 287; END	
END		
GO
--
-----------------------------------------------------




-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 287)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	CREATE FUNCTION [dbo].[fn.Backup50Upgrade.GetBackupsChainAsc] ( @id uniqueidentifier )
	RETURNS 
	@Result TABLE 
	(
		id UNIQUEIDENTIFIER, 
		rn int
	)
	AS
	BEGIN
		DECLARE @rn INT
		SET @rn = 1

		DECLARE @ChainAsc TABLE (id UNIQUEIDENTIFIER, parent_id UNIQUEIDENTIFIER, rn int)
		INSERT @ChainAsc(id, parent_id, rn)
		SELECT linked_rollback, id, @rn from Backups where id = @id

		WHILE @@RowCount <> 0
		BEGIN
			set @rn = @rn + 1
			INSERT @ChainAsc(id, parent_id, rn)
			select b.linked_rollback, b.id, @rn from Backups b, @ChainAsc bc
			where b.id = bc.id and bc.id != bc.parent_id AND bc.rn = @rn - 1
		END

		INSERT @Result(id, rn)
		select parent_id , rn from @ChainAsc
			
		RETURN 
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 288; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 288)
BEGIN
	---------------------------------------------------
	exec sp_executesql @stat = N'
	CREATE FUNCTION [dbo].[fn.Backup50Upgrade.GetNextLinkedObjectInBackup] ( @id uniqueidentifier )
	RETURNS uniqueidentifier
	AS
	BEGIN
		declare @linkId uniqueidentifier
		
		SELECT top 1 @linkId = oibs.id FROM 
			(SELECT * from [dbo].[fn.Backup50Upgrade.GetBackupsChainAsc]((SELECT TOP 1 b.id FROM backups b, [ObjectsInBackups] o WHERE o.[backup_id] = b.id AND o.id = @id))) backupsChain,
			[ObjectsInBackups] oibs,
			(SELECT * FROM ObjectsInBackups WHERE id = @id) oibs1
		WHERE
			oibs.[backup_id] = backupsChain.[id] AND
			oibs.object_id = oibs1.OBJECT_ID and backupsChain.rn <> 1
		order by backupsChain.rn
		
		return @linkId
	END
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 289; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 289)
BEGIN
	---------------------------------------------------
	declare @usn bigint
	
	declare @bid              uniqueidentifier 
	declare @bcreation_time   datetime
	declare @bis_rollback     bit
	declare @bhost_id         uniqueidentifier 
	declare @blinked_rollback uniqueidentifier 
	declare @bjob_name        nvarchar(255) 
	declare @bjob_id          uniqueidentifier 
	declare @bjob_type        int
	declare @bis_retry        bit
	declare @bfile_name       nvarchar(255)
	declare @bstats           xml
	declare @bversion         int
	declare @bjob_source_type int 
	declare @bis_last         bit

	declare @points_backups as table ([pid] uniqueidentifier, [bid] uniqueidentifier)


	--populate [dbo].[Backup.Model.Backups]
	DECLARE points_cursor CURSOR FOR
	SELECT 
		[id],
		[creation_time],
		[is_rollback],
		[host_id],
		[linked_rollback],
		[job_name],
		[job_id],
		[job_type],
		[is_retry],
		[file_name], 
		[stats],
		[version],
		[job_source_type],
		[is_last]
	FROM [dbo].[Backups]
	ORDER BY job_id, creation_time
	OPEN points_cursor
	FETCH NEXT FROM points_cursor into @bid, @bcreation_time, @bis_rollback, @bhost_id, @blinked_rollback, @bjob_name, @bjob_id, @bjob_type, @bis_retry, @bfile_name, @bstats, @bversion, @bjob_source_type, @bis_last
	WHILE @@FETCH_STATUS = 0
	BEGIN

		declare @backup_id uniqueidentifier	
		set @backup_id = null			

		if @bjob_id is not null
			select top 1 @backup_id = id from [dbo].[Backup.Model.Backups] where job_id = @bjob_id
		else
			select top 1 @backup_id = id from [dbo].[Backup.Model.Backups] where job_name = @bjob_name
			
		DECLARE @bhost_protocol int
		set @bhost_protocol = null
		select @bhost_protocol = protocol from [dbo].[Hosts] where id = @bhost_id

		if @backup_id is null
		BEGIN
			set @backup_id = newid()
			
			exec [dbo].[IncrementUsn] @usn OUTPUT
			insert [dbo].[Backup.Model.Backups]
				(id,
				 job_id, 
				 job_name, 
				 job_source_type, 
				 job_target_type, 
				 job_target_host_id,
				 job_target_host_protocol,
				 usn)
			select
				 @backup_id,
				 @bjob_id, 
				 @bjob_name, 
				 @bjob_source_type,
				 @bjob_type,
				 @bhost_id,
				 @bhost_protocol,
				 @usn
		END

		insert 
			@points_backups(pid, bid)
		select
			@bid, @backup_id
		
		FETCH NEXT FROM points_cursor into @bid, @bcreation_time, @bis_rollback, @bhost_id, @blinked_rollback, @bjob_name, @bjob_id, @bjob_type, @bis_retry, @bfile_name, @bstats, @bversion, @bjob_source_type, @bis_last
	END
	CLOSE points_cursor
	DEALLOCATE points_cursor
	--


	declare @bkpid       uniqueidentifier
	declare @bkpjob_id   uniqueidentifier
	declare @bkpjob_name nvarchar(255) 
	declare @bkpjob_source_type int
	declare @bkpjob_target_type int
	declare @bkptarget_host_id  uniqueidentifier

	--run through [dbo].[Backup.Model.Backups]
	DECLARE backups_cursor CURSOR FOR
	SELECT 
		[id],
		[job_id], 
		[job_name], 
		[job_source_type], 
		[job_target_type], 
		[job_target_host_id]
	FROM [dbo].[Backup.Model.Backups]

	OPEN backups_cursor
	FETCH NEXT FROM backups_cursor into @bkpid, @bkpjob_id, @bkpjob_name, @bkpjob_source_type, @bkpjob_target_type, @bkptarget_host_id
	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		declare @pnum int
		set     @pnum = 1

		declare @pgroup_id uniqueidentifier
		set     @pgroup_id = newid()

		--disable constraints
		ALTER TABLE [dbo].[Backup.Model.Points] NOCHECK CONSTRAINT [FK_Points_Points]
		ALTER TABLE [dbo].[Backup.Model.OIBs] NOCHECK CONSTRAINT [FK_OIBs_OIBs]

		--populate [dbo].[Backup.Model.Points]	
		DECLARE pnt_cursor CURSOR FOR
		SELECT 
			[id],
			[creation_time],
			[is_rollback],
			[host_id],
			[linked_rollback],
			[job_name],
			[job_id],
			[job_type],
			[is_retry],
			[file_name], 
			[stats],
			[version],
			[job_source_type],
			[is_last]
		FROM [dbo].[Backups]
		WHERE id in (select pid from @points_backups where bid = @bkpid)
		ORDER BY job_id, creation_time
		OPEN pnt_cursor
		
		FETCH NEXT FROM pnt_cursor into @bid, @bcreation_time, @bis_rollback, @bhost_id, @blinked_rollback, @bjob_name, @bjob_id, @bjob_type, @bis_retry, @bfile_name, @bstats, @bversion, @bjob_source_type, @bis_last
		WHILE @@FETCH_STATUS = 0
		BEGIN
					
			declare @palg  int
			set     @palg  = 1 --synthetic

			declare @ptype int
			set     @ptype = 1 --normal
			
			declare @plink_id uniqueidentifier
			set     @plink_id = @blinked_rollback
			
			declare @chain_finished bit
			set     @chain_finished = 0
		
		
			if @bis_rollback = 0
			begin
				set @ptype = 0
				if not exists (select id from [dbo].[Backups] where linked_rollback = @blinked_rollback and id <> linked_rollback)
				begin
				set @palg  = 0
				end
				set @plink_id = null
				set @chain_finished = 1
			end


			--
			exec [dbo].[IncrementUsn] @usn OUTPUT			
			insert [dbo].[Backup.Model.Points]
				(id, link_id, num, creation_time, type, alg, group_id, backup_id, usn)
			select
				 @bid, @plink_id, @pnum, @bcreation_time, @ptype, @palg, @pgroup_id, @bkpid, @usn
			--

			declare @oib_id            uniqueidentifier
			declare @oib_object_id     uniqueidentifier
			declare @oib_backup_id     uniqueidentifier
			declare @oib_filename      nvarchar(1000)
			declare @oib_is_corrupted  bit
			declare @oib_state         int
			declare @oib_inside_dir    nvarchar(400)
			declare @oib_is_full       bit
			declare @oib_creation_time datetime
			declare @oib_approx_size   bigint
			declare @oib_proccess_id   int
			
			DECLARE oib_cursor CURSOR FOR
			SELECT 
				[id],
				[object_id],
				[backup_id],
				[filename],
				[is_corrupted],
				[state],
				[inside_dir],
				[is_full],
				[creation_time],
				[approx_size],
				[proccess_id]
			FROM [dbo].[ObjectsInBackups]
			WHERE backup_id = @bid
			OPEN oib_cursor
			
			FETCH NEXT FROM oib_cursor into @oib_id, @oib_object_id, @oib_backup_id, @oib_filename, @oib_is_corrupted, @oib_state, @oib_inside_dir, @oib_is_full, @oib_creation_time, @oib_approx_size, @oib_proccess_id
			WHILE @@FETCH_STATUS = 0
			BEGIN		

				declare @storage_id uniqueidentifier
				set @storage_id = null
				
				
				select top 1 @storage_id = id 
				from
					[dbo].[Backup.Model.Storages]
				where
					backup_id = @bkpid and
					file_path = @oib_filename and
					host_id   = @bhost_id

				--populate [dbo].[Backup.Model.Storages]
				if @storage_id is null
				BEGIN
					set @storage_id = newid()
					
					exec [dbo].[IncrementUsn] @usn OUTPUT
					insert [dbo].[Backup.Model.Storages]		
					   (id,
						file_path,
						backup_id,
						host_id,
						creation_time,
						modification_time,
						stats,
						version,
						usn
						)
					select 
						@storage_id,
						@oib_filename,
						@bkpid,
						@bhost_id,
						@oib_creation_time,
						@oib_creation_time,
						@bstats,
						@bversion,
						@usn
				END
				--
				
				
				declare @oib_type int 
				declare @oib_alg int
				
				set @oib_type = 1 --rollback
				set @oib_alg  = 1 --synthetic
				
				if @bis_rollback = 0
				begin
				
					set @oib_type = 0 --full

					if (
						select count(*) from [dbo].[ObjectsInBackups] coibs, [dbo].[Backups] cbkps
						where
							coibs.object_id = @oib_object_id and
							coibs.backup_id = cbkps.id and
							cbkps.job_id = @bkpjob_id
					) = 1
					begin
						set @oib_alg  = 0 --full
					end
				end
				 		
				--populate [dbo].[Backup.Model.OIBs]
				exec [dbo].[IncrementUsn] @usn OUTPUT
				insert [dbo].[Backup.Model.OIBs]
					(id, 
					object_id, 
					point_id, 
					storage_id, 
					link_id, 
					is_corrupted, 
					is_consistent, 
					state, 
					type, 
					alg,
					inside_dir,
					creation_time,
					vmname,
					guest_os_info,
					memory,
					approx_size,
					process_id,
					has_index,
					usn)
				select
					@oib_id, 
					@oib_object_id, 
					@oib_backup_id, 
					@storage_id, 
					[dbo].[fn.Backup50Upgrade.GetNextLinkedObjectInBackup] (@oib_id), --link_id
					@oib_is_corrupted, 
					@oib_is_full, 
					@oib_state, 
					@oib_type, 
					@oib_alg,
					@oib_inside_dir,
					@oib_creation_time,
					o.object_name,
					o.guest_os,
					0,
					@oib_approx_size,
					@oib_proccess_id,
					0, -- has_index
					@usn
				from [dbo].[BObjects] o
				where
					o.id = @oib_object_id
				--
				
				FETCH NEXT FROM oib_cursor into @oib_id, @oib_object_id, @oib_backup_id, @oib_filename, @oib_is_corrupted, @oib_state, @oib_inside_dir, @oib_is_full, @oib_creation_time, @oib_approx_size, @oib_proccess_id
			END
			CLOSE oib_cursor
			DEALLOCATE oib_cursor	
			--


			set @pnum = @pnum + 1		
			if @chain_finished = 1 
			begin
				set @pgroup_id = newid()
			end
			
			FETCH NEXT FROM pnt_cursor into @bid, @bcreation_time, @bis_rollback, @bhost_id, @blinked_rollback, @bjob_name, @bjob_id, @bjob_type, @bis_retry, @bfile_name, @bstats, @bversion, @bjob_source_type, @bis_last
		END
		CLOSE pnt_cursor
		DEALLOCATE pnt_cursor	
		--
		
		--enable constraints
		ALTER TABLE [dbo].[Backup.Model.Points] CHECK CONSTRAINT [FK_Points_Points]
		ALTER TABLE [dbo].[Backup.Model.OIBs]   CHECK CONSTRAINT [FK_OIBs_OIBs]
		--
		
		FETCH NEXT FROM backups_cursor into @bkpid, @bkpjob_id, @bkpjob_name, @bkpjob_source_type, @bkpjob_target_type, @bkptarget_host_id
	END
	CLOSE backups_cursor
	DEALLOCATE backups_cursor
	--
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 290; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 290)
BEGIN
	---------------------------------------------------
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn.Backup50Upgrade.GetBackupsChainAsc]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
	DROP FUNCTION [dbo].[fn.Backup50Upgrade.GetBackupsChainAsc]
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn.Backup50Upgrade.GetNextLinkedObjectInBackup]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
	DROP FUNCTION [dbo].[fn.Backup50Upgrade.GetNextLinkedObjectInBackup]	
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 291; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- (16661 fix)
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 291)
BEGIN

	update 
		oij
	set 
		oij.disk_filter = j.disk_filter,
		oij.update_vmx = j.update_vmx
	from
		[dbo].[ObjectsInJobs] oij,
		(
			select 
				id,
				(
				case df
					when '' then '2000;2001;2002;2003;2004;2005;2006;2008;2009;2010;2011;2012;2013;2014;2015;2016;2017;2018;2019;2020;2021;2022;2024;2025;2026;2027;2028;2029;2030;2031;2032;2033;2034;2035;2036;2037;2038;2040;2041;2042;2043;2044;2045;2046;2047;2048;2049;2050;2051;2052;2053;2054;2056;2057;2058;2059;2060;2061;2062;2063'
					else df  end
				) disk_filter,
				update_vmx
			from
			(
				select 
					bj.id,
					bj.options.query('BackupJobOptions/DiskFilter').value('.', 'nvarchar(max)') df,
					bj.options.query('BackupJobOptions/UpdateVmxFromDiskFilter').value('.', 'bit') update_vmx
				from [dbo].[BJobs] bj
			) o
		) j(id, disk_filter, update_vmx)
	where 
		oij.job_id = j.id

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 292; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--(16662 fix)
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 292)
BEGIN

	declare @id uniqueidentifier
	declare @job_id uniqueidentifier
	declare @vss_options xml
	declare @ignore_errors bit
	declare @ignore_errors_str nvarchar(255)

	DECLARE vssoptions_cursor CURSOR FOR
	select
		oij.id,
		bj.id job_id,
		oij.vss_options vss_options,
		(case when bj.vss_options.exist('CVssOptions/IgnoreErrors') = 1 then bj.vss_options.query('CVssOptions/IgnoreErrors').value('.', 'bit') else 1 end) ignore_errors,
		(case when bj.vss_options.exist('CVssOptions/IgnoreErrors') = 1 then bj.vss_options.query('CVssOptions/IgnoreErrors').value('.', 'nvarchar(255)') else 'true' end) ignore_errors_str
	from
		[dbo].[BJobs] bj,
		[dbo].[ObjectsInJobs] oij
	where 
		bj.id = oij.job_id

	OPEN vssoptions_cursor

	FETCH NEXT FROM vssoptions_cursor into @id, @job_id, @vss_options, @ignore_errors,  @ignore_errors_str
	WHILE @@FETCH_STATUS = 0
	BEGIN		

	if @vss_options.exist('CVssOptions/IgnoreErrors') = 1
		begin
			SET @vss_options.modify('replace value of (CVssOptions/IgnoreErrors/text())[1] with sql:variable("@ignore_errors")')
		end
		else
		begin
			declare @ignore_errors_xml xml
			set @ignore_errors_xml = '<IgnoreErrors>' + @ignore_errors_str + '</IgnoreErrors>' 

			set @vss_options = [dbo].[f_insert_as_first] (@vss_options, @ignore_errors_xml)
		end
		
		
		update [dbo].[ObjectsInJobs]
		set vss_options = @vss_options
		where id = @id
		
		FETCH NEXT FROM vssoptions_cursor into @id, @job_id, @vss_options, @ignore_errors, @ignore_errors_str
	END

	CLOSE vssoptions_cursor
	DEALLOCATE vssoptions_cursor	
	--
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 293; END	
END		
GO
--
-----------------------------------------------------




-----------------------------------------------------
-- Upgrade data: Backup.Model.JobSessions
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 293)
BEGIN

declare @usn bigint

DECLARE bs_cursor CURSOR FOR
select
	bs.id,
	bs.job_id,
	bs.job_name,
	bs.job_type,
	bs.creation_time,
	bs.end_time,
	bs.state,
	bs.result,
	0,
	bs.description,
	bs.operation,
	bs.progress
from
	[dbo].[BSessions] bs

OPEN bs_cursor

declare @id uniqueidentifier
declare @job_id uniqueidentifier
declare @job_name nvarchar(255)
declare @job_type int
declare @creation_time datetime
declare @end_time datetime
declare @state int
declare @result int
declare @control int
declare @description varchar(max)
declare @operation nvarchar(400)
declare @progress int

FETCH NEXT FROM bs_cursor into @id, @job_id, @job_name, @job_type, @creation_time, @end_time, @state, @result, @control, @description, @operation, @progress
WHILE @@FETCH_STATUS = 0
BEGIN	
	exec [dbo].[IncrementUsn] @usn OUTPUT
	insert into 
		[dbo].[Backup.Model.JobSessions]
	(
		[id],
		[job_id],
		[job_name],
		[job_type],
		[creation_time],
		[end_time],
		[state],
		[result] ,
		[control],
		[description],
		[operation],
		[progress],
		[usn]
	)
	select
		@id,
		@job_id,
		@job_name,
		@job_type,
		@creation_time,
		@end_time,
		@state,
		@result,
		@control,
		@description,
		@operation,
		@progress,
		@usn
	FETCH NEXT FROM bs_cursor into @id, @job_id, @job_name, @job_type, @creation_time, @end_time, @state, @result, @control, @description, @operation, @progress
END

CLOSE bs_cursor
DEALLOCATE bs_cursor	
--

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 294; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- Upgrade data: Backup.Model.BackupJobSessions
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 294)
BEGIN

declare @usn bigint

declare @id uniqueidentifier
declare @is_retry bit
declare @total_objects int
declare @processed_objects int
declare @total_size bigint
declare @processed_size bigint
declare @job_source_type int
declare @avg_speed bigint
declare @is_startfull bit


DECLARE bs_cursor CURSOR FOR
select
	bs.id,
	bs.is_retry,
	bs.total_objects,
	bs.processed_objects,
	bs.total_size,
	bs.processed_size,
	bs.job_source_type,
	bs.avg_speed,
	bs.is_startfull
from
	[dbo].[BSessions] bs	

OPEN bs_cursor

FETCH NEXT FROM bs_cursor into @id, @is_retry, @total_objects, @processed_objects, @total_size, @processed_size, @job_source_type, @avg_speed, @is_startfull
WHILE @@FETCH_STATUS = 0
BEGIN	

	exec [dbo].[IncrementUsn] @usn OUTPUT
	insert into
	[dbo].[Backup.Model.BackupJobSessions](
		[id],
		[is_retry],
		[total_objects],
		[processed_objects],
		[total_size],
		[processed_size],
		[job_source_type],
		[avg_speed],
		[is_startfull],
		[usn]	
		)
	select
		@id,
		@is_retry,
		@total_objects,
		@processed_objects,
		@total_size,
		@processed_size,
		@job_source_type,
		@avg_speed,
		@is_startfull,
		@usn		
		
	FETCH NEXT FROM bs_cursor into @id, @is_retry, @total_objects, @processed_objects, @total_size, @processed_size, @job_source_type, @avg_speed, @is_startfull
END

CLOSE bs_cursor
DEALLOCATE bs_cursor	
--

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 295; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- Upgrade data: Backup.Model.BackupTaskSessions
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 295)
BEGIN

declare @usn bigint

declare @id uniqueidentifier
declare @session_id uniqueidentifier
declare @creation_time datetime
declare @object_name nvarchar(2000)
declare @status int
declare @reason nvarchar(max)
declare @object_id uniqueidentifier
declare @end_time datetime
declare @operation nvarchar(400)
declare @total_objects int
declare @processed_objects int
declare @total_size bigint
declare @processed_size bigint
declare @mode int
declare @avg_speed bigint
declare @change_tracking bit


DECLARE bts_cursor CURSOR FOR
select 
	bts.id,
	bts.session_id,
	bts.creation_time,
	bts.object_name,
	bts.status,
	bts.reason,
	bts.object_id,
	bts.end_time,
	bts.operation,
	bts.total_objects,
	bts.processed_objects,
	bts.total_size,
	bts.processed_size,
	bts.mode,
	bts.avg_speed,
	bts.change_tracking
from
	[dbo].[BSessionInfo] bts

OPEN bts_cursor

FETCH NEXT FROM bts_cursor into @id, @session_id, @creation_time, @object_name, @status, @reason, @object_id, @end_time, @operation, @total_objects, @processed_objects, @total_size, @processed_size, @mode, @avg_speed, @change_tracking
WHILE @@FETCH_STATUS = 0
BEGIN	

	exec [dbo].[IncrementUsn] @usn OUTPUT
	insert into [dbo].[Backup.Model.BackupTaskSessions]
	(
		[id],
		[session_id],
		[creation_time],
		[object_name],
		[status],
		[reason],
		[object_id],
		[end_time],
		[operation],
		[total_objects],
		[processed_objects],
		[total_size],
		[processed_size],
		[mode],
		[avg_speed],
		[change_tracking],
		[usn]
	)
	select 
		@id,
		@session_id, 
		@creation_time, 
		@object_name, 
		@status, 
		@reason, 
		@object_id, 
		@end_time, 
		@operation, 
		@total_objects, 
		@processed_objects, 
		@total_size, 
		@processed_size, 
		@mode, 
		@avg_speed, 
		@change_tracking,
		@usn
		
	FETCH NEXT FROM bts_cursor into @id, @session_id, @creation_time, @object_name, @status, @reason, @object_id, @end_time, @operation, @total_objects, @processed_objects, @total_size, @processed_size, @mode, @avg_speed, @change_tracking
END

CLOSE bts_cursor
DEALLOCATE bts_cursor	
--

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 296; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- Upgrade data: Failover
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 296)
BEGIN


declare @id uniqueidentifier
declare @object_id uniqueidentifier
declare @backup_id uniqueidentifier
declare @creation_time datetime
declare @state int

DECLARE failovered_oibs_cursor CURSOR FOR
select id, object_id, backup_id, creation_time, state from [dbo].[ObjectsInBackups]
where state = 1

OPEN failovered_oibs_cursor

FETCH NEXT FROM failovered_oibs_cursor into @id, @object_id, @backup_id, @creation_time, @state
WHILE @@FETCH_STATUS = 0
BEGIN	

	declare @options xml	
	declare @options_backup_name nvarchar(max)
	declare @options_oibdt datetime
	declare @options_oibid uniqueidentifier

	set @options = '
	<CVmReplicaFailoverInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
	<BackupName>none</BackupName>
	<OibDT>none</OibDT>
	<VmReplicaFailoverData>
	<OibId>none</OibId>
	</VmReplicaFailoverData>
	</CVmReplicaFailoverInfo>
	'

	select @options_backup_name = job_name from [dbo].[Backups] where id = @backup_id
	set    @options_oibdt = @creation_time
	set    @options_oibid = @id

	--SET @options.modify('replace value of (/CVmReplicaFailoverInfo/BackupName[1]/text())[1] with sql:variable("@options_backup_name")')
	--SET @options.modify('replace value of (/CVmReplicaFailoverInfo/OibDT[1]/text())[1] with sql:variable("@options_oibdt")')
	--SET @options.modify('replace value of (/CVmReplicaFailoverInfo/VmReplicaFailoverData/OibId[1]/text())[1] with sql:variable("@options_oibid")')

	set @options = 
	(
	select
		@options_backup_name as [BackupName],
		@options_oibdt as [OibDT],
		@options_oibid as [VmReplicaFailoverData/OibId]
	for xml path(''), root('CVmReplicaFailoverInfo'), type
	)
		
	declare @initiator_sid nvarchar(255)
	declare @initiator_name nvarchar(255)
	declare @reason nvarchar(max)
	declare @files_log_xml xml
	
	set @initiator_sid = ''
	set @initiator_name = ''
	set @reason = ''
	set @files_log_xml = '<Root TotalUsn="0" TotalId="0" />'

	declare @usn bigint
	
	declare @sess_id uniqueidentifier
	set @sess_id = newid()
	
	--[Backup.Model.RestoreJobSessions]
	--	
	
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	insert into
	[dbo].[Backup.Model.RestoreJobSessions]
	(
		[id],
		[action],
		[options],
		[initiator_sid],
		[initiator_name],
		[reason],		
		[files_log_xml],
		[usn]
	)
	select 
		@sess_id, 
		3,
		@options,
		@initiator_sid,
		@initiator_name,
		@reason,
		@files_log_xml,
		@usn
		
	--		
	--[Backup.Model.RestoreJobSessions]



	--[Backup.Model.JobSessions]
	--		
		
	declare @job_id uniqueidentifier
	declare @job_name nvarchar(max)
	declare @description nvarchar(max)
	
	set    @job_id  = newid()
	select @job_name = object_name from [dbo].[BObjects] where id = @object_id
	set    @description = ''
		
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	insert into
	[dbo].[Backup.Model.JobSessions](
		[id],
		[job_id],
		[job_name],
		[job_type],
		[creation_time],
		[state],
		[result],
		[control],
		[description],
		[operation],
		[progress],
		[usn]
	)
	SELECT
		@sess_id,
		@job_id,
		@job_name,
		7,  --job_type = Failover
		@creation_time,
		5,  --state = Working
		-1, --result = None 
		0,  
		@description,
		'',
		0,
		@usn
		
	--		
	--[Backup.Model.JobSessions]



	--[Backup.Model.BackupTaskSessions]
	--		

	declare @object_name nvarchar(max)
	select @object_name = object_name from [dbo].[BObjects] where id = @object_id

	exec [dbo].[IncrementUsn] @usn OUTPUT	
	insert into
	[dbo].[Backup.Model.RestoreTaskSessions](
		[id],
		[session_id],
		[object_name],
		[object_id],
		[status],
		[reason],
		[creation_time],
		[operation],
		[usn],
		[process]
	)
	select
		newid(),
		@sess_id,
		@object_name,
		'00000000-0000-0000-0000-000000000000',
		0, --ESessionStatus.Success
		'',
		@creation_time,
		'',
		@usn,
		''
	--		
	--[Backup.Model.BackupTaskSessions]


	FETCH NEXT FROM failovered_oibs_cursor into @id, @object_id, @backup_id, @creation_time, @state
END

CLOSE failovered_oibs_cursor
DEALLOCATE failovered_oibs_cursor	
--


IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 297; END	
END		
GO
--
-----------------------------------------------------

-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 297)
BEGIN

    alter table [dbo].[Backup.Model.BackupJobSessions] add cur_point_id uniqueidentifier DEFAULT null
    print 'New column {cur_point_id} has been successfully added to [dbo].[Backup.Model.BackupJobSessions] table'

    alter table [dbo].[Backup.Model.JobSessions] add orig_session_id uniqueidentifier DEFAULT null
    print 'New column {orig_session_id} has been successfully added to [dbo].[Backup.Model.JobSessions] table'
    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 298; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 298)
BEGIN

	delete [dbo].[LicensedHosts]

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 299; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 299)
BEGIN

	declare @id uniqueidentifier
	declare @job_options xml

	declare jobsoptions_cursor cursor for
	select 
		id,
		options
	from [dbo].[BJobs]

	open jobsoptions_cursor 

	fetch next from jobsoptions_cursor into @id, @job_options
	while @@FETCH_STATUS = 0
	begin
		declare @alg xml
		set @alg = '<Algorithm>Syntethic</Algorithm>'		
		exec @job_options = [dbo].[f_insert_as_first] @job_options, @alg
		
		if @job_options.exist('BackupJobOptions/VMToolsQuiesce') = 0
		begin
			declare @vmtoolsquiesce xml
			set @vmtoolsquiesce = '<VMToolsQuiesce>true</VMToolsQuiesce>'
			exec @job_options = [dbo].[f_insert_as_first] @job_options, @vmtoolsquiesce
		end	

		if @job_options.exist('BackupJobOptions/EmailNotification') = 0
		begin
			declare @emailnotification xml
			set @emailnotification = '<EmailNotification>true</EmailNotification>'
			exec @job_options = [dbo].[f_insert_as_first] @job_options, @emailnotification
		end	
		
		update 
			[dbo].[BJobs]
		set
			options = @job_options
		where id = @id
		
		fetch next from jobsoptions_cursor into @id, @job_options
	end

	close jobsoptions_cursor

	deallocate jobsoptions_cursor
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 300; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 300)
BEGIN

	update [dbo].[ReplicationInfo] set base_id = newid()

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 301; END	
END
GO
--
-----------------------------------------------------

-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 301)
BEGIN

    alter table [dbo].[Backup.TrackedActions.Leases] add session_id uniqueidentifier DEFAULT null
    print 'New column {session_id} has been successfully added to [dbo].[Backup.TrackedActions.Leases] table'
    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 302; END	
END
GO
--
-----------------------------------------------------


/*             END OF DATA UPGRADE 40-50				*/
/********************************************************/





-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 302)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VeeamProductVersion]') AND type in (N'U'))
    BEGIN
			CREATE TABLE [dbo].[VeeamProductVersion](
                  [VeeamProductID] NVARCHAR(38) NOT NULL,
                  [VeeamProductVersion] NVARCHAR(16) NOT NULL
            )
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 303; END	
END
GO
--
-----------------------------------------------------



----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 303)
BEGIN

	DECLARE @ProductUID NVARCHAR(38);
	DECLARE @ProductVersion NVARCHAR(16);

	SET @ProductUID = 'B1E61D9B-8D78-4419-8F63-D21279F71A56'
	/*AUTOGENERATED*/SET @ProductVersion = '7.0.0.690'/*AUTOGENERATED*/

	UPDATE dbo.VeeamProductVersion
	SET VeeamProductVersion = @ProductVersion
	WHERE [VeeamProductID] = @ProductUID

	IF @@ROWCOUNT = 0
	INSERT INTO dbo.VeeamProductVersion (VeeamProductID, VeeamProductVersion)
	VALUES (@ProductUID, @ProductVersion)

END
GO
--
-----------------------------------------------------



-----------------------------------------------------
--dummy section for execute stored procedures
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 303 AND current_version < 306)
	UPDATE [dbo].[Version] SET current_version = 306;
GO
--
-----------------------------------------------------








--5.0.2
-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 306)
BEGIN

	exec sp_executesql @st = N'
	if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.Points]'') and [name] = ''num2'')
	begin

		alter table [dbo].[Backup.Model.Points]
		add [num2] numeric(16, 10) not null default(0)

	end
	'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 307; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 307)
BEGIN
	
	exec sp_executesql @st = N'
	update 
		[dbo].[Backup.Model.Points]
	set 
		[num2] = [num]
	'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 308; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 308)
BEGIN

	if exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.Points]') and [name] = 'num')
	begin
		declare @defconstraint_name nvarchar(max)
		select @defconstraint_name = object_name(cdefault) from syscolumns
		where [id] = object_id('[dbo].[Backup.Model.Points]')
		and [name] = 'num'

		if @defconstraint_name is not null
		exec ('alter table [dbo].[Backup.Model.Points] drop constraint [' + @defconstraint_name + ']')
		
		alter table [dbo].[Backup.Model.Points] drop column [num]
		
		exec sp_rename '[dbo].[Backup.Model.Points].[num2]', 'num', 'COLUMN'
	end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 309; END	
END
GO
--
-----------------------------------------------------








--350 - Starting version number for 6.0
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 309)
BEGIN
	UPDATE [dbo].[Version] SET current_version = 350;
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 350)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 351; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 351)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.JobSessions]') and [name] = 'run_manually')
begin
    alter table [dbo].[Backup.Model.JobSessions] add run_manually bit not null default(1)
    print 'New column {run_manually} has been successfully added to [dbo].[Backup.Model.JobSessions] table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 352; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 352)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 353; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 353)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 354; END	
END
GO
--
-----------------------------------------------------




-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 354)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 355; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 355)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'options')
begin
    alter table [dbo].[Hosts] add options xml null
    print 'New column {options} has been successfully added to [dbo].[Hosts] table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 356; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 356)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.Backups]') and [name] = 'target_type')
begin
	ALTER TABLE [dbo].[Backup.Model.Backups] ADD [target_type] int not null default 0
	print 'New column [target_type] has been successfully added to [Backup.Model.Backups] table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 357; END	
END
GO
--
-----------------------------------------------------

-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 357)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'source_proxy_host_id')
begin
	ALTER TABLE [dbo].[BJobs] ADD [source_proxy_host_id] uniqueidentifier not null default '6745a759-2205-4cd2-b172-8ec8f7e60ef8'
	print 'New column [source_proxy_host_id] has been successfully added to [BJobs] table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BJobs]') and [name] = 'target_proxy_host_id')
begin
	ALTER TABLE [dbo].[BJobs] ADD [target_proxy_host_id] uniqueidentifier not null default '6745a759-2205-4cd2-b172-8ec8f7e60ef8'
	print 'New column [target_proxy_host_id] has been successfully added to [BJobs] table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 358; END	
END
GO
--
--------------------------------------
--Creation components and roles for Local Server
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 358)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 359; END
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 359)
BEGIN

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 360; END	
END
GO
--
--------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 360)
BEGIN

IF not exists (select * from sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.FileRestore]') AND type in (N'U'))
begin
CREATE TABLE [dbo].[Backup.TrackedActions.FileRestore](
	[id] [uniqueidentifier] NOT NULL,
	[lease_id] [uniqueidentifier] NOT NULL,
	[action_state] [int] NOT NULL,
	[restore_point_id] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_Backup.TrackedActions.FileRestore] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

  print 'Table [dbo].[Backup.TrackedActions.FileRestore] has been successfully added'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 361; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 361)
BEGIN

    alter table [dbo].[Backup.Model.JobSessions] add aux_data xml DEFAULT null
    print 'New column {aux_data} has been successfully added to [dbo].[Backup.Model.JobSessions] table'
    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 362; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 362)
BEGIN

	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') AND [name] = ''platform'')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.RestoreJobSessions] ADD platform int NOT NULL DEFAULT(0)
	END'	
		    
    print 'New column {platform} has been successfully added to [dbo].[Backup.Model.RestoreJobSessions] table'
    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 363; END	
END
GO
--
-----------------------------------------------------



-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 363)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.BackupTaskSessions]'') and [name] = ''log_xml'')
	begin
		alter table [dbo].[Backup.Model.BackupTaskSessions] add [log_xml] [xml] not null default (''<Root TotalUsn="0" TotalId="0"></Root>'')
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 364; END	
END		
GO

--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 364)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.JobProxies]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.JobProxies](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_JobProxies_id]  DEFAULT (newid()),
			[job_id] [uniqueidentifier] NOT NULL,
			[proxy_id] [uniqueidentifier] NOT NULL,
			[type] [int] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
		 CONSTRAINT [PK_JobProxies] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 365; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 365)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HostDisks]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.HostDisks](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_HostDisks_id]  DEFAULT (newid()),
			[host_id] [uniqueidentifier] NOT NULL,
			[name] [nvarchar] (1000) NOT NULL,
			[inquiry] [nvarchar] (1000) NOT NULL,
			[add_type] [int] NOT NULL,
			[lun] [int] NOT NULL,
			[path_id] [int] NOT NULL,
			[target_id] [int] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
		 CONSTRAINT [PK_HostDisks] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 366; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 366)
BEGIN

	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[Backup.Model.Backups]'') AND [name] = ''dir_path'')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Backups] ADD dir_path nvarchar(max) NOT NULL DEFAULT('''')
	END'	

    print 'New column {dir_path} has been successfully added to [dbo].[Backup.Model.Backups] table'

	exec sp_executesql @stat = N'IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N''[dbo].[Backup.Model.Backups]'') AND [name] = ''meta_file_name'')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Backups] ADD meta_file_name nvarchar(max) NOT NULL DEFAULT('''')
	END'	
		    
    print 'New column {meta_file_name} has been successfully added to [dbo].[Backup.Model.Backups] table'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 367; END	
END		
GO
--
-----------------------------------------------------



-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 367)
BEGIN

	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[BObjects]') AND [name] = 'uuid')
	BEGIN
		ALTER TABLE [dbo].[BObjects] ADD uuid nvarchar(256) NULL
	END	
    print 'New column {uuid} has been successfully added to [dbo].[BObjects] table'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 368; END	
END
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 368)
BEGIN

	--- Create table PhysicalHosts
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PhysicalHosts]') AND type in (N'U'))
	BEGIN
	CREATE TABLE [dbo].[PhysicalHosts]
	(
		[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_PhysicalHosts_id]  DEFAULT (newid()),
		[name] [nvarchar](max) NOT NULL,
		[bios_uuid] [nvarchar](255) NOT NULL,
		[chassis_type] int NOT NULL,
		[usn] [bigint] NOT NULL DEFAULT 0
		
		CONSTRAINT [PK_PhysicalHosts] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)
		WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		
	) ON [PRIMARY]
	END

	--- Create table HostComponents
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HostComponents]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[HostComponents] 
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_HostComponents_id]  DEFAULT (newid()),
			[physical_host_id] uniqueidentifier NOT NULL,
			[type] int NOT NULL,
			[version] [nvarchar](255) NOT NULL,
			[options] xml NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
			CONSTRAINT [PK_HostComponents] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		
		) ON [PRIMARY]
	END
	
	--- Add link in Hosts to PhysicalHosts
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'physical_host_id')
	BEGIN
		ALTER TABLE [dbo].[Hosts] ADD [physical_host_id] uniqueidentifier NULL
	END
	
		DECLARE @local_physical_host_id uniqueidentifier
	SET @local_physical_host_id = 'D7C4FF97-B99B-4d1f-884D-283B7B6B9EE3'

	-- Add Local Physical Host
	declare @usn bigint
	
	IF NOT EXISTS (SELECT * FROM [dbo].[PhysicalHosts] WHERE [id] = @local_physical_host_id)
	BEGIN
		exec [dbo].[IncrementUsn] @usn OUTPUT
		
		INSERT INTO [dbo].[PhysicalHosts]
			(
				[id],
				[name],
				[bios_uuid],
				[chassis_type],
				[usn]
			)
		VALUES
			(
				@local_physical_host_id,
				'This server',
				'',
				0,
				@usn
			)
	END

	-- Update Local Host with PhysicalHostId
	BEGIN
		exec sp_executesql @statement = N'
		declare @usn bigint
		exec [dbo].[IncrementUsn] @usn OUTPUT
		
		update [dbo].[Hosts] 
		set 
			[physical_host_id] = ''D7C4FF97-B99B-4d1f-884D-283B7B6B9EE3'',
			[usn] = @usn
		where [id] = ''6745a759-2205-4cd2-b172-8ec8f7e60ef8'''
	END
	
		-- Add Deployer Service Component	
	IF NOT EXISTS (SELECT * FROM [dbo].[HostComponents] WHERE ([physical_host_id] = @local_physical_host_id) AND [type] = 3)
	BEGIN
		exec [dbo].[IncrementUsn] @usn OUTPUT
	
		DECLARE @deployerSvcVer nvarchar(255)
		/*AUTOGENERATED*/SET @deployerSvcVer = '7.0.0.690'/*AUTOGENERATED*/
		
		INSERT INTO [dbo].[HostComponents]
			(
				[id],
				[physical_host_id],
				[type],
				[version],
				[options],
				[usn]
			)
		VALUES
			(
				newid(),
				@local_physical_host_id,
				3,
				@deployerSvcVer,
				'<DeployerSvcClientOptions/>',
				@usn
			)
	END

	-- Add Local Transport Component	
	IF NOT EXISTS (SELECT * FROM [dbo].[HostComponents] WHERE ([physical_host_id] = @local_physical_host_id) AND [type] = 0)
	BEGIN
		exec [dbo].[IncrementUsn] @usn OUTPUT
		
		DECLARE @transpVer nvarchar(255)
		/*AUTOGENERATED*/SET @transpVer = '7.0.0.690'/*AUTOGENERATED*/
	
		INSERT INTO [dbo].[HostComponents]
			(
				[id],
				[physical_host_id],
				[type],
				[version],
				[options],
				[usn]
			)
		VALUES
			(
				newid(),
				@local_physical_host_id,
				0,
				@transpVer,
				'<TransportClientOptions/>',
				@usn
			)
	END
	
	-- Add Local Nfs Component	
	IF NOT EXISTS (SELECT * FROM [dbo].[HostComponents] WHERE ([physical_host_id] = @local_physical_host_id) AND [type] = 1)
	BEGIN
		exec [dbo].[IncrementUsn] @usn OUTPUT
		
		DECLARE @nfsVer nvarchar(255)
		/*AUTOGENERATED*/SET @nfsVer = '7.0.0.690'/*AUTOGENERATED*/
	
		INSERT INTO [dbo].[HostComponents]
			(
				[id],
				[physical_host_id],
				[type],
				[version],
				[options],
				[usn]
			)
		VALUES
			(
				newid(),
				@local_physical_host_id,
				1,
				@nfsVer,
				'<NfsClientOptions/>',
				@usn
			)
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 369; END	
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 369)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BackupRepositories]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[BackupRepositories] 
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BackupRepositories_id]  DEFAULT (newid()),
			[name] [nvarchar](max) NOT NULL,
			[description] [nvarchar](max) NOT NULL,
			[type] int NOT NULL,
			[host_id] uniqueidentifier NULL,
			[mount_host_id] uniqueidentifier NULL,
			[path] [nvarchar](max) NOT NULL,
			[options] xml NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
			CONSTRAINT [PK_BackupRepositories] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		
		) ON [PRIMARY]
	END

	DECLARE @local_repository_id uniqueidentifier
	SET @local_repository_id = '88788F9E-D8F5-4eb4-BC4F-9B3F5403BCEC'

	declare @usn bigint
	exec [dbo].[IncrementUsn] @usn OUTPUT
	
	IF NOT EXISTS (SELECT * FROM [dbo].[BackupRepositories] WHERE [id] = @local_repository_id)
	BEGIN
		INSERT INTO [dbo].[BackupRepositories]
			(
				[id],
				[name],
				[description],
				[type],
				[host_id],
				[mount_host_id],
				[path],
				[options],
				[usn]
			)
		VALUES
			(
				@local_repository_id,
				'Default Backup Repository',
				'Created by Veeam Backup',
				0,
				'6745a759-2205-4cd2-b172-8ec8f7e60ef8',
				'6745a759-2205-4cd2-b172-8ec8f7e60ef8',
				'c:\backup',
				'<BackupRepositoryOptions></BackupRepositoryOptions>',
				@usn
			)
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 370; END	
END		
GO
--
-----------------------------------------------------

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 370)
BEGIN

	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[BJobs]') AND [name] = 'repository_id')
	BEGIN
		ALTER TABLE [dbo].[BJobs] ADD repository_id uniqueidentifier NULL
	END	
    print 'New column {repository_id} has been successfully added to [dbo].[BJobs] table'
    
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[BJobs]') AND [name] = 'initialsync_repository_id')
	BEGIN
		ALTER TABLE [dbo].[BJobs] ADD initialsync_repository_id uniqueidentifier NULL
	END	
    print 'New column {initialsync_repository_id} has been successfully added to [dbo].[BJobs] table'
    
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.Backups]') AND [name] = 'repository_id')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.Backups] ADD repository_id uniqueidentifier NULL
	END	
    print 'New column {repository_id} has been successfully added to [dbo].[Backup.Model.Backups] table'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 371; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 371)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Credentials]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Credentials] 
	(
		[id] uniqueidentifier primary key NOT NULL DEFAULT (newid()),
		[user_name] nvarchar(max) NOT NULL,
		[password] nvarchar(max) NOT NULL,
		[usn] bigint NOT NULL DEFAULT 0
	)
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 372; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 372)
BEGIN

	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'credentials_id')
	BEGIN
		ALTER TABLE [dbo].[Hosts] ADD [credentials_id] uniqueidentifier NULL
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 373; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 373)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.Session.Filters]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.Session.Filters] (
			[id] uniqueidentifier primary key NOT NULL DEFAULT (newid()),
			[name] [nvarchar](max) NOT NULL,
			[data] xml NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0)
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 374; END	
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 374)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') AND [name] = 'vm_filter')
	BEGIN
		ALTER TABLE dbo.ObjectsInJobs ADD vm_filter xml DEFAULT '' not null
		print 'New column {vm_filter} has been successfully added to dbo.ObjectsInJobs table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 375; END	
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 375)
BEGIN
	DELETE FROM [dbo].[Backup.Model.Session.Filters]

	declare @usn bigint

	exec [dbo].[IncrementUsn] @usn OUTPUT
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('83B702D1-2C19-4ec1-BB5E-CB701CD77273',
		   'Backup',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 0)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)

	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('AF04D740-811D-484b-83A3-799511BD0044',
		   'Replication',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 1)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)

	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('BE4D46D0-5345-4741-9B36-7AF216D8DCF3',
		   'SureBackup',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 3)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('BE4D46D0-5345-4741-9B36-7AF216D8DCF2',
		   'Restore',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] &gt; 3 AND [job_type] != 8 AND [job_type] &lt; 18)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('225D4C03-0B09-44ce-BB24-7CF8AC34DD6E',
		   'Copy',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 8 OR [job_type] = 2)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('95600FC2-2E51-4aec-9053-CC784A5CEEEB',
		   'System',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] &gt; 17 AND [job_type] &lt; 21)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 376; END	
END		
GO
--
-----------------------------------------------------

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 376)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BackupProxies]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[BackupProxies] 
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BackupProxies_id]  DEFAULT (newid()),
			[name] [nvarchar](max) NOT NULL,
			[description] [nvarchar](max) NOT NULL,
			[type] int NOT NULL,
			[host_id] uniqueidentifier NULL,
			[options] xml NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
			CONSTRAINT [PK_BackupProxies] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		
		) ON [PRIMARY]
	END

	DECLARE @local_proxy_id uniqueidentifier
	SET @local_proxy_id = '18B661C1-D9DC-4233-90A0-7E7B10DC2D09'

	declare @usn bigint
	exec [dbo].[IncrementUsn] @usn OUTPUT
	
	IF NOT EXISTS (SELECT * FROM [dbo].[BackupProxies] WHERE [id] = @local_proxy_id)
	BEGIN
		INSERT INTO [dbo].[BackupProxies]
			(
				[id],
				[name],
				[description],
				[type],
				[host_id],
				[options],
				[usn]
			)
		VALUES
			(
				@local_proxy_id,
				'VMware Backup Proxy',
				'Created by Veeam Backup & Replication',
				0,
				'6745a759-2205-4cd2-b172-8ec8f7e60ef8',
				'<BackupProxyOptions></BackupProxyOptions>',
				@usn
			)
	END
		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 377; END	
END		
GO


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 377)
BEGIN

ALTER TABLE [dbo].[Hosts] ALTER column reference nvarchar(1024) null

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 378; END	
END		
GO

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 378)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.VmReplica.Mapping]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.VmReplica.Mapping] (
			[id] uniqueidentifier primary key NOT NULL DEFAULT (newid()),
			[job_id] uniqueidentifier NOT NULL,
			[obj_id] uniqueidentifier NOT NULL,
			[mapped_obj_id] uniqueidentifier NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0)
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 379; END	
END		
GO

--
-----------------------------------------------------

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 379)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND [name] = 'read_size')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD read_size bigint DEFAULT 0 not null
		ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD stored_size bigint DEFAULT 0 not null
		print 'New columns {read_size, stored_size} has been successfully added to dbo.Backup.Model.BackupTaskSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 381; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 381)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupJobSessions]') AND [name] = 'read_size')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD read_size bigint DEFAULT 0 not null
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD stored_size bigint DEFAULT 0 not null
		print 'New columns {read_size, stored_size} has been successfully added to dbo.Backup.Model.BackupJobSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 382; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 382)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Disks]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Disks](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Disks_id]  DEFAULT (newid()),
			[name] [nvarchar] (1000) NOT NULL,
			[inquiry] [nvarchar] (1000) NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
		 CONSTRAINT [PK_Disks] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PhysHost_Disk]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[PhysHost_Disk](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_PhysHostDisk_id]  DEFAULT (newid()),
			[physhost_id] [uniqueidentifier] NOT NULL,
			[disk_id] [uniqueidentifier] NOT NULL,
			[port] [int] NOT NULL,
			[path_id] [int] NOT NULL,
			[target_id] [int] NOT NULL,
			[lun] [int] NOT NULL,
			[add_type] [int] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
		 CONSTRAINT [PK_PhysHostDisk] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Volumes]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Volumes](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Volumes_id]  DEFAULT (newid()),
			[uid] [uniqueidentifier] NOT NULL,
			[type] [int] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
		 CONSTRAINT [PK_Volumes] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PhysHost_Volume]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[PhysHost_Volume](
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_PhysHostVolume_id]  DEFAULT (newid()),
			[physhost_id] [uniqueidentifier] NOT NULL,
			[volume_id] [uniqueidentifier] NOT NULL,
			[mount_point] nvarchar (1000) NOT NULL,
			[provider] [xml] NOT NULL,
			[provider_select_type] [int] NOT NULL,
			[add_type] [int] NOT NULL,
			[usn] [bigint] NOT NULL DEFAULT 0
			
		 CONSTRAINT [PK_PhysHostVolume] PRIMARY KEY CLUSTERED 
		(
			[id] ASC
		)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		) ON [PRIMARY]
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 383; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 383)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 394; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 394)
BEGIN

	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[BackupRepositories]') AND [name] = 'share_creds_id')
	BEGIN
		ALTER TABLE [dbo].[BackupRepositories] ADD [share_creds_id] [uniqueidentifier] DEFAULT NULL
		print 'New column {share_creds_id} has been successfully added to BackupRepositories table'
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 395; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 395)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 396; END	
END		
GO

--
-----------------------------------------------------

--
---------------------------------------------------------------------------


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 396)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.QuickMigrationTaskSessions]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.QuickMigrationTaskSessions](
			[id] [uniqueidentifier] NOT NULL,
			[session_id] [uniqueidentifier] NOT NULL,
			[creation_time] [datetime] NOT NULL,
			[object_name] [nvarchar](2000) NULL,
			[status] [int] NOT NULL,
			[reason] [ntext] NULL,
			[object_id] [uniqueidentifier] NULL,
			[end_time] [datetime] NOT NULL DEFAULT ('01.01.1900'),
			[operation] [nvarchar](400) NOT NULL  DEFAULT (''),
			[total_objects] [int] NOT NULL DEFAULT 0,
			[processed_objects] [int] NOT NULL  DEFAULT 0,
			[total_size] [bigint] NOT NULL DEFAULT 0,
			[processed_size] [bigint] NOT NULL DEFAULT 0,
			[usn] [bigint] NOT NULL DEFAULT 0,
			[avg_speed] [bigint] NOT NULL DEFAULT 0,
			[log_xml] [xml] NOT NULL DEFAULT '<Root TotalUsn="0" TotalId="0"></Root>'
			)
			
		exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.QuickMigrationTaskSessions]''))
		begin
			exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.QuickMigrationTaskSessions'', 0, 0
		end	
		'
	END
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 397; END	
END		
GO

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 397)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Backup.Model.QuickMigrationSessions]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.QuickMigrationSessions](
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[total_objects] [int] NOT NULL  DEFAULT 0,
			[processed_objects] [int] NOT NULL DEFAULT 0,
			[total_size] [bigint] NOT NULL DEFAULT 0,
			[processed_size] [bigint] NOT NULL DEFAULT 0,
			[usn] [bigint] NOT NULL DEFAULT 0,
			[avg_speed] [bigint] NOT NULL DEFAULT 0	)
	END


	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.QuickMigrationSessions]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.QuickMigrationSessions'', 0, 0 
	end	
	'
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 398; END	
END		
GO

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 398)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 399; END	
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 399)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[PhysHost_Volume]') AND [name] = 'scsi_bus')
	BEGIN
		ALTER TABLE [dbo].[PhysHost_Volume] ADD scsi_bus bigint DEFAULT 0 not null
		ALTER TABLE [dbo].[PhysHost_Volume] ADD scsi_logical_unit bigint DEFAULT 0 not null
		ALTER TABLE [dbo].[PhysHost_Volume] ADD scsi_port bigint DEFAULT 0 not null
		ALTER TABLE [dbo].[PhysHost_Volume] ADD scsi_target_id bigint DEFAULT 0 not null
		print 'New columns {scsi_bus scsi_logical_unit scsi_port scsi_target_id} has been successfully added to dbo.Backup.Model.BackupJobSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 400; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 400)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 401; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 401)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 402; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 402)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 403; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 403)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 404; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 404)
BEGIN
	
IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[PhysHost_Disk]') AND [name] = 'vms_count')
BEGIN
    ALTER TABLE [dbo].[PhysHost_Disk] ADD [vms_count] int DEFAULT 0 NOT NULL
    PRINT 'New column {vms_count} has been successfully added to dbo.PhysHost_Disk table'
END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 405; END	
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 405)
BEGIN

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[PhysicalHosts]') AND [name] = 'hardware_info')
BEGIN
    ALTER TABLE [dbo].[PhysicalHosts] ADD [hardware_info] xml DEFAULT '' NOT NULL
    PRINT 'New column {hardware_info} has been successfully added to dbo.PhysicalHosts table'
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 407; END	
END		
GO

-----------------------------------------------------
--267
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 407)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.Model.RestoreJobSessions]'') and [name] = ''multi_restore_id'')
	begin
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [multi_restore_id] [uniqueidentifier] not null DEFAULT (newid())
		alter table [dbo].[Backup.Model.RestoreJobSessions] add [restore_type] [int] not null default 0
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 408; END	
END		
GO


--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 408)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 409; END	
END		
GO

-------------------------------------------------------


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 409)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[JobCredentials]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[JobCredentials](
			[id] [uniqueidentifier] NOT NULL,
			[job_id] [uniqueidentifier] NOT NULL,
			[object_id] [uniqueidentifier] NOT NULL,
			[credentials_id] [uniqueidentifier] NOT NULL,
			[usn] [bigint] NOT NULL,
			CONSTRAINT [PK_JobCredentials] PRIMARY KEY CLUSTERED ( [id] ASC)
			WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]


		ALTER TABLE [dbo].[JobCredentials] ADD  CONSTRAINT [DF_JobCredentials_id]  DEFAULT (newid()) FOR [id]
		ALTER TABLE [dbo].[JobCredentials] ADD  CONSTRAINT [DF_JobCredentials_usn]  DEFAULT ((0)) FOR [usn]
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 410; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 410)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ProxyAgents]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[ProxyAgents] (
			[session_id]  [uniqueidentifier] NOT NULL,
			[agent_id] [uniqueidentifier] NOT NULL,
			[host_name] nvarchar(255) NOT NULL
			)
	END			
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 411; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 411)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HvVolumeSnapshots]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[HvVolumeSnapshots] (
			[session_id]  [uniqueidentifier] NOT NULL,
			[snapshot_id] [uniqueidentifier] NOT NULL,
			[host_name] nvarchar(255) NOT NULL
			)
	END		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 412; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 412)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.OIBsFailoverInfo]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.OIBsFailoverInfo]
		(
			[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
			[oib_id] [uniqueidentifier] NOT NULL,
			[failback_object_id] [uniqueidentifier] NOT NULL,
			[failback_aux_data] [xml] NOT NULL
		)			  		
	END
	    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 413; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 413)
BEGIN
	IF NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.OIBsFailoverInfo]') and [name] = 'usn')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.OIBsFailoverInfo] add usn bigint not null default 0
		PRINT 'New column {usn} has been successfully added to dbo.Backup.Model.OIBsFailoverInfo'
    
		
	END
	    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 414; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 414)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 415; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 415)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[HostComponents]') and [name] = 'is_up_to_date')
begin
    alter table [dbo].[HostComponents] add is_up_to_date bit default 1 not null
    print 'New column {is_up_to_date} has been successfully added to dbo.HostComponents table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 416; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 416)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInJobs]') and [name] = 'order_no')
begin
    alter table dbo.ObjectsInJobs add order_no int default 0 not null
    alter table dbo.ObjectsInJobs add ex_options xml default '<ExOptions/>' not null
    print 'New columns {order_no ex_options} has been successfully added to dbo.ObjectsInJobs table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 417; END
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 417)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupProxies]') and [name] = 'disabled')
begin
    alter table [dbo].[BackupProxies] add disabled bit default 0 not null
    print 'New column {disabled} has been successfully added to dbo.BackupProxies table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 418; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 418)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 419; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 419)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 420; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 420)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 421; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 421)
BEGIN
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[PhysHost_Disk]') and [name] = 'datastore_name')
begin
    alter table [dbo].[PhysHost_Disk] add datastore_name nvarchar(max) default '' not null
    print 'New column {datastore_name} has been successfully added to dbo.PhysHost_Disk table'
end
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 422; END
END		
GO

--
-----------------------------------------------------


-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 422)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 423; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 423)
BEGIN

	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VmWareSnapshots]') AND type in (N'U'))
	BEGIN
		DROP TABLE [dbo].[VmWareSnapshots]
		print 'Old table {VmWareSnapshots} has been deleted.'
	END		
	
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VmWareSnapshots]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[VmWareSnapshots] (
			[session_id]  [uniqueidentifier] NOT NULL,
			[host_name]  [nvarchar](1024) NOT NULL,		
			[snapshot_ref]  [nvarchar](1024) NOT NULL,
			[vm_ref] [nvarchar](1024) NOT NULL,
			[snapshot_name] [nvarchar](1024) NOT NULL,
			[description] [nvarchar](1024) NOT NULL		
			)
		print 'New table {VmWareSnapshots} has been created.'
	END		
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 424; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 424)
BEGIN

	UPDATE [dbo].[Hosts] SET
           [name] = 'This server'
	WHERE  [id] = '6745a759-2205-4cd2-b172-8ec8f7e60ef8'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 425; END	
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 425)
BEGIN
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.RestoreJobSessions]') and [name] = 'oib_id')
begin
    alter table [dbo].[Backup.Model.RestoreJobSessions] add oib_id uniqueidentifier default '00000000-0000-0000-0000-000000000000' not null
    print 'New column {oib_id} has been successfully added to dbo.Backup.Model.RestoreJobSessions table'
end
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 426; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 426)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 427; END
END		
GO

--
-----------------------------------------------------



-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 427)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 428; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 428)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 429; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 429)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 430; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 430)
BEGIN
if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ObjectsInApplicationGroups]') and [name] = 'backup_id')
begin
    alter table [dbo].[ObjectsInApplicationGroups] add backup_id uniqueidentifier default '00000000-0000-0000-0000-000000000000' not null
    print 'New column {backup_id} has been successfully added to dbo.ObjectsInApplicationGroups table'
end
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 431; END
END		
GO
--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 431)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupJobSessions]') AND [name] = 'bottleneck')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD bottleneck int DEFAULT 0 not null
		print 'New column {bottleneck} has been successfully added to dbo.Backup.Model.BackupJobSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 432; END	
END		
GO
--
-----------------------------------------------------

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 432)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupJobSessions]') AND [name] = 'source_storage')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD source_storage int DEFAULT 0 not null
		print 'New column {source_storage} has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD source_proxy int DEFAULT 0 not null
		print 'New column source_proxy has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD source_network int DEFAULT 0 not null
		print 'New column source_network has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD target_storage int DEFAULT 0 not null
		print 'New column target_storage has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD target_proxy int DEFAULT 0 not null
		print 'New column target_proxy has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD target_network int DEFAULT 0 not null
		print 'New column target_network has been successfully added to dbo.Backup.Model.BackupJobSessions table'
		
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 433; END	
END		
GO


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 433)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupJobSessions]') AND [name] = 'processed_used_size')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD processed_used_size bigint DEFAULT 0 not null
		print 'New column {processed_used_size} has been successfully added to dbo.Backup.Model.BackupJobSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 434; END	
END		
GO

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 434)
BEGIN
	
		UPDATE [dbo].[Backup.Model.BackupJobSessions] 
		SET processed_used_size = processed_size
		WHERE processed_used_size = 0
		print 'Colume values {processed_used_size} were copied from the {processed_size} column.'

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 435; END	
END		
GO

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 435)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND [name] = 'processed_used_size')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD processed_used_size bigint DEFAULT 0 not null
		print 'New column {source_storage} has been successfully added to dbo.Backup.Model.BackupTaskSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 436; END	
END		
GO

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 436)
BEGIN
	
		UPDATE [dbo].[Backup.Model.BackupTaskSessions] 
		SET processed_used_size = processed_size
		WHERE processed_used_size = 0
		print 'Column values {processed_used_size} were copied from the {processed_size} column.'

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 437; END	
END		
GO

-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 437)
BEGIN
	
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Disks]') and [name] = 'controllerInquiry')
	begin
		alter table [dbo].[Disks] add diskInquiry nvarchar (1000) default '' NOT NULL;
		print 'New column [diskInquiry] has been successfully added to [dbo].[Disks] table'
	    
		exec sp_rename '[dbo].[Disks].[inquiry]', 'controllerInquiry', 'COLUMN'
		print 'Column [dbo].[Disks].[inquiry] has been successfully renamed to [dbo].[Disks].[controllerInquiry].'
	    
	end

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 438; END	
END		
GO

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 438)
BEGIN
	
	DECLARE @pk_name nvarchar(max)

	SELECT
		@pk_name = [name]
	FROM
		sys.indexes
	WHERE
		object_id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND
		type = 1

	IF (@pk_name IS NOT NULL)
	BEGIN
		IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND name = @pk_name)
		BEGIN
			EXEC('ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] DROP CONSTRAINT [' + @pk_name + ']')
		END
	END

	ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD CONSTRAINT PK_Backup_Model_BackupTaskSessions PRIMARY KEY (id)

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 439; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 439 AND current_version < 445)
BEGIN
	declare @usn bigint
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	
	UPDATE [dbo].[Backup.Model.Session.Filters] 
	SET [data] = '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] &gt; 17 AND [job_type] &lt; 22)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>',
		[usn] = @usn
	WHERE [id] = '95600FC2-2E51-4aec-9053-CC784A5CEEEB' --System

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 445; END
END		
GO


--
-----------------------------------------------------
--
-- BEGIN UPGRADE FROM 5.X TO 6.0
--
-- Condition: 445
--
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 445)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 446; END
END
GO

--
-----------------------------------------------------
--
-- END UPGRADE
--
-----------------------------------------------------
--


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 446)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND [name] = 'queued_time')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD [queued_time] datetime not null default getdate()
		print 'New column {queued_time} has been successfully added to dbo.Backup.Model.BackupTaskSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 447; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 447)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[PhysHost_Disk]') and [name] = 'is_auto_detected')
begin
    alter table [dbo].[PhysHost_Disk] add [is_auto_detected] bit default 1 not null
    print 'New column {is_auto_detected} has been successfully added to dbo.PhysHost_Disk table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[PhysHost_Disk]') and [name] = 'is_manual_added')
begin
    alter table [dbo].[PhysHost_Disk] add [is_manual_added] bit default 0 not null
    print 'New column {is_manual_added} has been successfully added to dbo.PhysHost_Disk table'
end


	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 448; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 448 AND current_version < 451)
BEGIN

	alter table [dbo].[Backup.TrackedActions.FileRestore] add [restore_session_id] uniqueidentifier default null

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 451; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

--IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 449)
--BEGIN
--IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 450; END
--END		
GO

--
-----------------------------------------------------


-----------------------------------------------------
--


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 451)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmWareSnapshots]') and [name] = 'viproxy_id')
begin
    alter table [dbo].[VmWareSnapshots] add viproxy_id uniqueidentifier not null default '{00000000-0000-0000-0000-000000000000}'
    print 'New column {viproxy_id} has been successfully added to dbo.VmWareSnapshots table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmWareSnapshots]') and [name] = 'proxymode')
begin
    alter table [dbo].[VmWareSnapshots] add proxymode nvarchar(1024) not null default 'nbd'
    print 'New column {proxymode} has been successfully added to dbo.VmWareSnapshots table'
end

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 452; END
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 452)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 453; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 453)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 454; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 454)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 455; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 455)
BEGIN

IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Disks]') AND [name] = 'diskId')
BEGIN
	ALTER TABLE [dbo].[Disks] ADD [diskId] nvarchar(255) not null default ''
	print 'New column {diskId} has been successfully added to dbo.Disks table'
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 456; END
END		

GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 456)
BEGIN

DECLARE @mailOptionsId uniqueidentifier
DECLARE @xml xml
SET @mailOptionsId = '91bb166b-e197-48f7-a430-7904e013b30b'

SET @xml = (SELECT [value] from [dbo].[Options] WHERE [id] = @mailOptionsId)

DECLARE @str nvarchar(max)
SET @str = CAST (@xml as nvarchar(max))

SET @str = replace(@str, '<EncryptedPassword>', '<Password>')
SET @str = replace(@str, '</EncryptedPassword>', '</Password>')

UPDATE [dbo].[Options] SET
	[value] = @str
WHERE [id] = @mailOptionsId


IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 457; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 457)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 458; END
END		
GO

--
-----------------------------------------------------

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 458)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 459; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 459)
BEGIN
	DELETE FROM [dbo].[Backup.Model.Session.Filters]

	declare @usn bigint

	exec [dbo].[IncrementUsn] @usn OUTPUT
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('83B702D1-2C19-4ec1-BB5E-CB701CD77273',
		   'Backup',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 0)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)

	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('AF04D740-811D-484b-83A3-799511BD0044',
		   'Replication',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 1)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('4508C3E9-6791-4ecf-B502-FF0FDA01B1D5',
		   'Migration',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 8)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)

	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('BE4D46D0-5345-4741-9B36-7AF216D8DCF3',
		   'SureBackup',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 3)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	  
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('225D4C03-0B09-44ce-BB24-7CF8AC34DD6E',
		   'Copy',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 2)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('95600FC2-2E51-4aec-9053-CC784A5CEEEB',
		   'System',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] &gt; 17 AND [job_type] &lt; 21)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('12612F1A-6FD2-47db-8962-FEE0E54BD381',
		   'Full VM restore',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 4)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('A34648B0-1845-462b-9DC4-E42EABE5290D',
		   'VM disk restore',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 13)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('34F621F2-E03E-468b-8183-2A3344BC20F5',
		   'VM file restore',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 5)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('6BF6EFDE-B654-43ec-BA84-094AD79A46D0',
		   'Guest file restore',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 6 OR [job_type] = 10 OR [job_type] = 11)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
		   
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('F2323D84-AA8D-4cad-B9BB-D72F022746EF',
		   'Replica',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 7 OR [job_type] = 9 OR [job_type] &gt; 13 AND [job_type] &lt; 18)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	exec [dbo].[IncrementUsn] @usn OUTPUT	
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('2E80AFDD-9B0E-467c-9032-D6C5303FF05A',
		   'Instant VM recovery',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 12)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 460; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 460)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupProxies]') and [name] = 'is_busy')
begin
    alter table [dbo].[BackupProxies] add [is_busy] bit not null default 0
    print 'New column {is_busy} has been successfully added to dbo.BackupProxies table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupProxies]') and [name] = 'is_unavailable')
begin
    alter table [dbo].[BackupProxies] add [is_unavailable] bit not null default 0
    print 'New column {is_unavailable} has been successfully added to dbo.BackupProxies table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupRepositories]') and [name] = 'is_busy')
begin
    alter table [dbo].[BackupRepositories] add [is_busy] bit not null default 0
    print 'New column {is_busy} has been successfully added to dbo.BackupRepositories table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupRepositories]') and [name] = 'is_unavailable')
begin
    alter table [dbo].[BackupRepositories] add [is_unavailable] bit not null default 0
    print 'New column {is_unavailable} has been successfully added to dbo.BackupRepositories table'
end

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupRepositories]') and [name] = 'is_full')
begin
    alter table [dbo].[BackupRepositories] add [is_full] bit not null default 0
    print 'New column {is_full} has been successfully added to dbo.BackupRepositories table'
end
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 461; END
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 461)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'is_unavailable')
begin
    alter table [dbo].[Hosts] add [is_unavailable] bit not null default 0
    print 'New column {is_unavailable} has been successfully added to dbo.Hosts table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 462; END
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 462)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.MruUsers]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.Model.MruUsers](
		[id] [uniqueidentifier] NOT NULL DEFAULT(NEWID()),
		[name] [nvarchar](256) NOT NULL,
	CONSTRAINT [PK_Backup_Model_MruUsers] PRIMARY KEY CLUSTERED 
	(
		[id] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.MruList]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.Model.MruList](
		[id] [uniqueidentifier] NOT NULL DEFAULT(NEWID()),
		[url] [nvarchar](MAX) NOT NULL,
		[credential_id] [uniqueidentifier] NOT NULL,
		[user_id] [uniqueidentifier] NOT NULL,
		[changed_time] [datetime] NOT NULL,
	CONSTRAINT [PK_Backup_Model_MruList] PRIMARY KEY CLUSTERED 
	(
		[id] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 463; END
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 463)
BEGIN

if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[PhysicalHosts]') and [name] = 'net_info')
begin
    alter table [dbo].[PhysicalHosts] add [net_info] xml not null default ''
    print 'New column {net_info} has been successfully added to dbo.PhysicalHosts table'
end

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 464; END
END		
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 464)
BEGIN

    alter table [dbo].[Backup.Model.JobSessions] add job_spec xml DEFAULT null
    print 'New column {job_spec} has been successfully added to [dbo].[Backup.Model.JobSessions] table'
    
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 465; END	
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
--
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 465)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 466; END	
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
-- InstantRecovery (12) job_type added into check in procedure GetJobRestoreSessionsStarted

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 466)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 467; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 467)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[BackupRepositories]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''BackupRepositories''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 468; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

-----------------------------------------------------
-- Update GetJobRestoreSession procedure. Field [dbo].[Backup.Model.RestoreJobSessions].[action] added into request

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 468)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 469; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 469)
BEGIN	
	---------------------------------------------------
	exec sp_executesql @stat = N'
	IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[BackupProxies]''))
	begin
		exec [dbo].[AddTrackChangeTriggers] N''BackupProxies''
	end
	'
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 470; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 470)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.RestoreJobSessions]') AND [name] = 'state_xml')
	BEGIN

		ALTER TABLE [dbo].[Backup.Model.RestoreJobSessions] ADD state_xml xml DEFAULT '' not null
		print 'New column {state_xml} has been successfully added to dbo.Backup.Model.RestoreJobSessions table'
		
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 471; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 471)
BEGIN	
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmssVms]') and [name] = 'content_restore_percent')
	begin
		alter table dbo.VmssVms add content_restore_percent int DEFAULT 0 NOT null
		print 'New column {content_restore_percent} has been successfully added to [dbo].[VmssVms] table'
	end	
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 472; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 472)
BEGIN	
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmssVms]') and [name] = 'content_restore_state')
	begin
		alter table dbo.VmssVms add content_restore_state int DEFAULT 0 NOT null
		print 'New column {content_restore_state} has been successfully added to dbo.VmssVms table'
	end	
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 473; END	
END
GO
--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 473)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 474; END	
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 474)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 475; END	
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 475)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 476; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 476)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 477; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 477)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions.TemporaryBackups]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.TrackedActions.TemporaryBackups](
		[backup_id] [uniqueidentifier] NOT NULL,
		[session_id] [uniqueidentifier] NOT NULL)
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 478; END
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 478)
BEGIN	
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmssVms]') and [name] = 'irctl_restore_state')
	begin
		alter table dbo.VmssVms add irctl_restore_state int DEFAULT 0 NOT null
		print 'New column {irctl_restore_state} has been successfully added to dbo.VmssVms table'
	end	
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 479; END	
END
GO
--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 479)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 480; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 480)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 481; END	
END
GO

--
-----------------------------------------------------


-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 481)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[Backup.TrackedActions.VmMount]'') and [name] = ''share_creds_id'')
	begin
		alter table [dbo].[Backup.TrackedActions.VmMount] add [share_creds_id] uniqueidentifier null 
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 482; END	
END		
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 482 AND current_version < 489)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 489; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 489)
BEGIN
	exec sp_executesql @stat = N'if not exists (select * from syscolumns where id = OBJECT_ID(N''[dbo].[VmssVms]'') and [name] = ''object_id'')
	begin
		alter table [dbo].[VmssVms] add [object_id] uniqueidentifier not null default ''{00000000-0000-0000-0000-000000000000}''
	end'
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 490; END	
END		
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 490 AND current_version < 504)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 504; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 504)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.JobSessions]') AND name = N'IX_Backup.Model.JobSessions_State')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup.Model.JobSessions_State] ON dbo.[Backup.Model.JobSessions]
		(
			[state] ASC
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END

	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.JobSessions]') AND name = N'IX_Backup.Model.JobSessions_JobId')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup.Model.JobSessions_JobId] ON dbo.[Backup.Model.JobSessions]
		(
			job_id
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 505; END	
END

GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 505 AND current_version < 515)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 514; END	
END
GO

--
-----------------------------------------------------

-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 514)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 515; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 515)
BEGIN

DECLARE host_cursor CURSOR FOR
SELECT
	[id],
	[name],
	[parent_id]
FROM
	[dbo].[Hosts]
WHERE
	([parent_id] IS NULL OR [parent_id] = '00000000-0000-0000-0000-000000000000') AND
	([physical_host_id] IS NOT NULL AND [physical_host_id] <> '00000000-0000-0000-0000-000000000000')

OPEN host_cursor

DECLARE @host_id uniqueidentifier
DECLARE @host_name nvarchar(255)
DECLARE @host_parent_id uniqueidentifier

DECLARE @root_folder_id uniqueidentifier
SET @root_folder_id = '4CEBEB16-A4BB-4B9B-8CBB-67BBB8C59F0E'

FETCH NEXT FROM
	host_cursor
INTO
	@host_id,
	@host_name,
	@host_parent_id

WHILE @@fetch_status = 0
BEGIN                                                             
	IF NOT EXISTS (SELECT TOP 1 * FROM [dbo].[Folder_Host] WHERE [host_id] = @host_id AND [folder_id] = @root_folder_id)
	BEGIN
		PRINT 'Fixing host without parent:'
		PRINT '  Id: ' + cast(@host_id as nvarchar(255))
		PRINT '  Name: ' + @host_name
		PRINT '  Folder Id: ' + cast(@root_folder_id as nvarchar(255))

		INSERT INTO
			[dbo].[Folder_Host]
		VALUES
		(
			newid(),
			@root_folder_id,
			@host_id,
			0
		)
	END

	FETCH NEXT FROM
		host_cursor
	INTO
		@host_id,
		@host_name,
		@host_parent_id
END

CLOSE host_cursor
DEALLOCATE host_cursor

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 516; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 517)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 518; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 518)
BEGIN

DECLARE @xmlDoc xml
DECLARE @text nvarchar(max)
SET @xmlDoc = (SELECT [value]
FROM [dbo].[Options]
WHERE [id] = '91bb166b-e197-48f7-a430-7904e013b30b')

SET @text = cast(@xmlDoc as nvarchar(max))
SET @text = replace(@text, 'Job %JobName% completed: %JobResult%', '[%JobResult%] %JobName% (%VmCount% VMs) %Issues%')
SET @xmlDoc = cast(@text as xml)

UPDATE dbo.Options SET value = @xmlDoc WHERE id = '91bb166b-e197-48f7-a430-7904e013b30b'

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 519; END	
END
GO

--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 519 AND current_version < 523)
BEGIN
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 523; END	
END
GO
--
-----------------------------------------------------
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 523)
BEGIN	
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.OIBs]') and [name] = N'[has_exchange]')
	begin
		alter table [dbo].[Backup.Model.OIBs] add [has_exchange] bit DEFAULT 0 NOT null
		print 'New column {has_exchange} has been successfully added to dbo.Backup.Model.OIBs table'
	end	
	---------------------------------------------------
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 524; END	
END
GO
--
-----------------------------------------------------

--------------------------------------------------------------------------------
--Version 524

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 524)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[PhysicalHosts]') and [name] = 'os_type')
	begin
			alter table [dbo].[PhysicalHosts] add os_type int DEFAULT 0  NOT null
			print 'New column {os_type} has been successfully added to dbo.PhysicalHosts table'					
	end

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 525; END
END		
GO
--------------------------------------------------------------------------------
--Version 525


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 525)
BEGIN
			
	UPDATE [dbo].[PhysicalHosts]
	SET [dbo].[PhysicalHosts].[os_type] = 5
	FROM [dbo].[PhysicalHosts], [dbo].[Hosts]
	WHERE [dbo].[PhysicalHosts].[id] = [dbo].[Hosts].[physical_host_id] AND [dbo].[Hosts].[type] = 7 AND [dbo].[PhysicalHosts].[os_type] = 0		

	print 'Upgraded values of os_type field for Hyper-V 2008 servers'

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 526; END
END		
GO
--------------------------------------------------------------------------------
--Version 526

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 526)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanClusters]') AND type in (N'U'))
BEGIN
		CREATE TABLE [dbo].[Backup.Model.HPSanClusters](
		 [id] [uniqueidentifier] NOT NULL,
		 [name] [nvarchar](255) NOT NULL,
		 [host_id] [uniqueidentifier] NOT NULL,
		 [usn] [bigint] NOT NULL default 0,
		 CONSTRAINT [PK_Backup.HPSanClusters] PRIMARY KEY CLUSTERED 
		(
		 [id] ASC
		)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]
END

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 527; END
END
GO
--------------------------------------------------------------------------------
--Version 527

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 527)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanVolumes]') AND type in (N'U'))
BEGIN
		CREATE TABLE [dbo].[Backup.Model.HPSanVolumes](
		 [id] [uniqueidentifier] NOT NULL,
		 [name] [nvarchar](255) NOT NULL,
		 [cluster_id] [uniqueidentifier] NOT NULL,
		 [iqn] [nvarchar](512) NOT NULL,
		 [usn] [bigint] NOT NULL default 0,
		 CONSTRAINT [PK_Backup.HPSanVolumes] PRIMARY KEY CLUSTERED 
		(
		 [id] ASC
		)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 528; END
END
GO
--------------------------------------------------------------------------------
--Version 528

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 528)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanSnapshots]') AND type in (N'U'))
BEGIN
		CREATE TABLE [dbo].[Backup.Model.HPSanSnapshots](
		 [id] [uniqueidentifier] NOT NULL,
		 [name] [nvarchar](255) NOT NULL,
		 [creation_time] [datetime] NOT NULL,
		 [volume_id] [uniqueidentifier] NOT NULL,
		 [usn] [bigint] NOT NULL default 0,
		 CONSTRAINT [PK_Backup.HPSanSnapshots] PRIMARY KEY CLUSTERED 
		(
		 [id] ASC
		)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 529; END
END
GO
--------------------------------------------------------------------------------
--Version 529

IF EXISTS(SELECT 1 FROM [dbo].[Version] WHERE current_version = 529) 
BEGIN
	IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[BJobs]') and name = 'parent_schedule_id')
	BEGIN
		ALTER TABLE [dbo].[BJobs] ADD [parent_schedule_id] [uniqueidentifier] DEFAULT NULL;
		CREATE NONCLUSTERED INDEX ix_parent_schedule_id ON [dbo].[BJobs] (parent_schedule_id);
		PRINT 'New column [parent_schedule_id] has been successfully added to [BJobs]'
	END
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 530; END
END
GO

---------------------------------------------------------------------------------
--Version 530

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 530)
BEGIN
	IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version < 214)
	BEGIN
		---------------------------------------------------
		exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.HPSanClusters]''))
		begin
			exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.HPSanClusters'', 0, 0, 1
		end
		'
		---------------------------------------------------
		---------------------------------------------------
		exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.HPSanVolumes]''))
		begin
			exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.HPSanVolumes'', 0, 0, 1
		end
		'
		---------------------------------------------------
		---------------------------------------------------
		exec sp_executesql @stat = N'
		IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[dbo].[Backup.Model.HPSanSnapshots]''))
		begin
			exec [dbo].[AddTrackChangeTriggers] N''Backup.Model.HPSanSnapshots'', 0, 0, 1
		end
		'
		---------------------------------------------------
	END
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 531; END	
END
GO

---------------------------------------------------------------------------------
--Version 531

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 531)
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SmbFileShares]') AND type in (N'U'))
	BEGIN
			CREATE TABLE [dbo].[SmbFileShares](
			 [id] [uniqueidentifier] NOT NULL,
			 [server_name] [nvarchar](255) NOT NULL,
			 [folder_name] [nvarchar](255) NOT NULL,
			 [host_id] [uniqueidentifier] NOT NULL,
			 [credentials_id] [uniqueidentifier] NOT NULL,
			 CONSTRAINT [PK_SmbFileShares] PRIMARY KEY CLUSTERED 
			 (
		 		[id] ASC
			 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
			 ) ON [PRIMARY]
	END
		
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 532; END	
END
GO


---------------------------------------------------------------------------------
--Version 531

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 532 AND current_version < 534)
BEGIN

	IF NOT EXISTS(SELECT 1 FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') and name = 'work_details')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupTaskSessions] ADD [work_details] xml DEFAULT NULL;
		PRINT 'New column [work_details] has been successfully added to [Backup.Model.BackupTaskSessions]'
	END

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 534; END	
END
GO


---------------------------------------------------------------------------------
--Version 534
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 534)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[SmbFileShares]') and [name] = 'type')
	begin
			alter table [dbo].[SmbFileShares] add type int DEFAULT 0  NOT null
			print 'New column {type} has been successfully added to dbo.SmbFileShares table'					
	end
	
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 535; END	
END
GO

--------------------------------------------------------------------------------
--Version 535

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 535)
BEGIN


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanVolumeBackups]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.HpSanVolumeBackups]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Model_HpSanVolumeBackups_id]  DEFAULT (newid()),
			[volume_id] [uniqueidentifier] NOT NULL,
			[backup_id] [uniqueidentifier] NOT NULL
			
		    CONSTRAINT [PK_Backup_Model_HpSanVolumeBackups_id] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END
	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 536; END
END
GO

--------------------------------------------------------------------------------
--Version 536

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 536)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanSnapshotStorages]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.Model.HpSanSnapshotStorages]
		(
			[id] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Backup_Model_HpSanSnapshotStorages_id]  DEFAULT (newid()),
			[snapshot_id] [uniqueidentifier] NOT NULL,
			[storage_id] [uniqueidentifier] NOT NULL
			
		    CONSTRAINT [PK_Backup_Model_HpSanSnapshotStorages_id] PRIMARY KEY CLUSTERED 
			(
				[id] ASC
			)
			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
		)
		ON [PRIMARY]
	END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 537; END
END
GO

--------------------------------------------------------------------------------
--Version 537
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 537 AND current_version < 544)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.ResourceUsages]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Backup.Model.ResourceUsages] (
	[task_id] [uniqueidentifier] NOT NULL,
	[resource_id] [uniqueidentifier] NOT NULL,
	[resource_type] [int] NOT NULL)
END

IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 544; END	
END
GO

---------------------------------------------------------------------------------
--Version 544
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 544)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanSnapshots]') and [name] = 'indexed')
	begin
			alter table [dbo].[Backup.Model.HPSanSnapshots] add indexed int DEFAULT 0  NOT null
			print 'New column {indexed} has been successfully added to [dbo].[Backup.Model.HPSanSnapshots] table'					
	end
	
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 545; END	
END
GO

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 545)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 546; END	
END
GO

---------------------------------------------------------------------------------
--Version 546
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 546)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanSnapshots]') and [name] = 'iqn')
	begin
			alter table [dbo].[Backup.Model.HPSanSnapshots] add [iqn] [nvarchar](512) default '' NOT NULL
			print 'New column {iqn} has been successfully added to [dbo].[Backup.Model.HPSanSnapshots] table'					
	end
	
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 547; END	
END
GO


---------------------------------------------------------------------------------
--Version 555
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE  current_version >= 547 AND current_version < 556)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupRepositories]') and [name] = 'total_space')
	begin
			alter table [dbo].[BackupRepositories] add total_space bigint DEFAULT -1  NOT NULL
			print 'New column {total_space} has been successfully added to [dbo].[BackupRepositories] table'
	end
	
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[BackupRepositories]') and [name] = 'free_space')
	begin
			alter table [dbo].[BackupRepositories] add free_space bigint DEFAULT -1  NOT NULL
			print 'New column {free_space} has been successfully added to [dbo].[BackupRepositories] table'
	end
	
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 556; END	
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 556 AND current_version < 559)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 559; END	
END
GO


---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 559)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.TrackedActions]') AND type in (N'U'))
	BEGIN
		CREATE TABLE [dbo].[Backup.TrackedActions] (
		[id] [uniqueidentifier] primary key NOT NULL DEFAULT (newid()),
		[lease_id] [uniqueidentifier] NOT NULL,
		[type] int NOT NULL,
		[data] xml NOT NULL,
		)
	END

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 560; END	
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 560)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanSnapshotStorages]') AND name = N'IX_Backup_Model_HpSanSnapshotStorages_storage_id')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup_Model_HpSanSnapshotStorages_storage_id] ON [dbo].[Backup.Model.HpSanSnapshotStorages]
		(
			[storage_id] ASC
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END	

	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanSnapshotStorages]') AND name = N'IX_Backup_Model_HpSanSnapshotStorages_snapshot_id')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup_Model_HpSanSnapshotStorages_snapshot_id] ON [dbo].[Backup.Model.HpSanSnapshotStorages]
		(
			[snapshot_id] ASC
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END	

	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanVolumeBackups]') AND name = N'IX_Backup_Model_HpSanVolumeBackups_backup_id')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup_Model_HpSanVolumeBackups_backup_id] ON [dbo].[Backup.Model.HpSanVolumeBackups]
		(
			[backup_id] ASC
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END	

	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HpSanVolumeBackups]') AND name = N'IX_Backup_Model_HpSanVolumeBackups_volume_id')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup_Model_HpSanVolumeBackups_volume_id] ON [dbo].[Backup.Model.HpSanVolumeBackups]
		(
			[volume_id] ASC
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END	

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 561; END	
END
GO


---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 561 AND current_version < 567)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 567; END	
END
GO

-----------------------------------------------------
-- 
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 567)
BEGIN
    alter table [dbo].[Backup.TrackedActions.Leases] add aux_data xml DEFAULT null
    print 'New column {aux_data} has been successfully added to [dbo].[Backup.TrackedActions.Leases] table'
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 568; END
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 568 AND current_version < 576)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 576; END	
END
GO

-----------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 576)
BEGIN
    alter table [dbo].[Backup.Model.HPSanVolumes] add size bigint DEFAULT -1  NOT NULL
    print 'New column {size} has been successfully added to [dbo].[Backup.Model.HPSanVolumes] table'
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 577; END
END
GO

-----------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 577)
BEGIN
    alter table [dbo].[Backup.Model.HPSanClusters] add space_total bigint DEFAULT -1  NOT NULL
    print 'New column {space_total} has been successfully added to [dbo].[Backup.Model.HPSanClusters] table'

	alter table [dbo].[Backup.Model.HPSanClusters] add space_free bigint DEFAULT -1  NOT NULL
    print 'New column {space_free} has been successfully added to [dbo].[Backup.Model.HPSanClusters] table'
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 578; END
END
GO

-----------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 578 AND current_version < 581)
BEGIN
    alter table [dbo].[Backup.Model.HPSanVolumes] add is_thin_provision bit DEFAULT 0  NOT NULL
    print 'New column {is_thin_provision} has been successfully added to [dbo].[Backup.Model.HPSanVolumes] table'

	alter table [dbo].[Backup.Model.HPSanVolumes] add consumed_space bigint DEFAULT -1  NOT NULL
    print 'New column {consumed_space} has been successfully added to [dbo].[Backup.Model.HPSanVolumes] table'

	alter table [dbo].[Backup.Model.HPSanVolumes] add saved_space bigint DEFAULT -1  NOT NULL
    print 'New column {saved_space} has been successfully added to [dbo].[Backup.Model.HPSanVolumes] table'	

	alter table [dbo].[Backup.Model.HPSanSnapshots] add consumed_space bigint DEFAULT -1  NOT NULL
    print 'New column {consumed_space} has been successfully added to [dbo].[Backup.Model.HPSanSnapshots] table'	

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 581; END
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 581 AND current_version < 589)
BEGIN	
	alter table [dbo].[Backup.Model.HPSanSnapshots] add vmfs_version int DEFAULT -1  NOT null
	print 'New column {vmfs_version} has been successfully added to [dbo].[Backup.Model.HPSanSnapshots] table'						
	
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 589; END	
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 589 AND current_version < 595)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[Hosts]') and [name] = 'dns_name')
	begin
			alter table [dbo].Hosts add [dns_name] nvarchar(255) DEFAULT null
			print 'New column {dns_name} has been successfully added to dbo.Hosts table'					
	end
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 595; END	
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 595 AND current_version < 598)
BEGIN
	if not exists (select * from syscolumns where id = OBJECT_ID(N'[dbo].[LicensedHosts]') and [name] = 'cores')
	begin
		alter table dbo.LicensedHosts add cores int DEFAULT 0 NOT null
		print 'New column {cores} has been successfully added to dbo.LicensedHosts table'
	end
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 598; END	
END
GO


---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 598 AND current_version < 605)
BEGIN
	declare @usn bigint

	exec [dbo].[IncrementUsn] @usn OUTPUT
	INSERT INTO [dbo].[Backup.Model.Session.Filters] ([id],[name],[data],[usn])
	VALUES('D2F0F072-1CA9-40C0-AFD1-56B3DE9AA366',
		   'Snapshot',
		   '<?xml version="1.0"?><ReportCriteria><Criterions><string>([job_type] = 23)</string></Criterions><Order><Ascending>false</Ascending><PropertyName>creation_time</PropertyName></Order></ReportCriteria>'
		   ,@usn)
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 605; END	
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 605 AND current_version < 607)
BEGIN
	alter table [dbo].[Backup.Model.HPSanSnapshots] add app_managed bit DEFAULT 0  NOT NULL
    print 'New column {app_managed} has been successfully added to [dbo].[Backup.Model.HPSanSnapshots] table'

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 607; END	
END
GO

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 607 AND current_version < 613)
BEGIN

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.HPSanStorageSystems]') AND type in (N'U'))
BEGIN
		CREATE TABLE [dbo].[Backup.Model.HPSanStorageSystems](
		 [id] [uniqueidentifier] NOT NULL,
		 [name] [nvarchar](255) NOT NULL,
		 [cluster_id] [uniqueidentifier] NOT NULL,		 
		 [eth0_ip] [nvarchar](255) NOT NULL,
		 [eth1_ip] [nvarchar](255) NOT NULL,
		 CONSTRAINT [PK_Backup.HPSanStorageSystems] PRIMARY KEY CLUSTERED 
		(
		 [id] ASC
		)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
		) ON [PRIMARY]
END

	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 613; END
END
GO

---------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 613 AND current_version < 617)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ReplicationInfo]') and [name] = 'em_name')
	begin
			alter table [dbo].[ReplicationInfo] add [em_name] nvarchar(255) DEFAULT null
			print 'New column {em_name} has been successfully added to dbo.ReplicationInfo table'					
	end
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 617; END	
END
GO


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 617 AND current_version < 620)
BEGIN
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID(N'[dbo].[Backup.Model.BackupJobSessions]') AND [name] = 'will_be_retried')
	BEGIN
		ALTER TABLE [dbo].[Backup.Model.BackupJobSessions] ADD will_be_retried bit DEFAULT 0 not null
		print 'New column ''will_be_retried'' has been successfully added to dbo.Backup.Model.BackupJobSessions table'
	END

	
IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 620; END	
END		
GO


IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 620 AND current_version < 625)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 625; END	
END
GO


--
-----------------------------------------------------
--
-- BEGIN UPGRADE DATA FROM 6.1 TO 6.5
--
-- Condition: 625
--
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 625 AND current_version < 628)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 628; END
END
GO

--
-----------------------------------------------------
--
-- END UPGRADE DATA
--
-----------------------------------------------------
--

IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 628)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[ReplicationInfo]') and [name] = 'em_version')
	begin
			alter table [dbo].[ReplicationInfo] add [em_version] nvarchar(255) DEFAULT null
			print 'New column {em_version} has been successfully added to dbo.ReplicationInfo table'					
	end
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 629; END	
END
GO

--IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 629)
--BEGIN
--	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 630; END	
--END
--GO

-----------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 629 AND current_version < 632)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 632; END	
END
GO

-----------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 632)
BEGIN
	IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Backup.Model.BackupTaskSessions]') AND name = N'IX_Backup.Model.BackupTaskSessions_SessionId')
	BEGIN
		CREATE NONCLUSTERED INDEX [IX_Backup.Model.BackupTaskSessions_SessionId] ON dbo.[Backup.Model.BackupTaskSessions]
		(
			[session_id]
		) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	END
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 633; END	
END
GO

-----------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version = 633)
BEGIN
	if NOT EXISTS (select * from syscolumns where id = OBJECT_ID(N'[dbo].[VmWareSnapshots]') and [name] = 'job_id')
	begin
			alter table [dbo].[VmWareSnapshots] add [job_id]  [uniqueidentifier] not null default ('00000000-0000-0000-0000-000000000000')
			print 'New column {job_id} has been successfully added to dbo.VmWareSnapshots table'					
	end
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 634; END	
END
GO

-----------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM [dbo].[Version] WHERE current_version >= 634 AND current_version < 638)
BEGIN
	IF @@Error = 0 BEGIN UPDATE [dbo].[Version] SET current_version = 638; END	
END
GO
