DECLARE @constraint nvarchar(50)
DECLARE @sql nvarchar(255)

select @constraint = c.name from sys.all_columns a
inner join sys.tables b on a.object_id = b.object_id
inner join sys.default_constraints c on a.default_object_id = c.object_id
where b.name='Principals' and a.name = 'AccountEnabled'

if @constraint IS NOT NULL
begin
	SET @sql = 'ALTER TABLE Principals DROP CONSTRAINT ' + @constraint
	exec sp_executesql @sql
end
ALTER TABLE [dbo].[Principals] ADD CONSTRAINT [DF_Principals_AccountEnabled] DEFAULT (1) FOR [AccountEnabled]

DECLARE @constraintExternalUser nvarchar(50)
DECLARE @sqlExternalUser nvarchar(255)

select @constraintExternalUser = c.name from sys.all_columns a
inner join sys.tables b on a.object_id = b.object_id
inner join sys.default_constraints c on a.default_object_id = c.object_id
where b.name='Principals' and a.name = 'ExternalUser'

if @constraintExternalUser IS NOT NULL
begin
	SET @sqlExternalUser = 'ALTER TABLE Principals DROP CONSTRAINT ' + @constraintExternalUser
	exec sp_executesql @sqlExternalUser
end
ALTER TABLE [dbo].[Principals] ADD CONSTRAINT [DF_Principals_ExternalUser] DEFAULT (0) FOR [ExternalUser]

DECLARE @constraintIsPartner nvarchar(50)
DECLARE @sqlIsPartner nvarchar(255)

select @constraintIsPartner = c.name from sys.all_columns a
inner join sys.tables b on a.object_id = b.object_id
inner join sys.default_constraints c on a.default_object_id = c.object_id
where b.name='WebApplications' and a.name = 'IsPartner'

if @constraintIsPartner IS NOT NULL
begin
	SET @sqlIsPartner = 'ALTER TABLE WebApplications DROP CONSTRAINT ' + @constraintIsPartner
	exec sp_executesql @sqlIsPartner
end
ALTER TABLE [dbo].[WebApplications] ADD CONSTRAINT [DF_WebApplications_IsPartner] DEFAULT (0) FOR [IsPartner]

DECLARE @constraintUseOrganizationalAccount nvarchar(50)
DECLARE @sqlIsUseOrganizationalAccount nvarchar(255)

select @constraintUseOrganizationalAccount = c.name from sys.all_columns a
inner join sys.tables b on a.object_id = b.object_id
inner join sys.default_constraints c on a.default_object_id = c.object_id
where b.name='WebApplications' and a.name = 'UseOrganizationalAccount'

if @constraintUseOrganizationalAccount IS NOT NULL
begin
	SET @sqlIsUseOrganizationalAccount = 'ALTER TABLE WebApplications DROP CONSTRAINT ' + @constraintUseOrganizationalAccount
	exec sp_executesql @sqlIsUseOrganizationalAccount
end
ALTER TABLE [dbo].[WebApplications] ADD CONSTRAINT [DF_WebApplications_UseOrganizationalAccount] DEFAULT (0) FOR [UseOrganizationalAccount]

DROP TABLE [dbo].[PermissionScopeAlterations]

UPDATE Options SET OptionValue = '5.1.5' WHERE OptionID = 14;